Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Fixing a NoReverseMatch in a Django Project for Registration
Hi I keep getting NoReverseMatch at /users/register/ however I am have followed the step by step for fixing this error: Here is the urls.py app_name = 'tac' urlpatterns = [ path('terms-and-conditions/', TermsAndConditionsView.as_view(), namespace='terms_and_conditions'), path('user-agreement/', UserAgreementView.as_view(), namespace='user_agreement'), ] Here is the register.html that is causing the error: <label class="form-check-label" for="terms_and_conditions">I agree to the <a href="{% url 'tac:terms_and_conditions' %}">terms and conditions</a> </label> Here is the traceback error: Traceback (most recent call last): File "C:\Users\User\Desktop\Project\venv\lib\site-packages\django\core\handlers\exception.py", line 55, in inner response = get_response(request) File "C:\Users\User\Desktop\Project\venv\lib\site-packages\django\core\handlers\base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\User\Desktop\Project\users\views.py", line 34, in register return render(request, 'users/register.html', {'form': form}) File "C:\Users\User\Desktop\Project\venv\lib\site-packages\django\shortcuts.py", line 24, in render content = loader.render_to_string(template_name, context, request, using=using) File "C:\Users\User\Desktop\Project\venv\lib\site-packages\django\template\loader.py", line 62, in render_to_string return template.render(context, request) File "C:\Users\User\Desktop\Project\venv\lib\site-packages\django\template\backends\django.py", line 62, in render return self.template.render(context) File "C:\Users\User\Desktop\Project\venv\lib\site-packages\django\template\base.py", line 175, in render return self._render(context) File "C:\Users\User\Desktop\Project\venv\lib\site-packages\django\template\base.py", line 167, in _render return self.nodelist.render(context) File "C:\Users\User\Desktop\Project\venv\lib\site-packages\django\template\base.py", line 1005, in render return SafeString("".join([node.render_annotated(context) for node in self])) File "C:\Users\User\Desktop\Project\venv\lib\site-packages\django\template\base.py", line 1005, in <listcomp> return SafeString("".join([node.render_annotated(context) for node in self])) File "C:\Users\User\Desktop\Project\venv\lib\site-packages\django\template\base.py", line 966, in render_annotated return self.render(context) File "C:\Users\User\Desktop\Project\venv\lib\site-packages\django\template\defaulttags.py", line 472, in render url = reverse(view_name, args=args, kwargs=kwargs, current_app=current_app) File "C:\Users\User\Desktop\Project\venv\lib\site-packages\django\urls\base.py", line 82, in reverse raise NoReverseMatch("%s is not … -
RuntimeError: Model class django_celery_beat.models.SolarSchedule doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS
I'm using my virtualenv and upon executing celery -A app beat -l info -S django, this error always displays. RuntimeError: Model class django_celery_beat.models.SolarSchedule doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS. N.B: django_celery_beat already installed and migrated. I have used the following versions, like Python Version: 3.8 Celery Version: 5.1.1 Celery-Beat Version: 2.2.1 But my expectation is to run celery smoothly :) -
How to change url params (query_string) in django rest framework before handle request?
Because I need compatible with old client. For example, when I recevie an request http://0.0.0.0:8000/api/exercises/?pk=13, i want change the params so http://0.0.0.0:8000/api/exercises/?id=13. Others: http://0.0.0.0:8000/api/exercises/?displayName=ABC change to http://0.0.0.0:8000/api/exercises/?display_name=ABC http://0.0.0.0:8000/api/exercises/?target=1,2 change to http://0.0.0.0:8000/api/exercises/?target=1&target=2 Is there any place I can write code before handle the request? Thanks. -
How to display a form error on invalid password input in django?
I have a login form that can display a error message on invalid username input, but I am having trouble figuring out how to display an error on a invalid password input. The invalid username error I want to be able to display an error like this for the password when the user inputs a correct username but incorrect password. forms.py from django import forms from django.contrib.auth.hashers import make_password, check_password from django.contrib.auth.forms import AuthenticationForm from .models import User class LoginForm(AuthenticationForm): username = forms.CharField(max_length=255, widget=forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Username', 'required': True})) password = forms.CharField(max_length=255, widget=forms.PasswordInput(attrs={'class': 'form-control', 'placeholder': 'Password', 'required': True})) def clean_username(self): username = self.cleaned_data['username'] user = User.objects.filter(username=username) if not user: raise forms.ValidationError('Incorrect username') return username def clean_password(self): # This is the part I need help with # NOTE This code does nothing, just used to # display the functionality I want to implement password = self.cleaned_data['password'] if not check_password(password): raise forms.ValidationError('Incorrect password') return password views.py from django.contrib.auth.views import LoginView from .forms import LoginForm class LoginUserView(LoginView): template_name = 'login.html' authentication_form = LoginForm login.html {% extends 'base.html' %} {% block title%} Login {% endblock title %} {% block content %} </div> <form method="post"> {% csrf_token %} <div class="mb-4"> <p class="text-danger"> {{ form.username.errors.as_text }} … -
Exception Value: ['“Sunday” value has an invalid date format. It must be in YYYY-MM-DD format.']
I'm trying to save theAttendance mode, but I'm getting an error. I can't figureout what it is. Error is ['“Sunday” value has an invalid date format. It must be in YYYY-MM-DD format.'] Here is my models.py from django.db import models from employee.models import Employee # Create your models here. class Attendance(models.Model): employee = models.ForeignKey(Employee, on_delete=models.CASCADE) date = models.DateField() day = models.CharField(max_length=10) in_time = models.CharField(max_length=5) out_time = models.CharField(max_length=5) Here is my views.py from django.shortcuts import render,redirect from django.views.generic import View from django.http import JsonResponse from employee.models import Employee from .models import Attendance # Create your views here. class MarkAttendanceMainView(View): def get(self,request): return render(request,"mark_attendance.html") def post(self,request): attendance_time_in = [] attendance_time_out = [] attendance_date = [] attendance_day = [] emp_id = request.POST['attendance_emp_id'] emp = Employee.objects.filter(emp_id=emp_id) for id in request.POST: if "in" in id.split("_"): attendance_time_in.append(id) elif "out" in id.split("_"): attendance_time_out.append(id) elif "date" in id.split("_"): attendance_date.append(id) elif "day" in id.split("_"): attendance_day.append(id) i = 0 while i < len(attendance_time_in): date = request.POST[attendance_date[i]] day = request.POST[attendance_day[i]] time_in = request.POST[attendance_time_in[i]] time_out = request.POST[attendance_time_out[i]] i +=1 print(emp, date, day, time_in, time_out) attendance = Attendance(emp,date,day,time_in,time_out) attendance.save() return redirect('mark_attendance_main_view') -
Form attributes duplicating in '.controls' div when using CheckboxSelectMultiple widget with Crispy Forms
I have a form that's meant to filter results in a list view. I'm using HTMX to submit a GET request whenever the form changes, and I'm using Crispy Forms to render the form (including the hx attributes on the <form> tag). I've used this pattern multiple times before with no issues, but on this particular form I want to use the CheckboxSelectMultiple widget. When the form is rendered, the hx attributes that I'm applying to the <form> tag are getting duplicated on the <div class="controls"> tag that holds the checkboxes. Form class MyListFilterForm(forms.Form): status = forms.MultipleChoiceField(choices=MyModel.STATUS_CHOICES, required=False, widget=forms.CheckboxSelectMultiple) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_method = 'GET' self.helper.disable_csrf = True self.helper.attrs = { 'hx_get': reverse('myapp:my_view'), 'hx_trigger': 'change', 'hx_target': '#my_table_body', } Rendered HTML <form hx-get="/path/to/view/" hx-target="#my_table_body" hx-trigger="change" method="get"> <div id="div_id_status" class="control-group"> <label for="" class="control-label "> Status </label> <div class="controls" hx-get="/path/to/view/" hx-target="#my_table_body" hx-trigger="change"> <label class="checkbox" for="id_status_0"><input type="checkbox" name="status" id="id_status_0" value="1">Choice 1</label> <label class="checkbox" for="id_status_1"><input type="checkbox" name="status" id="id_status_1" value="2">Choice 2</label> <label class="checkbox" for="id_status_2"><input type="checkbox" name="status" id="id_status_2" value="3">Choice 3</label> </div> </div> </form> This duplication of the hx attributes is causing the HTMX request to fire twice whenever one of these checkboxes is clicked. Not only that, but the first request … -
Fixing date & time format in HTML
Context of Question Hi all, I'm building a Twitter clone. I'm using JavaScript to create & insert a new Tweet into the news feed. After inserting the new Tweet into the news feed, I noticed the date & time format is different after refreshing the page. Examples below for reference: Tweet after inserting into news feed & before refreshing the page Tweet after refreshing the page The Tweet in JSON format looks like this { "id": 56, "user": "admin", "content": "yes", "date": "Feb 07 2023, 12:26 AM", "likes": 0 } I'm using Django as the backend & the how a Tweet gets serialized is as follows: def serialize(self): return { "id": self.id, "user": self.user.username, "content": self.content, "date": self.date.strftime("%b %d %Y, %I:%M %p"), "likes": self.likes } Now, I'm not sure what's causing this mismatch of date & time format: the serializer for the Tweet, or how HTML handles the date & time format -
django.core.exceptions.ImproperlyConfigured: Could not find the GDAL library (when I try to run "python manage.py runserver")
I installed PostGIS 3.3. That PostGIS 3.3.2 bundle includes PostGIS 3.3.2 w, GDAL 3.4.3 (SQLite 3.30.1, OpenJPEG 2.4.0, Expat 2.4.8, FreeXL 1.0.6), GEOS 3.11.1, Proj 7.2.1, pgRouting 3.4.2, osm2pgrouting 2.3.8, ogr_fdw 1.1.3 spatial foreign data wrapper extension, and pgPointcloud 1.2.4, h3-pg 4.0.3. But when I try to run GeoDjango app, then it stopped with the following error. django.core.exceptions.ImproperlyConfigured: Could not find the GDAL library (tried "gdal304", "gdal303", "gdal302", "gdal301", "gdal300", "gdal204", "gdal203", "gdal202"). Is GDAL installed? If it is, try setting GDAL_LIBRARY_PATH in your settings. My system variables show GDAL installed and path set already. I am trying to setup correctly geodjango with gdal, So kindly expecting help to solve this matter. -
Why is my django session not persisting? It works when I use Postman but not when I try through my Frontend
I'm currently working on a registration component for an application built using React with TypeScript and Tailwind CSS, Django and MongoDB. In my Django backend I have an app called login_register_app, which is used for registration functionality. I want to create a session that stores the id of the document when the document is created so that when the user is asked to add further details on the following page the correct document can be updated. So far, I have the following function for registration: @api_view(['POST']) def create_login(request): # parse json body = json.loads(request.body) # get email and password and confirm password email = body.get('email') password = body.get('password') confirm_password = body.get('confirm_password') email_is_valid = False password_is_valid = False error = '' # password must be at least 8 characters and contain digit 0 - 9, Uppercase, Lowercase and Special # character from list (#?!@$%^&*-) password_validation_pattern = re.compile('^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])(?=.*?[#?!@$%^&*-]).{8,}$') # compare password to confirm password and regex pattern if password == confirm_password and re.match(password_validation_pattern, password): password_is_valid = True elif password == confirm_password: error = 'password is not valid. Requires at least one uppercase, lowercase, digit and special character [#?!@$%^&*-]' else: error = 'passwords do not match' # verify email does not already exist … -
How do i get selected value from select option from my template? Django
views.py: def add(request): categories = Category.objects.all() current_user = request.user owner = current_user if request.method == "POST": isActive = True img = "ASS" title = request.POST["title"] description = request.POST["description"] price = request.POST["price"] category = request.POST["categories_n"] f = Listing(title,description, img, price, isActive=True, owner = owner, category) f.save() context = {'owner': owner, "categories":categories} return render(request, "auctions/add.html", context) template: {% block body %} <div class ="main"> <form action = "{% url 'add' %}" method = "POST"> {% csrf_token %} <h3>Owner of the item: <strong>{{owner}}</strong></h3> <ul class = "u_list"> <li class = "l_item"><label for = "t">Title:</label> <input type = "text" name = "title" id = "t" placeholder = "Item's name"></li> <li class = "l_item"><label for = "d">Description: </label><input type = "text", name = "description" id = "d" placeholder = "Details about the item"></li> <li class = "l_item"><label for = "p">Price: </label> <input type = "price" name = "price" id = "p" placeholder = "Item's price"></li> <select name = "categories_n" id = "c"> {% for option in categories %} <option value = "{{option.id}}" {% if categories_n == option.name %} selected = "selected"{% endif %}> {{option}} </option> {% endfor %} </select> <input type = "submit" value = "Submit"> </ul> </form> </div> {% endblock body %} How do … -
Django Heroku deploy error "connection to server at "127.0.0.1", port 5432 failed: Connection refused"
I am trying to re-deploy my Python Django App on Heroku after the free dyno canceled. However, I got OperationalError at /catalog/ in Heroku: connection to server at "127.0.0.1", port 5432 failed: Connection refused Is the server running on that host and accepting TCP/IP connections? Exception Location: /app/.heroku/python/lib/python3.10/site-packages/psycopg2/__init__.py, line 122, in connect I ran the App locally without any issue, and I used this as a reference but not solving my problem. I tried several changes in my settings.py: ALLOWED_HOSTS = ['.herokuapp.com','127.0.0.1'] DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'somename', 'USER': 'someuser', 'PASSWORD': 'somepassword', 'HOST': '127.0.0.1', 'PORT': '5432', } } import dj_database_url db_from_env = dj_database_url.config(conn_max_age=500) DATABASES['default'].update(db_from_env) I personally believe the error was caused by those code above, and I had changed PORT to "8000", or used DATABASES['default'] = dj_database_url.config(), or set ENGINE to 'django.db.backends.postgresql', but those attempts were not working neither. Since it rans without error locally, so I am wondering what caused the Operational Error appeared? I would sincerely appreciate all the help since this issue bothered me for few days. -
linking django to web hosting site
I have created a webpage using Django and am looking to link it to my purchased domain name through domain.com. Domain.com tutorials have been worthless and they offer web hosting but I am not sure how to link my local Django project. Does it have to do with the SSL Certificate? Feel free to explain it to me like I am a 5 year old. I tried including the domain and ip of the purchased domain in the ALLOWED_HOSTS=[] but obviously that doesn't work without some communication between domain.com and Django. -
Django Rest Framework - How to use url parameters in API requests to exclude fields in response
Let's say I have an API that returns some simple list of objects at the /users endpoint { "count": 42, "results": [ { "name": "David", "age": 30, "job": "Baker", "location": "Alaska", "sex": "male", }, ... ] } I would like to pass a simple boolean that changes the output by removing certain fields. So /users?abridged=True would return the same objects, but omit a few fields. { "count": 42, "results": [ { "name": "David", "age": 30, }, ... ] } I suppose I could create two serializers, one for the full version and one abridged, but I'm not sure how I could use a url parameter to select which serializer to use. Is there a better way to do this? -
Converting fields inside a Serializer in django
I have a project where one model, called Request, has two fields (source, dest) that contain two ids which are not known to the user. However, each one is connected to another model User, who let's say that they have one field, username, which is known to the user. Now, I want to make a serializer that can take usernames, and convert them into ids. (The opposite was simple to achieve, I just modified the to_representation method.) The problem is that when I send {'source': 'john', 'dest': 'jim'} the serializer does not take these data as valid. This was expected behavior, as it expected ids and got strings (usernames). However, even when I overridden the validate_source, validate_dest and validate methods to actually check that the usernames exist (instead of the ids), I am still getting errors that the serializer expected id but got string. Are the validate, validate_<field> methods the wrong ones to override in this case? Should I just convert the usernames into ids inside my view? is it pythonic and good practice, django-wise, to receive some fields from the user and change them inside the serializer (as I change username into id)? Thank you. -
django query left join, sum and group by
I have a model: class Product(models.Model): name = models.CharField(max_length=100) class Sales(models.Model): product_id = models.ForeignKey(Product, on_delete=models.CASCADE, related_name='products') date = models.DateTimeField(null=True) price = models.FloatField() How do I return data as the following sql query (annotate sales with product name, group by product, day and month, and calculate sum of sales): select p.name , extract(day from date) as day , extract(month from date) as month , sum(s.price) from timetracker.main_sales s left join timetracker.main_product p on p.id = s.product_id_id group by month, day, p.name; Thanks, If only ORM was as simple as sql... Spent several hours trying to figuring it out... PS. Why when executing Sales.objects.raw(sql) with sql query above I get "Raw query must include the primary key" -
How to pass dynamic filtering options in django_filters form instead of all model objects?
I have the following structure of the project (models): Company (based on Groups) <-- Products (foreignKey to Company) <-- Reviews (foreignKey to Products). Inside template i want to give a user an opportunity to filter reviews by products, but when using django_filters it shows corrects queryset of reviews (related only to company's products) but in filter form dropdown options i can see all products of all companies (even those which are not presented on the page), for example for Company X i see on my page only Cactus and Dakimakura reviews, but in filter form i can select Sausage (but i shouldnt, because its product from another company). For now it's all looks like this: #View def reviewsView(request): context = {} user = request.user company = user.company products_qset = ProductModel.objects.filter(company=company) reviews_objects = ReviewModel.objects.filter(product__in=products_qset) filter = ReviewFilter(request.GET, queryset=reviews_objects) context['filter'] = filter return render(request, 'companies/reviews.html', context) #Filter class ReviewFilter(django_filters.FilterSet): class Meta: model = ReviewModel fields = [ 'product', 'marketplace', 'operator', 'state' ] #Template <form action="" method="get"> {{ filter.form.as_p }} <input type="submit" name="press me" id=""> </form> <div class="review-list"> {% for i in filter %} {{i.product}}, {{i.marketplace}} etc. {% endfor %} I've done quite a lot of research on django_filters docs and this question … -
Cannot make a migration in Django project to compose up docker file
I have a Django project that uses old version of django.db.models.signals - post_syncdb. I changed models and added new to the db. To make docker-compose up and launch Django with docker I need to make a migration, but when I'm doing this it shows me this error `AttributeError: module 'django.db.models.signals' has no attribute 'post_syncdb' I tried google the solution and noticed three ways: Check the Django version used in the project, as the post_syncdb signal has been deprecated since Django 1.9. Look through the project's code and identify any references to post_syncdb signal. If there are any, you may have to update the code to use a different signal. If the error persists, it may be a bug in one of the installed packages. You can try to update the packages to the latest version or raise an issue on the package's repository. The problem is that it's not mu project and I currently work on dev branch. How do I fix it and make a migration? -
How to optimizing database queries
How can I optimize an API, starting with optimizing database queries? Step 1: Model.objects.filter(is_disabled=0) Step 2: Index the database Step 3: Use pagination: Model.objects.filter(is_disabled=0)[offset:offset+10], where offset depends on the page number. Step 4: Consider using Redis to save data. Which Redis method should I use? I feel that a sorted set is fast, but it only stores integers and strings. If I want to save a dictionary, I need to use another Redis method. I'm also facing an issue with the Redis key if add data in redis for (Model.objects.filter(is_disabled=0)[offset:offset+10]) then key should be redis_key=”key”+str(page_number)), as deleting data would affect all page numbers. How can I handle Redis keys with page numbers? is it Good or bad to use redis for every 10 rows? -
Error when upload files to Azure Blob storage through Django App
I need to build a file manager to upload images from a Django app to Azure blob storage. However, when I try to upload a file to Azure's blob storage, I get the following error: Traceback (most recent call last): File "/Users/marilynmarquez/Desktop/webster/python/file_manager/venv/lib/python3.10/site-packages/django/core/handlers/exception.py", line 55, in inner response = get_response(request) File "/Users/marilynmarquez/Desktop/webster/python/file_manager/venv/lib/python3.10/site-packages/django/core/handlers/base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Users/marilynmarquez/Desktop/webster/python/file_manager/website/files/views.py", line 27, in upload_file new_file=upload_file_to_blob(file) File "/Users/marilynmarquez/Desktop/webster/python/file_manager/website/files/azure_controller.py", line 57, in upload_file_to_blob blob_client =create_blob_client(file_name = file_name) #problem File "/Users/marilynmarquez/Desktop/webster/python/file_manager/website/files/azure_controller.py", line 20, in create_blob_client storage_credentials = secret_client.get_secret(name=settings.AZURE_STORAGE_KEY_NAME) #problem File "/Users/marilynmarquez/Desktop/webster/python/file_manager/venv/lib/python3.10/site-packages/azure/core/tracing/decorator.py", line 78, in wrapper_use_tracer return func(*args, **kwargs) File "/Users/marilynmarquez/Desktop/webster/python/file_manager/venv/lib/python3.10/site-packages/azure/keyvault/secrets/_client.py", line 72, in get_secret bundle = self._client.get_secret( File "/Users/marilynmarquez/Desktop/webster/python/file_manager/venv/lib/python3.10/site-packages/azure/keyvault/secrets/_generated/_operations_mixin.py", line 1574, in get_secret return mixin_instance.get_secret(vault_base_url, secret_name, secret_version, **kwargs) File "/Users/marilynmarquez/Desktop/webster/python/file_manager/venv/lib/python3.10/site-packages/azure/core/tracing/decorator.py", line 78, in wrapper_use_tracer return func(*args, **kwargs) File "/Users/marilynmarquez/Desktop/webster/python/file_manager/venv/lib/python3.10/site-packages/azure/keyvault/secrets/_generated/v7_3/operations/_key_vault_client_operations.py", line 694, in get_secret pipeline_response = self._client._pipeline.run( # pylint: disable=protected-access File "/Users/marilynmarquez/Desktop/webster/python/file_manager/venv/lib/python3.10/site-packages/azure/core/pipeline/_base.py", line 211, in run return first_node.send(pipeline_request) # type: ignore File "/Users/marilynmarquez/Desktop/webster/python/file_manager/venv/lib/python3.10/site-packages/azure/core/pipeline/_base.py", line 71, in send response = self.next.send(request) File "/Users/marilynmarquez/Desktop/webster/python/file_manager/venv/lib/python3.10/site-packages/azure/core/pipeline/_base.py", line 71, in send response = self.next.send(request) File "/Users/marilynmarquez/Desktop/webster/python/file_manager/venv/lib/python3.10/site-packages/azure/core/pipeline/_base.py", line 71, in send response = self.next.send(request) [Previous line repeated 2 more times] File "/Users/marilynmarquez/Desktop/webster/python/file_manager/venv/lib/python3.10/site-packages/azure/core/pipeline/policies/_redirect.py", line 160, in send response = self.next.send(request) File "/Users/marilynmarquez/Desktop/webster/python/file_manager/venv/lib/python3.10/site-packages/azure/core/pipeline/policies/_retry.py", line 512, in send raise err File … -
How can I get a Field Id from a Related Django Model
I am working on a Django project where and I want to get an ID of a Related model with a OneToOne attributed so I can edit the profile of the user with his related Profile but all I get in return is Field 'id' expected a number but got 'GANDE1'. Here are my Models: class Profile(models.Model): customer = models.OneToOneField(User, on_delete=models.CASCADE, null = True) surname = models.CharField(max_length=20, null=True) othernames = models.CharField(max_length=40, null=True) gender = models.CharField(max_length=6, choices=GENDER, blank=True, null=True) address = models.CharField(max_length=200, null=True) phone = models.CharField(max_length=11, null=True) image = models.ImageField(default='avatar.jpg', blank=False, null=False, upload_to ='profile_images', ) #Method to save Image def save(self, *args, **kwargs): super().save(*args, **kwargs) img = Image.open(self.image.path) #Check for Image Height and Width then resize it then save if img.height > 200 or img.width > 150: output_size = (150, 250) img.thumbnail(output_size) img.save(self.image.path) def __str__(self): return f'{self.customer.username}-Profile' class Account(models.Model): customer = models.OneToOneField(User, on_delete=models.CASCADE, null=True) account_number = models.CharField(max_length=10, null=True) date = models.DateTimeField(auto_now_add=True, null=True) def __str__(self): return f' {self.customer} - Account No: {self.account_number}' Here is my Views: def create_account(request): #Search Customer if searchForm.is_valid(): #Value of search form value = searchForm.cleaned_data['value'] #Filter Customer by Surname, Othernames , Account Number using Q Objects user_filter = Q(customer__exact = value) | Q(account_number__exact = value) #Apply the Customer … -
nginx not seeing static files, when launching with docker compose +gunicorn
The thing is that i have set up dockerfiles, docker-compose is running everything as it should be. Databases is connected and all the staff. But the only problem is, that i cant load staticfiles. Gunicorn informs, that files "Not Found" both admin, and rest_framework static files. When im doing "docker-compose up" it says that `0 static files were copied to '/static', 165 unmodified So far i have checked paths which are configured in STATIC_ROOT and STATIC URL. Also, modified my docker-compose file: version: '3.11' services: django_gunicorn: volumes: - static:/static/ env_file: - .env build: context: . ports: - "8000:8000" nginx: build: ./nginx volumes: - static:/static/ ports: - "80:80" depends_on: - django_gunicorn - db db: image: postgres expose: - 5432 environment: - POSTGRES_USER=postgres - POSTGRES_PASSWORD=postgres - POSTGRES_DB=postgres volumes: static: Also i have inspected nginx config file one more time: upstream django { server django_gunicorn:8000; } server { listen 80; location / { proxy_pass http://django; } location /static/ { autoindex on; alias /static/; } } i have also tried different approaches to setting up root and url of staticfiles, but left it like this for now: STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATIC_URL = '/static/' Also there were suggestions to run "collectstatic" first, which i … -
Duplicated reponse with axios in React component's lifecycle method
everyone I'm making a web app and configured a Django backend server to which I make API calls with axios.get. The problem is, the middleware code is being executed twice and I don't understand why, I'm using the API call within a React component's lifecycle method: componentDidMount() { console.log('This line prints only once in the console'); axios.get("http://server:port"). .then((response) => { console.log('This line prints twice in the console!'); }) .catch((err) => console.log(err);); } I was expecting the second call (in the dummy code snippet) to be executed only once... Am I doing something wrong? Can somebody explain what is going on? Thank you in advance for your attention. -
ForeignKey with multiple dependencies
Assume there are some number of buildings located in several locations (BL). Each building can have a certain building type (BT), for example it can be a residential house, a hospital or a school. The choice of construction material (CM) used to build buildings' walls depends on BL and BT. How can I declare CM in my models, so that my app determines CM based on the selection of BL and BT? I assume regular ForeignKey won't work in this case. -
Django: Unable to Apply Function View Decorator to Class Based View
I'm migrating from regular function based views, to class based views. One of the things that I couldn't migrate were the decorators I used. The decorator in question checks if the credentials of the current user are valid and then executes the decorated function: def custom_auth(function): @wraps(function) def wrap(request, *args, **kwargs): # Logic for validating if user has correct credentials # Fetches the user that accessed the function user_object = User.objects.get(username=request_username) # Try to execute the decorated function. If it fails, redirect # to previous page and show an error popup try: return function(request, user=user_object, *args, **kwargs) except: # Logic for displaying the popup Previously I could just decorate my function by doing @custom_auth def view(request, *args, **kwargs): # View logic However, when I try to apply it to my class based view in the same way, I get an error saying __init__() takes 1 positional argument but 2 were given: @custom_auth class CBV(View): def get(self, request, *args, **kwargs): # Get request logic I know that this is not the way you are supposed to apply the decorator, so I tried with different approaches. Either adding the decorator to urls.py, adding the @method_decorator(custom_auth, name="dispatch") or simply overriding the dispatch method, … -
How do I filter data in a ForeignKey Django to display the corresponding data?
class Entrepreneur(models.Model) f ... Class Skills(models.Model) usevalue = models.ForeignKey(Entrepreneur) rating = (rating = models.PositiveSmallIntegerField(validators=[MinValueValidator(0),MaxValueValidator(5)]) Hello I am on a professional project and I had a question given that I am a young developer for the moment I did not know how to filter the data of the skills model for the entrepreneur and that I can filter it and then I can display it on the frontend. Thank you for your answers.