Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django create profile for user signal
im trying to create profile for user account using signals but after writing the codes is not creating at all Django 3.0.5 users/models.py from django.db import models from django.contrib.auth.models import User from PIL import Image# class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) profile_image = models.ImageField(default='default.jpg', upload_to='profile_pics') def __str__(self): return f'{self.user.username} Profile' def save(self): super().save() img = Image.open(self.profile_image.path) if img.height > 300 or img.width > 300: output_size = (300, 300) img.thumbnail(output_size) img.save(self.profile_image.path) users/signals.py from django.contrib.auth.models import User from django.db.models.signals import post_save from django.dispatch import receiver from .models import Profile @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) @receiver(post_save, sender=User) def save_user_profile(sender, instance, **kwargs): instance.profile.save() users/apps.py from django.apps import AppConfig class UsersConfig(AppConfig): name = 'users' def ready(self): import users.signals i check all the option on internet , but cant make this work , can any one help, maybe i missing something in my codes settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'users', 'courses', 'crispy_forms', ] -
How can I unittest get_context_data() of a ListView in Django?
I tried to write a unittest for a ListView in Django 3.0.5. I need to check the data included in the context. The Application is running for this view, so error in implementation is not likely. But what did I missed when setting up my test? Here parts of my source: urls.py: app_name = 'gene' urlpatterns = [ path('persons/', views.PersonList.as_view(), name='person-list'), ... ] views.py from django.views.generic.list import ListView from gene.models import Person class PersonList(ListView): model = Person def get_context_data(self, **kwargs): context = super(PersonList, self).get_context_data(**kwargs) # this is line 11 ... return context tests.py: from django.test import TestCase, RequestFactory from django.urls import reverse from gene.models import Person from gene.views import PersonList class PersonListTest(TestCase): def setUp(self): person1 = Person.objects.create(name="Person 1") person2 = Person.objects.create(name="Person 2") def test_context(self): request = RequestFactory().get(reverse('gene:person-list')) view = PersonList() view.setup(request) context = view.get_context_data() # this is line 20, Error here self.assertIn('environment', context) I followed the guides from official documentation. But when I run this test I get following on console: Error Traceback (most recent call last): File "/home/macbarfuss/PycharmProjects/Genealogy/gene/tests.py", line 20, in test_context context = view.get_context_data() File "/home/macbarfuss/PycharmProjects/Genealogy/gene/views.py", line 11, in get_context_data context = super(PersonList, self).get_context_data(**kwargs) File "/home/macbarfuss/PycharmProjects/Genealogy/venv/lib/python3.8/site-packages/django/views/generic/list.py", line 115, in get_context_data queryset = object_list if object_list is not None … -
Discord.py - 'NoneType' object has no attribute 'voice_state'
Thought this was going to be fairly simple but clearly not, the guild I'm passing into join_guild is a Django Model Object. In _join_guild I'm trying to get the first VoiceChannel for the guild and simply connect the bot to it. However, been getting the following error for ages. Any help on where I'm going wrong or what's happening here would help. Error: Traceback (most recent call last): File ".../env/lib/python3.8/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File ".../env/lib/python3.8/site-packages/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File ".../env/lib/python3.8/site-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File ".../soundboard/sound/views.py", line 41, in play_guild_sound join_guild(guild) File ".../soundboard/sound/discord.py", line 38, in join_guild loop.run_until_complete(_join_guild(guild)) File "/usr/lib/python3.8/asyncio/base_events.py", line 608, in run_until_complete return future.result() File ".../soundboard/sound/discord.py", line 32, in _join_guild await first_channel.connect() File ".../env/lib/python3.8/site-packages/discord/abc.py", line 1066, in connect await voice.connect(reconnect=reconnect) File ".../env/lib/python3.8/site-packages/discord/voice_client.py", line 219, in connect await self.start_handshake() File ".../env/lib/python3.8/site-packages/discord/voice_client.py", line 152, in start_handshake await ws.voice_state(guild_id, channel_id) AttributeError: 'NoneType' object has no attribute 'voice_state' Code: import asyncio from discord import Client, VoiceChannel client = Client() def voice_channels(channels): r = [channel for channel in channels if isinstance(channel, VoiceChannel)] r.sort(key=lambda c: (c.position, c.id)) return r async def _join_guild(guild): await client.login(token=settings.BOT_TOKEN) disc_guild = await client.fetch_guild(guild.guild_id) channels = … -
i stuck with these error in django there all command work but if i want start server these error occur
Unable to create process using 'C:\Users\Bunty Waghmare\Desktop\env_site\Scripts\python.exe manage.py runserverenter image description here -
Django TabularInline with custom inner formset
In the Django admin I have a TabularInline (WhitholdingModel) form that has three attributes, one of them is a Model itself (CIIUModel). I want to have three different choiceFields mapping an attribute of the CIIUModel. If the user selects one field, the other should be filtered to the ones that have that attribute value. So, for example, if the first choiceField is city, and I select X city, the second choiceField must only contains values whose city is X. Besides that, I'm trying the choicefields to be stacked one below other. I have tried with formset but with no luck by now. How can I accomplish this? This is the layout I'd like to have. P.S: I'm trying not to have to handle html, so if it can be accomplished with only Python would be excelent! -
disable weasyprint django
I am working on django python and i am new to this. I just want to disable rendering pdf because it is causing trouble to me and I just want to render a normal html. How would i edit this current code I have to just let it render html instead of weasyprint pdf? from django.http import HttpResponse from django.template.loader import render_to_string from weasyprint import HTML from tests.models import Test from users.models import Sponsor from datetime import datetime def generate_report(request, test_id): test = Test.objects.get(pk=page_id) page_type = get_type(test.type) html = render_to_string(f'pdf_templates/{report_type}/pdf_{language}.html', { 'sometext': text.user.name, }) html = HTML(string=html) result = html.write_pdf() timestamp = datetime.now().isoformat(' ', 'seconds') # Creating http response response = HttpResponse(content_type='application/pdf;') response['Content-Disposition'] = f'attachment; filename={text.user.name} {timestamp}.pdf' response['Content-Transfer-Encoding'] = 'binary' with tempfile.NamedTemporaryFile(delete=True) as output: output.write(result) output.flush() output = open(output.name, 'rb') response.write(output.read()) return response -
The custom domain in my django app deployed with heroku doesn't work well
I deployed my first django application with heroku. I followed the procedure to add a custom domain ( example.com) inserting it in settings in ALLOWED_HOSTS and adding the custom domain in the heroku page. If I use the custom domain I can see the page but if I go in the subpages ( for example with the heroku domain app.herokuapp.com/subpage1) it doesn't add nothing to the URL but remains always example.com instead of example.com/subpage1. How can I fix it? -
Dango-rest-auth: no password set in admin panel
I am using rest-auth. I have create an custom RegisterSerializer and a custom user model. Registration is working properly but when I check password of user in admin panel it shows 'no password set' and when try to login it is showing { "non_field_errors": [ "Unable to log in with provided credentials." ] } models.py class CustomUserManager(BaseUserManager): def _create_user(self,username, email, password, is_staff,is_admin, is_superuser, **extra_fields): if not email: raise ValueError('Users must have an email address') if not username: raise ValueError('Users must have an username') now = timezone.now() email = self.normalize_email(email) user = self.model( email=email, username=username, is_staff=is_staff, is_active=True, is_admin=is_admin, is_superuser=is_superuser, last_login=now, date_joined=now, **extra_fields ) user.set_password(password) user.save(using=self._db) return user def create_user(self,username, email, password=None, **extra_fields): return self._create_user( username, email, password, False, False, False, **extra_fields) def create_staff(self,username, email, password, **extra_fields): user = self._create_user( username,email, password, True, False, False, **extra_fields) user.save(using=self._db) return user def create_admin(self,username, email, password, **extra_fields): user = self._create_user( username,email, password, True, True, False, **extra_fields) user.save(using=self._db) return user def create_superuser(self,username, email, password, **extra_fields): user = self._create_user( username,email, password, True, True, True, **extra_fields) user.save(using=self._db) return user class User(AbstractBaseUser): username = CharField(_('username'), max_length=100,unique=True) email = EmailField(_('email address'), unique=True) is_staff = BooleanField(default=False) is_admin = BooleanField(default=False) is_active = BooleanField(default=True) is_superuser = BooleanField(default=False) last_login = DateTimeField(auto_now=True) date_joined = DateTimeField(auto_now_add=True) … -
Django model: join and group by first element
I have two models in Django. Columns A | ------------ id name address B ------------ ------------ Columns B | ------------ id ref name date ------------ ------------ If I would have data like this: id | name | address | B -------------------------------- 1 | one | ad. | 1 id | ref | name | date ---------------------------- 1 | 1 | one_ | 1.1.2020 2 | 1 | two_ | 1.2.2020 3 | 1 | thr_ | 1.3.2020 4 | 1 | fou_ | 1.7.2020 and I would do a join I would have (join is B to ref) id_a | name | address | B | id_b | ref | name | date --------------------------------------------------------- 1 | one | ad. | 1 | 1 | 1 | one_ | 1.1.2020 1 | one | ad. | 1 | 2 | 1 | two_ | 1.2.2020 1 | one | ad. | 1 | 3 | 1 | thr_ | 1.3.2020 1 | one | ad. | 1 | 4 | 1 | fou_ | 1.7.2020 Now I would like to group by either id_a or ref and get 'last' element (either by id_b, or date) so the end results should be: … -
for object in objects add foreignkey field bulk django
So I have this AppUser model and I want to create a send_notification function that after sending a notification to mobile via firebase SDK I want it to be added to every AppUser object as ForeignKey. Think of it like every user has notification history. The main question is how do I implement it? Which path would you take if you would write this? class AppUser(TimeStampedModel): ....... notifications = models.ForeignKey( "UserNotifications", on_delete=models.CASCADE, null=True, blank=True ) ........ I tried to write something like this for test purpose from django.utils import timezone def send_notifications(request): notification = { "title": "test title", "data": "test body", "read_date": timezone.now, "date": timezone.now, } AppUser.objects.all().update(notifications?????) -
Repeate same data in different tables OR colect data from different tables in a database
What is the best practice while coding with Django: repeate same data in different tables in a database OR do not repeat and collect them in different tables? See the example below: table1 categories column0 id column1 category table2 register column0 id column1 category.table1 column2 sales_price column3 photo table3 purchases column0 id column1 id.table2 column2 photo.table2 I'm wondering what is the best: a) Include column2 in table3 and be able to extract all information from this table b) Do not include column2 in table3 and get the photo information from column3 in the table2. Thank you! -
Django template loader cannot find template after moving to another app
I'm sure you've solved a lot of similar problems already. I decided to split old_app to new_app, so: old_app will keep Models and will be handling REST (new feature) new_app will display 'regular' views (which are all class-based btw) AND will continue to utilize old_app.models for that. In order to do that I've: splitted urls.py fixed .htmls, so now they're pointing to new_app:all_items added an entry to INSTALLED_APPS moved (and renamed) whole old_app/templates/old_app directory to new_app/templates/new_app And now, I'm getting TemplateDoesNotExist because it tries to find it in new_app/templates/old_app/modelname_list.html instead of new_app/templates/new_app/modelname_list.html What I noticed is that it works, when I add option in class derived from ListView, by explicitly giving the directory: template_name = 'new_app/modelname_list.html' (new_app.views) Why it keeps tracking old directory instead of new? -
How to change the elements of navbar of User Change Page in Django Admin with Custom User model?
Below is the picture of a User Change Page of Django Admin in which the navbar of the page is marked with red color. The name of the app under which the Custom User Model is defined is : Users And the name of the Custom User model is : Custom User So the question is how to change all 4 elements (i.e. Home,Users,Custom users,custom user) of the navbar of the User Change Page of Django admin?? -
How do we print django models object value?
Hello, everyone! So, I create models in models.py file of my django project and controllers in views.py . I wrote a function called register(request) that add a new user to my database and another called login(request) that verifies if the datas sent by the user are in my db to log him in. Brief, the problem is when I want to print the user's first name in my template, it shows to me the object in string ... Here is the login(request) function: def login(request): title = 'Connexion' if request.method == 'POST': email_sent = request.POST['email'] password_sent = request.POST['password'].encode('utf-8') global isConnected user = Users.objects.filter(email = email_sent) if user and bcrypt.checkpw(password_sent, user[0].password): if isConnected in request.session: isConnected = request.session['isConnected'] return redirect('http://localhost:8000/', {'isConnected':isConnected, 'first_name':user[0].first_name, 'last_name':user[0].first_name}) else: request.session['id'] =user[0].first_name request.session['first_name'] = user[0].first_name request.session['last_name'] = user[0].first_name request.session['phone'] = user[0].first_name isConnected = True return redirect('http://localhost:8000/', {'isConnected':isConnected, 'first_name':user[0].first_name }) else: print('Something went wrong') return render(request, 'login.html', {'title':title, 'isConnected':isConnected}) return render(request, 'login.html', {'title':title, 'isConnected':isConnected}) else: return render(request, 'login.html', {'title':title, 'isConnected':isConnected }) Here is what I represent the user's first_name variable in my template: <span class="initials" style="position: relative; top: 7px; color: white;">{{ first_name }}</span> And that is it prints to me: <django.db.models.query_utils.DeferredAttribute object at 0x0000017850EE7A00> -
Google App Engine Flexible - How can I list all files in the deployed application
I am using Google App Engine Flexible and I intend to see all the files deployed for the current django application. How can I achieve this ? runtime: python env: flex entrypoint: gunicorn -t 3600 -b :$PORT project_name.wsgi beta_settings: cloud_sql_instances: 'myapp:europe-west2:myapp' runtime_config: python_version: 3 -
Can't install Psycopg2 in virtual environment
I have a django project connected to a Postgresql DB so I also need Psycopg2 package installed. For some reason, I am able to install this globally on my computer and will be able to run things properly, but when I try and install it in my virtual environment I get this long return of an error. I only installed it globally for the sake of trying to narrow down the problem. I am able to install other packages in my environment without a problem. The specific problem occurs when I switch my DB settings from SQLite to PostgreSQL and it needs psycopg2. I've also tried uninstalling PostgreSQL and installing it back in case this was installed wrong in some way, but no difference. I'm thinking it has to do with folder structure somewhere but do not have much of an idea of how to go about it or if this is a reasonable thought. ERROR: Command errored out with exit status 1: command: /Users/luis/Documents/Code/bradynce-crm/env/bin/python3 -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/private/var/folders/hw/c0r922014qg_k21_k_zmyg6h0000gn/T/pip-install-y3pelxup/psycopg2/setup.py'"'"'; __file__='"'"'/private/var/folders/hw/c0r922014qg_k21_k_zmyg6h0000gn/T/pip-install-y3pelxup/psycopg2/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' install --record /private/var/folders/hw/c0r922014qg_k21_k_zmyg6h0000gn/T/pip-record-eptfxahu/install-record.txt --single-version-externally-managed --compile --install-headers /Users/luis/Documents/Code/bradynce-crm/env/include/site/python3.8/psycopg2 cwd: /private/var/folders/hw/c0r922014qg_k21_k_zmyg6h0000gn/T/pip-install-y3pelxup/psycopg2/ Complete output (151 lines): running install running build running build_py creating … -
How do i add multiple attributes to django forms
First of all i am very new to programming but i try hard to learn and i love it :). This is my model: from django.db import models from django.contrib.auth.models import User # Create your models here. class PersoonGegevens(models.Model): # Voornaam en achternaam voornaam = models.CharField(max_length=265) achternaam = models.CharField(max_length=265) #Gender keuze MENEER = 'Mr' MEVROUW = 'Mvr' GENDER = [ ('Mr', 'Meneer'), ('Mvr', 'Mevrouw'), ] gender = models.CharField(max_length=3, choices=GENDER, default=MENEER,) #Geboortedatum geboortedatum = models.DateField(auto_now=False) #emailfield email = models.EmailField(max_length=265, unique=True) #username user = models.OneToOneField(User, on_delete=models.CASCADE) def __str__(self): return self.user.username This is my form: from django import forms from registratie.models import PersoonGegevens from django.contrib.auth.models import User class PersoonGegevensForm(forms.ModelForm): class Meta(): model = PersoonGegevens fields = ('voornaam', 'achternaam', 'gender', 'geboortedatum', 'email') class UsernameAndPasswordForm(forms.ModelForm): password = forms.CharField(widget=forms.PasswordInput) class Meta(): model = User fields = ('username', 'password') This is are my own filters: from django import template register = template.Library() @register.filter(name='addclass') def addclass(value, arg): return value.as_widget(attrs={'class': arg}) This is my HTML code for example: <div class="wrap-input100 validate-input m-b-16" > {{pg.voornaam|addclass:'input100'}} <span class="focus-input100"></span> </div> ass you see i have added a class with the filter but i also want to add other attributes and now i saw on the internet the widget code : widget = … -
Parsing and looping through multi-level JSON data in Django
I have a Django website, and I'm making a call to Etsy's API in order to display products on the website. The data has multiple levels (abbreviated below): { "results":[ { "title":"#020", "price":"5.99", "Images":[ { "url_570xN":"www.example.com/image1.jpg" } ] }, { "title":"#051", "price":"5.99", "Images":[ { "url_570xN":"www.example.com/image2.jpg" } ] }, ] } I can successfully extract data from the results part (title, price) and display it in the template, but I can't figure out how to do the same thing for the Images part (url_570xN). I've spent a few hours trying to find the proper syntax, but I've been unsuccessful. My views.py: # Note: The commented lines are the ones giving me problems. # Removing them yields no errors and displays the info I want, # minus the images def products(request): parsed_data = [] response = requests.get('https://openapi.etsy.com/v2/shops/{SHOP_ID}/listings/active?includes=Images:1:0&api_key={KEY}') etsy_data = response.json() etsy_results = etsy_data['results'] # etsy_images = etsy_data['results']['Images'] for results in etsy_results: result_data = {} result_data['title'] = results['title'] result_data['price'] = results['price'] # for Images in etsy_images: # result_data['url_570xN'] = Images['url_570xN'] parsed_data.append(result_data) return render(request, 'blog/products.html', {'data' : parsed_data}) My products.html template: {% for result in data %} <p>Title: {{result.title}} Price: {{result.price}} <img src={{result.url_570xN}} width="200px"></p> {% endfor %} And lastly, the error message I get … -
Django pass data from one model to other model based on key fields I need occ_rating from NCR model(latest value) to Fmea model,
Models.py from django.db import models from database_app.models import Add_Part,Add_Sub_Assy,Add_Defect_category,Add_Contractor_or_Supplier,Add_Process Models.py class Ncr(models.Model): date = models.DateTimeField(default=timezone.now()) Process = models.ForeignKey(Add_Process_or_Function,on_delete=models.CASCADE,null=True) Lot_qty=models.IntegerField() qty = models.IntegerField() def occ_rating(self): ppm=self.qty/self.Lot_qty*1000000 if ppm >=1 and ppm < 10: return int(2) else: return int(1) '''Fmea Model''' from database_app.models import Add_Process_or_Function,Add_Part class Fmea(models.Model): date = models.DateField(default=timezone.now()) Process = models.ForeignKey(Add_Process_or_Function,on_delete=models.CASCADE,blank=True,null=True) #function required to get the data from ncr model def occ_rating(self): if self.Process == NCR.Process: return occ_rating -
Want to show detailview, clicking in a link in a listview
I want to show the detail from a school, which will show all the students but when i run the code, it doesnt find the url, i've been searching for the answer all over the web but still dont get it, the point is to show a list of all the schools in a list.html file, that works okay, but when i want to click in an item from that list, it supposed to show the details from that school which will be all the students attending that school, but it returns a 404 error, saying that it didnt find the url. ####MODELS # Create your models here. class School(models.Model): name = models.CharField(max_length=256) principal = models.CharField(max_length=256) location = models.CharField(max_length=256) def __str__(self): return self.name class Students(models.Model): name = models.CharField(max_length=256) age = models.PositiveIntegerField() school = models.ForeignKey(School,on_delete=models.CASCADE,related_name='students') def __str__(self): return self.name ####VIEWS from django.views.generic import View,DetailView,ListView from .models import * # Create your views here. class Index(View): def get(self,request): return HttpResponse('Hello World') class SchoolList(ListView): model = School template_name = 'firstapp/list.html' context_object_name = 'School' class SchoolDetails(DetailView): model = School template_name = 'firstapp/detail.html' context_object_name = 'School_detail' ####URLS from django.urls import path from . import views urlpatterns = [ path('list/',views.SchoolList.as_view(),name='list'), path('School_detail/<int:pk>',views.SchoolDetails.as_view(),name='details') ] ####LIST HTML {%extends 'firstapp/base.html'%} … -
Is it worth it to have an meta intermediate comparison model for Django?
I'm new to Django and I want to know how to best structure my models. I have a model Computer with fields screen_size, price, company, etc.., and eventually want to have a UI that is able to compare to other Computer instances. So for example, if we're looking at ComputerA, the UI would show all other Computer instances and and compare the price, screen size, and company relative to ComputerA Wondering if it's worth it to have an intermediate model ComputerComparison, that has two foreign keys that reference both the Computer instances I'm trying to compare? -
How to create dynamic ManyToMany field in Django?
In admin add view I would like to able to select dynamically field A_permission from selected A-object while creating new B-object A(models.Model): name = models.CharField(primary_key=True, max_length=50) permission = models.CharField(max_length=50) B(models.Model): A_name = models.ForeignKey(A) A_permissions = models.ManyToManyField(A) So I have objectA1 and objectA2 for example. While creating object B I should be able to first select one of the A objects, and then just get its permission for selection in field A_permissions Can someone please point me how to do this? I feel like I tried everything -
manage.py runserver do nothing on VPS
When I run python3 manage.py runserver on Ubuntu 16.04 VPS machine it does nothing with my project but it runs that runs on my computer. I try to run python3 -v manage.py runserver and have seen that it stopped when executing this: # code object from '/usr/lib/python3.5/site-packages/OpenSSL/__pycache__/SSL.cpython-35.pyc' import 'OpenSSL.SSL' # <_frozen_importlib_external.SourceFileLoader object at 0x2b1d1d937630> # /usr/lib/python3.5/site-packages/OpenSSL/__pycache__/version.cpython-35.pyc matches /usr/lib/python3.5/site-packages/OpenSSL/version.py # code object from '/usr/lib/python3.5/site-packages/OpenSSL/__pycache__/version.cpython-35.pyc' import 'OpenSSL.version' # <_frozen_importlib_external.SourceFileLoader object at 0x2b1d1e6a5c50> import 'OpenSSL' # <_frozen_importlib_external.SourceFileLoader object at 0x2b1d1d923da0> after last line it start to do nothing my settings.py file: """ Django settings for hahachat project. Generated by 'django-admin startproject' using Django 3.0.4. For more information on this file, see https://docs.djangoproject.com/en/3.0/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.0/ref/settings/ """ import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'p#b#s#!sfv#o(o661x=kb7!-nfef&33orv%74s8*1gdi)1w1u8' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ['localhost'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django_extensions', 'main', 'rest_framework', 'rest_framework.authtoken', 'corsheaders', 'djoser', 'channels', 'room', 'chat', 'game', … -
Javascript code not working using template inheritence in Django template
I am having trouble in executing Javascript code in a Django project. The following is working fine - i.e. without using template inheritence html: <!DOCTYPE html> <html> <head> {% load static %} <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous"> <script src="https://code.jquery.com/jquery-3.4.1.slim.min.js" integrity="sha384-J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script> <script src="{% static 'ads/test.js' %}" type="text/javascript"></script> <title> Test </title> </head> <body> <form action="{% url 'test' %}" method="post" id="my_form"> {% csrf_token %} <button type="submit" class="btn btn-success">Submit</button> </form> </body> </html> test.js $(document).ready(function() { $("#my_form").submit(function(){ alert('submitted'); }); }); Since the above external Javascript file test.js has executed successfully, I assume the settings of static url, static dirs, etc. are correct. Also, since jquery has worked, I assume the order of jquery first, then js code is also correct. The problem comes when I use template inheritence. base html: <!DOCTYPE html> <html> <head> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous"> <script src="https://code.jquery.com/jquery-3.4.1.slim.min.js" integrity="sha384-J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script> {% block scripts %} {% endblock %} <title> {% block title %}{% endblock %} </title> </head> <body> {% block body %} {% endblock %} </body> </html> inherited template: {% extends "base.html" %} {% block scripts %} {% load static %} <script src="{% static 'ads/test2.js' %}" … -
Using Foreign Keys to import Images in Django
I am using Django 2.2 to make a project where designers upload designs and when I want to post them from admin, I want to choose their names and after I choose their names only their designs appear in the drop down list. So far I have reach the reach the designer name in a drop down list but I don't know how to link only their designs in the designs drop list. I am using 2 different apps: 1."Score" where designers can upload their designs 2."Core" where I can list the items First in the Score .model where designers upload the designs class Post(models.Model): designer_name = models.ForeignKey(User, on_delete=models.CASCADE) design = models.ImageField( blank=False, null=True, upload_to='new designs') title = models.CharField(max_length=100) def __str__(self): return self.title def get_absolute_url(self): return reverse("score:post-detail", kwargs={"pk": self.pk}) Second in the Core App Model: class Item(models.Model): title = models.CharField(max_length=100) description = models.TextField() price = models.FloatField() designer_name = models.ForeignKey(User, on_delete=models.CASCADE) image = models.ImageField(blank=False, upload_to='imgs') **How can I make this a drop down list with the selected user's (designer's) all previously uploaded images to choose from instead of uploading new images** def __str__(self): return self.title