Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Reverse for 'updatedata' with no arguments not found. 1 pattern(s) tried: ['updatedata/(?P<id>[0-9]+)/$']
I have a web page where it allows the users to update the existing data from the database, but when i click on the update button, it suppose to redirect the users to the next page but instead I got this error: Reverse for 'updatedata' with no arguments not found. 1 pattern(s) tried: ['updatedata/(?P[0-9]+)/$'], any idea on how to fix this issues? traceback error: Environment: Request Method: POST Request URL: http://127.0.0.1:8000/updatedata/5/ Django Version: 3.1.4 Python Version: 3.8.0 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'account.apps.AccountConfig', 'crispy_forms', 'channels'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django_session_timeout.middleware.SessionTimeoutMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Template error: In template E:\Role_based_login_system-master\templates\home.html, error at line 0 Reverse for 'updatedata' with no arguments not found. 1 pattern(s) tried: ['updatedata/(?P&lt;id&gt;[0-9]+)/$'] 1 : &lt;!doctype html&gt; 2 : &lt;html lang="en"&gt; 3 : &lt;head&gt; 4 : &lt;!-- Required meta tags --&gt; 5 : &lt;meta charset="utf-8"&gt; 6 : &lt;meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"&gt; 7 : 8 : &lt;!-- CSS --&gt; 9 : {% load static %} 10 : &lt;link rel="stylesheet" href="{% static 'style.css' %}"&gt; Traceback (most recent call last): File "C:\Users\TAY\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\TAY\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\handlers\base.py", line 179, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\TAY\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\contrib\auth\decorators.py", line 21, in _wrapped_view … -
Django ORM How to force using LEFT JOIN for Foreign key
Just another question about "How to not use raw queries?" I have two models: class User(models.Model): id = models.IntegerField(primary_key=True) name = models.CharField(max_length=100) soname = models.CharField(max_length=100) group = models.ForeignKey('Group', on_delete=models.PROTECT) class Group(models.Model): id = models.IntegerField(primary_key=True) name = models.CharField(max_length=100) Only one User with id=5 has Group (it's important). I need to implement query like this (using LEFT JOIN): SELECT * FROM User LEFT JOIN Group ON Group.id = User.category WHERE User.name LIKE '%test%' OR User.soname LIKE '%test%' OR Group.name LIKE '%test%' And i want to get all records, even with Users without Groups. But if i try to use this: _res = User.objects.filter( Q(name__icontains='test') | Q(soname__icontains='test') | Q(group__name__contains='test') ) I get only one record with id=5, because ORM generate query with INNER JOIN. Can anyone tell me if there is an easy way to get Django ORM to use LEFT JOIN without building complex constructs, writing your own query builder, and using raw queries? -
Update profile picture through clicking on picture itself Django
I'm trying to find some info online on how to update my user's profile picture on the profile page in the same way that social media applications do it, i.e. by clicking on the profile picture itself and getting asked for the file upload straight away. However, all I'm finding online is options to create a form to do that job, but then it's going to be an upload button that does the job, which isn't the same? How do I get this done: how do I get the image to be clickable and to open a file upload after I click it that would then update my model ImageField? Thanks! -
django.db.transaction.TransactionManagementError: cannot perform saving of other object in model within transaction
Can't seem to find much info about this. This is NOT happening in a django test. I'm using DATABASES = { ATOMIC_REQUESTS: True }. Within a method (in mixin I created) called by the view, I'm trying to perform something like this: def process_valid(self, view): old_id = view.object.id view.object.id = None # need a new instance in db view.object.save() old_fac = Entfac.objects.get(id=old_id) new_fac = view.object old_dets = Detfac.objects.filter(fk_ent__id__exact = old_fac.id) new_formset = view.DetFormsetClass(view.request.POST, instance=view.object, save_as_new=True) if new_formset.is_valid(): new_dets = new_formset.save() new_fac.fk_cancel = old_fac # need a fk reference to initial fac in new one old_fac.fk_cancel = new_fac # need a fk reference to new in old fac # any save() action after this crashes with TransactionManagementError new_fac.save() I do not understand this error. I already created & saved a new object in db (when I set the object.id to None & saved that). Why would creating other objects create an issue for further saves? I have tried not instantiating the new_dets objects with the Formset, but instead explicitely defining them: new_det = Detfac(...) new_det.save() But then again, any further save after that raises the error. Further details: Essentially, I have an Entfac model, and a Detfac model that has a … -
PostgreSQL (Django - Production ) - Function similarity(character varying, unknown) does not exist
I just hosted my Django website on pythonanywhere with paid account. I am using Postgresql database, Everything is working fine but TrigramSimilarity is not working. In local host everything is working fine but in production it gives error. kindly help me , i have been searching but haven't found anything. Thanks in advance. Error: Exception Value: function similarity(character varying, unknown) does not exist -
<link rel="preconnect" href="{% static 'css/custom.css' %}" type="text/css"> css don't load
It can be a silly question but in django I am using s3bucket and cloudfront to serve my static files.I am trying to use preconnect but when I use preconnect CSS don't load. <link rel="preconnect" href="{% static 'css/custom.css' %}" type="text/css">. -
Running out of quotation marks. (Django statics with document.write)
This element: <img id="img" src="{% static 'pd.jpg' %}" /> should go here: popup.document.write("<img src={% static 'pd.jpg' %} />") So think i need a third kind of quotation marks, or ? popup.document.write(String(<img src="{% static 'pd.jpg' %}" />)) at least is not working. -
Django Class Based Views Forbidden (Referer checking failed - no Referer.) - webhook
I have made a class based view to act a webhook but whenever a request comes in I get Forbidden (Referer checking failed - no Referer.): /gc_callback/ I do have the csrf_exempt decorator for dispatch but it seems it does nothing def dispatch(self, *args, **kwargs): return super(Webhook, self).dispatch(*args, **kwargs) Any suggestions? -
Django ModelForm - ManyToMany nested selection
I'm building a Django application and I'm facing an issue I don't know how to solve... I'll try to explain it as clear as I can. I've got an app called "Impostazioni" which has a model called "AnniScolastici": class AnniScolastici(models.Model): nome = models.CharField(max_length=50) class Meta: verbose_name = "Anno scolastico" verbose_name_plural = "Anni scolastici" def __str__(self): return f"{self.nome}" I also have another app called "Attivita" which has a model called "Laboratori": class Laboratori(models.Model): nome = models.CharField(max_length=25) durata = models.IntegerField(default=0) anniscolastici = models.ManyToManyField(AnniScolastici) note = models.TextField(null=True, blank=True) class Meta: verbose_name = "Laboratorio" verbose_name_plural = "Laboratori" def __str__(self): return f"{self.nome}" I've coded up another model called "RichiesteLaboratori" which is related to different models in my Django app (and on the two above, of course): class RichiesteLaboratori(models.Model): date_added = models.DateTimeField(auto_now_add=True) date_valid = models.DateTimeField(null=True, blank=True) provincia = models.ForeignKey("impostazioni.Province", related_name="richiesta_provincia", null=True, on_delete=models.CASCADE) istituto = models.ForeignKey("contatti.Istituto", related_name="richiesta_istituto", null=True, on_delete=models.CASCADE) plesso = models.ForeignKey("contatti.Plesso", related_name="richiesta_plesso", null=True, on_delete=models.CASCADE) classe = models.CharField(max_length=25) numero_studenti = models.PositiveIntegerField() nome_referente = models.CharField(max_length=50) cognome_referente = models.CharField(max_length=50) email = models.EmailField() telefono = models.CharField(max_length=20) termini_servizio = models.BooleanField() classi_attivita = models.ManyToManyField(AnniScolastici, related_name="richiesta_anniScolastici") laboratori = models.ManyToManyField(Laboratori) note = models.TextField(null=True, blank=True) approvato = models.BooleanField(default=False) class Meta: verbose_name = "Richiesta - Laboratorio" verbose_name_plural = "Richieste - Laboratorio" def __str__(self): return f"{self.pk}" I'm … -
POST method doesn't recieve any information from Form (DJANGO & BOOTSTRAP)
I have a form which registers a new user, I used Bootstrap 5 to make it look nice. However, when I press the submit button the form does not validate. The error it shows when I write print(form.errors) says that every field is required, which means it didn't recieve anything. Why does this happen? This is my code: HTML <div class="card" id='signup_card'> <div class='card-header'> <h2 class='card-title'>Sign Up</h2> </div> <div class='card-body'> <form method='POST' action="" id='create_user_form' style="color: #fff;"> {% csrf_token %} <label for='usernameInput' class="form-label">{{form.username.label}}:</label> <input type="text" id='usernameInput' style="margin-bottom: 20px;"> <label for='phoneNumberInput' class="form-label">{{form.phone_number.label}}:</label> <input type="text" id='phoneNumberInput' style="margin-bottom: 20px;"> <label for='emailInput' class="form-label">{{form.email.label}}:</label> <input type="text" id='emailInput' style="margin-bottom: 20px;"> <label for='password1Input' class="form-label">{{form.password1.label}}:</label> <input type="text" id='password1Input' style="margin-bottom: 20px;"> <label for='password2Input' class="form-label">{{form.password2.label}}:</label> <input type="text" id='password2Input' style="margin-bottom: 20px;"> <button class="btn btn-primary" type='submit'>Submit</button> </form> </div> models.py class Account(User): phone_number = BigIntegerField() forms.py class CreateAccountForm(UserCreationForm): class Meta: model = Account fields = ['username', 'email', 'phone_number', 'password1', 'password2'] views.py def signup(request): if request.method == 'GET': form = CreateAccountForm() ctx = { 'form':form } return render(request, 'signup.html', ctx) if request.method == 'POST': form = CreateAccountForm(request.POST) if form.is_valid(): form.save() else: print(form.errors) return render(request, 'index.html') -
Python Environ Django - How to specify to read a different dot env file for dev, test and prod?
Background As I am getting ready for Django deployment to production, I realized that I need to split my settings.py file into different environments. I am trying to have each environment's settings file read a different .env file for that specific environment. Like such: As seen in the documentation # website.settings.dev from .common import * import environ env = environ.Env() # Take environment variables from .env file environ.Env.read_env('.env.dev', recurse=False) print(env('SECRET_KEY')) # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = env('SECRET_KEY') # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ... Issue The .env.dev file is never read and my SECRET_KEY env variable is never loaded onto the system, with python manage.py check, I get the following: File "C:\website\settings\dev.py", line 10, in <module> print(env('SECRET_KEY')) File "C:\project\virtual-env\lib\site-packages\environ\environ.py", line 165, in __call__ return self.get_value( File "C:\project\virtual-env\lib\site-packages\environ\environ.py", line 361, in get_value raise ImproperlyConfigured(error_msg) django.core.exceptions.ImproperlyConfigured: Set the SECRET_KEY environment variable (virtual-env) PS C:\project> However, if I were to rename my .env file back to .env and read the file with environ.Env.read_env() Everything works, and my print statement prints out my secret key. Question Why can't environ read the specified file? How to specify a file for … -
How do I reference my model in a nested folder structure to dump data in Django 3.2?
I'm using Django 3.2 and Python 3.9. I have this project directory setup + cbapp - manage.py - settings.py + models - __init__.py - crypto_currency.py In my settings.py file, I have INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'cbapp', ] I want to dump some data to a fixtures file, so I tried $ python3 manage.py dumpdata cbapp.models.crypto_currency > ./cbapp/fixtures/crypto_currency.json CommandError: No installed app with label 'cbapp.models.crypto_currency'. What's the proper way to reference my model to dump data? -
How to load editorJs scripts integrated with django after an ajax call?
I am using editorJs for my description field as follows: epic_description = EditorJsField( editorjs_config={ "tools": { "Image": { "config": { "endpoints": { "byFile": "/imageUlaod/", "byUrl": "/imageUlaod/", }, "additionalRequestHeader": [ {"content-Type": "multipart/form-data"} ], } }, "Attaches": { "config": { "endpoint": "/fileUPload/", } }, } }, blank=True, null=True, ) But I also call this form of this field via ajax to load it. And it turns out that the script for the editorJs is not loaded at all. When I looked to my console it uses the cdn url https://cdn.jsdelivr.net/sm/jsdelivr-separator.js. Now I have no idea how to solve this issue since I do not know what script to load in the first place I check at the url to see if I can download the js file. Eiih nothing. Any help would be appreciated highly. -
'WSGIRequest' object has no attribute 'get'... API link from google
I am trying to use the Books APIs from google to import books to the website and save them in the database. Unfortunately, I have a problem with the get method and I don't know where the problem is. I get an error like in the subject. search_url = "https://www.googleapis.com/books/v1/volumes?q=search+terms" params = { 'q': 'Hobbit', 'key': settings.BOOK_DATA_API_KEY } r = request.get(search_url, params=params) print(r.text) return render(request, "BookApp/book_import.html")``` -
Trouble starting Django project w/o errors
This is the original code in urls.py. Similarly, errors in view.py, and the app url.py files automatically appear whenever I start a project in django (3.2.8). I've just begun coding, no one I've asked can answer why. HELP! from django.contrib import admin from django.urls import path -
conexion django con base de datos 4Dimension
quiero conectarme con la base de datos 4Dimension desde django. alguien tiene alguna idea de como hacerlo en solo lectura? -
stale token even for first time user Djoser and DRF
the newly registered user get email for activation . He clicks on the links and move to an activation page .then he clicks on verify button which take uid and token from the link and post it to auth/users/activation/ and then gets the response stale token for the given user no matter how fast he click on the link on verify link . result is same. I am using djoser for activation and all user related stuff.and redux in the frontend for api calls and also the React as frontend here is my settings.py: DJOSER = { 'LOGIN_FIELD': 'email', 'USERNAME_CHANGED_EMAIL_CONFIRMATION': True, 'PASSWORD_CHANGED_EMAIL_CONFIRMATION': True, 'SEND_CONFIRMATION_EMAIL': True, 'SET_USERNAME_RETYPE': True, 'SET_PASSWORD_RETYPE': True, 'PASSWORD_CHANGED_EMAIL_CONFIRMATION':True, 'PASSWORD_RESET_CONFIRM_URL': 'password/reset/confirm/{uid}/{token}', 'SEND_ACTIVATION_EMAIL': True, 'ACTIVATION_URL': 'activate/{uid}/{token}', 'SOCIAL_AUTH_TOKEN_STRATEGY': 'djoser.social.token.jwt.TokenStrategy', 'SOCIAL_AUTH_ALLOWED_REDIRECT_URIS': ['https://negoziohub.herokuapp.com/google', 'http://127.0.0.1:8000/facebook'], 'SERIALIZERS': { 'user_create': 'base.serializers.UserSerializer', 'user': 'base.serializers.UserSerializer', 'user_delete': 'djoser.serializers.UserDeleteSerializer', } } here is userAction.js: export const activate = (uid, token) => async (dispatch) => { try { dispatch({ type: USER_ACTIVATE_REQUEST }) const config = { headers: { 'Content-type': 'application/json', } } const body = JSON.stringify({ uid, token }); const { data } = await axios.post(`/auth/users/activation/`, body, config ) dispatch({ type: USER_ACTIVATE_SUCCESS, payload: data }) // dispatch(login()) localStorage.setItem('userInfo', JSON.stringify(data)) } catch (error) { dispatch({ type: USER_ACTIVATE_FAIL, payload: error.response && error.response.data.detail ? … -
Upgrade Django with incompatible migrations
I'm tasked with upgrading the Django version for a project that currently uses Django 2.2.24. It contains a model (with existing migrations) that looks roughly like this: class Membership(models.Model): person = models.ForeignKey(Person, on_delete=models.CASCADE) type = models.ForeignKey(MembershipType, on_delete=None) Starting with Django 3.0, on_delete=None causes an error since on_delete is supposed to be a callable. In order to avoid the error, both the model and the existing migrations have to be changed. By itself, it's not an issue to change the model like this: class Membership(models.Model): person = models.ForeignKey(Person, on_delete=models.CASCADE) type = models.ForeignKey(MembershipType, on_delete=models.SET_NULL, null=True) But existing databases are not yet aware that the corresponding field can be nullable, so a new migration is required for that. The best way I currently see to do this is the following: change the model create&apply a migration using Django 2.2.24 change the old migrations manually Is there a more elegant way to solve this issue? -
How can I test delete view in Django app?
I want to test my View but I have problem with my delete function. class AnimalView(APIView): def delete(self, request, format = None): id = int(request.GET.get('id')) try: animal = Animal.objects.get(id=id) except: return Response(status=status.HTTP_404_NOT_FOUND) animal.delete() return Response(status=status.HTTP_204_NO_CONTENT) This is my model: class Animal(models.Model): name = models.CharField(unique=True, max_length=30, blank=False, null=False) class Meta: managed = True db_table = 'animal' ordering = ['name'] def __str__(self): return str(self.name) and this is the test that I'm trying to make: class TestURL(TestCase): def setUp(self): self.client = Client() def test_animal_delete(self): animal = Animal.objects.create(name = 'TestAnimal') response = self.client.delete(reverse("category_animal"), json.dumps({'id' : animal.id})) self.assertEqual(status.HTTP_204_NO_CONTENT,response.status_code ) But I'm getting a TypeError: int() argument must be a string, a bytes-like object or a number, not 'NoneType' Can you please help me with my test? -
Use template date filters in custom template tag?
I want to use Django template date filters inside a custom template tag. Is that possible? My end goal is to be able to use it like this: {{parcel.pickup_dates|delivery_dates_formating}} Problem is, that "pickup_dates" can be array of 1 or 2 or 3 elements. My desired output is: "Sunday, 21 September" if one element, "Satardau - Sunday, 21-22 September" if 2 elements, "Friday - Sunday, 20-22 September" if 3 elements, Currenly my temlpate tag looks like this: def delivery_dates_formating(value): if len(value) == 1: return [value[0]] if len(value) == 2: return [value[0], value[1]] if len(value) == 3: return [value[0], value[2]] And in template I used to use something like: {{parcel.delivery_date|date:'E j, l'|capfirst}} I woul like to use django tempaltes date filtes, as it handels localisation. Is that possible? -
Where do Django's Field's "default" and test's "client" parameters come from?
If you search for the parameters of a Field (e.g. IntergField) in Django through from django.db import models dir(models.IntegerField) you get 'default_error_messages', 'default_validators', 'unique', 'validate', 'validators', etc, but not "default" itself, although it's commonly used, as in class Choice(models.Model): ... votes = models.IntegerField(default=0) Same thing with "client". The docs say TestCase "comes with its own client". In this snippet from Django's docs, this client is explored class QuestionIndexViewTests(TestCase): def test_no_questions(self): """ If no questions exist, an appropriate message is displayed. """ response = self.client.get(reverse('polls:index')) but you can't find it through from django.test import TestCase dir(django.test.TestCase) or even dir(django.test.TestCase.client_class) I'm asking where they come from, but also how to search for these "hidden" parameters, methods, etc. -
Django call SOAP API
I made a CRM and now the company wants to set up their API, but it's a SOAP API who uses XML and after a little research here in Stack, some people said to use zeep, and didn't work. I'm trying first from a separate file to put in the CRM later (maybe not the best idea) but I think I'm doing wrong/more than I need to. Is it right to do this way or is there a better way ? from zeep import Client client = Client('httsp://company.com/?wsdl') element1 = client.get_element('ns0:E1') element2 = client.get_element('ns1:E2') element3 = client.get_element('ns2:E3') element4 = client.get_element('ns3:E4') element5 = client.get_element('ns4:E5') element6 = client.get_element('ns5:E6') element7 = client.get_element('ns6:E7') element8 = client.get_element('ns7:E8') element9 = client.get_element('ns8:E9') obj1 = element1(E1 = 'A') obj2 = element2(E2 = 'B') ... obj9 = element9(E9 = 'I') header_value = header(username='user', password='pass') client.service.Companymethod(_soapheader={heaeder_value, obj1, obj2, ... obj9}) XML: <definitions targetNamespace="http://X/soap/X"> <types> <xsd:schema targetNamespace="http://X/soap/X"> <xsd:import namespace="http://schemas.xmlsoap.org/soap/encoding/"/> <xsd:import namespace="http://schemas.xmlsoap.org/wsdl/"/> <xsd:complexType name="Companymethod"> <xsd:all> <xsd:element name="YRequest" type="tns:YRequest" minOccurs="1"/> </xsd:all> </xsd:complexType> <xsd:complexType name="YRequest"> <xsd:all> <xsd:element name="E1" type="xsd:string" minOccurs="1" maxOccurs="1"/> <xsd:element name="E2" type="xsd:nonNegativeInteger" minOccurs="1" maxOccurs="1"/> <xsd:element name="E3" type="xsd:string" minOccurs="1" maxOccurs="1"/> <xsd:element name="E4" type="xsd:string" minOccurs="1" maxOccurs="1"/> <xsd:element name="E5" type="xsd:nonNegativeInteger" minOccurs="1" maxOccurs="1"/> <xsd:element name="E6" type="xsd:boolean" minOccurs="0" maxOccurs="1"/> <xsd:element name="E7" type="xsd:nonNegativeInteger" minOccurs="0" maxOccurs="1"/> <xsd:element name="E8" type="xsd:nonNegativeInteger" … -
Custom User Model Django Error , No such table
Models.py class UserManager(BaseUserManager): def create_user(self, email, password=None): if not email: raise ValueError('Users must have an email address') user = self.model( email=self.normalize_email(email), ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, password): user = self.create_user( email, password=password, ) user.staff = True user.admin = True user.save(using=self._db) return user class User(AbstractBaseUser): email = models.EmailField( verbose_name='email address', max_length=255, unique=True, ) is_active = models.BooleanField(default=True) staff = models.BooleanField(default=False) # a admin user; non super-user admin = models.BooleanField(default=False) # a superuser phone = models.IntegerField() USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] def get_full_name(self): return self.email def get_short_name(self): return self.email def __str__(self): return self.email def has_perm(self, perm, obj=None): return True def has_module_perms(self, app_label): return True @property def is_staff(self): return self.staff @property def is_admin(self): return self.admin objects = UserManager() Settings.py AUTH_USER_MODEL = 'Accounts.User' Error: return Database.Cursor.execute(self, query, params) django.db.utils.OperationalError: no such table: Accounts_user I have created a Model User, but when I tried to create a superuser, i got an error, that table does not exist, I have tried makemigrations and migrate command multiple times, but nothing seems to solve the issue i can't even open the table even in the admin pannel, can someone help me solve this issue -
Django implicit field naming for class with query expression - how does it work?
Simplified example of what I wrote today: class Grandparent(models.Model): text = models.CharField(max_length=5, choices=too_many) class Parent(models.Model): grandparent = models.ForeignKey(Grandparent, on_delete=models.CASCADE) info = models.CharField(max_length=30) class ChildSomething(models.Model): parent = models.ForeignKey(Parent, on_delete=models.CASCADE) data = models.CharField(max_length=5, choices=chromosome_identities) Given a specific Grandparent object, I wanted to order Parent objects underneath it by most ChildSomething's each Parent has, which I did successfully below. grandparent = Grandparent.objects.get(id=32923) # arbitrary id # This query produces the desired result parents = ( Parent.objects.filter(grandparent=grandparent). annotate(num_child_somethings = Count('childsomething')). order_by('num_child_somethings') ) My question: Why is it Count('childsomething') instead of Count('child_something')? The latter was my intuition, which was corrected by a helpful Django error message: Exception Type: FieldError Exception Value: Cannot resolve keyword 'user_translation' into field. Choices are: id, translate_text, translate_text_id, translation, usertranslation The answer to this is likely simple, I just couldn't find anything in the docs related to this. How does the naming convention work? If anyone knows of the appropriate Django docs link that would be ideal. Thank you. -
Django Webpack static not finding file
I created a Django application and tried to serve files via webpack. Now the application can't find those files despite setting the required constants in settings.py. The output folder is right in the root directory and should be picked up by STATICFILES_DIRS, but if I start the application I get a 404 not found error. I'm outputting my files via webpack inside the root folder in /dist/js/*.js webpack.config.js const webpack = require('webpack'); const glob = require('glob'); let globOptions = { ignore: ['node_modules/**', 'venv/**'] } let entryFiles = glob.sync("**/javascript/*.js", globOptions) let entryObj = {}; entryFiles.forEach(function(file){ if (file.includes('.')) { let parts = file.split('/') let path = parts.pop() let fileName = path.split('.')[0]; entryObj[fileName] = `./${file}`; } }); const config = { mode: process.env.NODE_ENV, entry: entryObj, output: { path: __dirname + '/dist/js', filename: '[name].js' }, optimization: { minimize: false } } module.exports = config settings.py BASE_DIR = Path(__file__).resolve().parent.parent STATIC_URL = "/static/" STATICFILES_DIRS = [ ("js", f"{BASE_DIR}/dist/js"), ] STATIC_ROOT = os.path.join(BASE_DIR, "staticfiles") main.html: {% load static %} <!DOCTYPE html> <html lang="de"> <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> </head> <body> {% block content %} {% endblock %} </body> <!-- Load bundled webpack script --> <script src="{% static 'main.js' %}" …