Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
In django dockerization nginx does not listen on port 80 and cannot find static files even though it is in nginx container
Docker-compose.yml version: '3' services: nginx: build: ./nginx ports: - 80:80 depends_on: - "web" volumes: - ./static_volume/:/home/app/web/staticfiles db: image: postgres restart: always volumes: - ./pgdb:/var/lib/postgresql/data/ ports: - "5432:5432" env_file: - .env web: build: . command: gunicorn config.wsgi:application --bind 0.0.0.0:8000 volumes: - .:/app - ./static_volume/:/app/staticfiles ports: - "8000:8000" depends_on: - db - redis - celery env_file: - .env redis: image: redis ports: - "6379:6379" celery: build: . command: celery -A config worker -l info depends_on: - redis env_file: - .env volumes: static_volume: pgdb: external: false nginx.conf upstream hello_django { server web:8000; } server { listen 80; location / { proxy_pass http://hello_django; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $host; proxy_redirect off; } location /static/ { alias /home/app/web/staticfiles; } } Dockerfile for nginx FROM nginx:1.21-alpine RUN rm /etc/nginx/conf.d/default.conf COPY nginx.conf /etc/nginx/conf.d this is web and nginx container I'm trying to dockerize my Django project and have successfully managed to serve static files without configuring nginx within the container. However, after installing nginx, the static files are not found by nginx even though they exist in the nginx container. Additionally, the site only seems to work on the localhost:8000 port.My Operation system is Windows -
Django/PyCharm - Unresolved attribute reference '' for class 'User'
Just wondering if there's a way to get around this super annoying PyCharm warning without having to ignore it altogether. I have a custom User model with extra fields and methods. When I try to access these attributes in a view (ex. if self.request.user.type == 'foo':) I'll get the warning Unresolved attribute reference 'foo' for class 'User' in the IDE. It seems that PyCharm thinks that I'm still using django.contrib.auth.User even though I've specified AUTH_USER_MODEL = 'user.User' in the project settings. -
Django Channels permissions
Is there any supported way in Django Channels framework to write custom permission to connect to specific consumers? something like DRF: class MyConsumer(generics.APIView): permission_classes = [IsAuthenticated, MyCustomPermission] authentication_classes = [TokenAuthentication] -
403 error when using django with allauth and htmx
I am building a website with django and I use allauth for authentication and htmx to make the site dynamic. On my mainpage when the user clicks on Login an hx-get is issued and the div with id="login-logout-div" is swapped with the response of the allauth Login view. Then the user can enter the credentials and is logged in. The allauth settings are LOGIN_REDIRECT_URL = "hq:index" LOGIN_URL = "account_login" The login process also works, the user stays on the main page and the login div disappears. However, I also have a button that triggers an htmx-post further down that swaps the div with id=empty_entry. This button does not work right after the login and I get a 403 response. When I refresh the page, the user is still logged in and the hx-post request is now accepted when I click the button. I suspect that the csrf token is refreshed when I login but the X-CSRFToken in the hx-header is not updated when I redirect. The token is still sent on the hx-post request but it might be the wrong one. Help is very appreciated. :) index.html <body hx-headers='{"X-CSRFToken": "{{ csrf_token }}"}' hx-boost="true" hx-ext="multi-swap" homepage> <div> <div class="nav-links"> <a href="{% … -
How to change urls for "Add", "Change" etc. buttons in Django Admin?
My Django admin panel on production server has url like https://example.com/app/admin, but when I click on the buttons near my models (on the screenshots), I redirect to https://example.com/admin/metrics/..., without an /app/ part. If I manually go to https://example.com/app/admin/metrics/..., everything works perfectly. Can I somehow override this behaviour without overriding the whole admin panel template? -
Passing no variable in Django url template tag when one is required
Im using Django with htmx. I have set up a url as follows in my urls.py file: urlpatterns = [ path('@/<username>/my_orders/', views.myordersview, name="myorders"), ] and the myordersview function something like this: @login_required def myordersview(request, username): if request.htmx: return render(#something) else: return render(#something else) Now Im making a call to that url with htmx in my frame.html file: <a hx-target="#content" hx-get="{% url 'myorders' user.username %}"> My Orders </a> The <a> tag should also be displayed when a user is not logged in and redirect the unauthenticated user to a login page. The problem is, if a user is not logged in, no variable is passed into the url template tag aka user.username='' and Django spits out this error Reverse for 'myorders' with arguments '('',)' not found. I dont want to do this because its ugly: <a hx-target="#content" hx-get=" {% if user.is_authenticated %} {% url 'myorders' user.username %} {% else %} {% url 'login' %} {% endif %} "> My Orders </a> Is there a simple way to solve this without using a custom template tag? -
Overriding the default class attribute using django-crispy-forms
I am currently learning how to use django crispy forms and can't figure out this issue. I am using it alongside bootstrap5. I have the following form : class CommentForm(forms.ModelForm): class Meta : model = Comments fields = ["comment_content"] def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_show_labels = False self.fields['comment_content'].widget.attrs['placeholder'] = 'comment here...' self.helper.layout = Layout( "comment_content", ) self.helper.layout.append(Submit("post_comment", "Post comment",css_class="btn-outlined-primary")) The issue is with the last line : instead of replacing the default class (btn btn-primary) by the value of css_class,it simply adds this value afterwards so the resulting html is the following : <input type="submit" name="post_comment" value="Post comment" class="btn btn-primary btn-outlined-primary" id="submit-id-post_comment"> How do I make it so the resulting class is "btn btn-outlined-primary" and not "btn btn-primary btn-outlined-primary" ? Thanks to anyone taking the time to help me ! -
Django GIS - get all PERSONS within at least distance of "n" Points of Interest and annotate with distance
Let's imagine the two following models: from django.db import models from django.contrib.gis.db import models as models_gis class Person(models.Model): name = models.CharField(...) coordinates = models_gis.PointField(srid=4326, geography=True, spatial_index=True) class PointOfInterest(models.Model): name = models.CharField(...) coordinates = models_gis.PointField(srid=4326, geography=True, spatial_index=True) I manage to get all Person objects within a radius of an arbitrary number of PointOfInterest objects. The below seems to work: from django.contrib.gis.geos import MultiPoint # in meters radius = 1000 # *very* approximate conversion to degrees radius_in_degrees = float(radius) / 40010040.0 * 360.0 poi_points = tuple(PointOfInterest.objects.filter( pk__in=[1,2,3] ).values_list('coordinates', flat=True)) poi_multipoint = MultiPoint(*poi_points) persons = Person.objects.filter( coordinates__distance_lte=(poi_multipoint, radius_in_degrees), ) for person in persons: print(f'{person.name} is within {radius} meters of at least one of the specified points of interest') Cool. Now I would also like to annotate the persons queryset with the distance between each of its person and the individual POI of the poi_multipoint geometry it was found being closest to (and within the radius of course). How to do that so I can do: for person in persons: print(f'{person.name} is within {radius} meters of at least one of the specified points of interest. Distance to closest POI is {person.distance}') -
Django - nested modules in app with models don't trigger new migrations
In my Django project, I just created a new app named integrations, which defined an abstract model TwinResource. This integrations app, in turns, has a module called classroom, which also has a models.py file with a model ClassroomCourse which inherits from TwinResource. I have added the following to my INSTALLED_APPS: 'integrations', 'integrations.classroom', and I have created an init.py both in integrations and integrations.classroom, and both directories have a migrations folder with an init.py file. However, when running manage.py makemigrations, I get “No changes detected”. What am I missing? -
How to track that a request is handled by which view in django project?
I am working on a django project which consists of multiple apps and every app has its separate urls.py file. Now when we send a request in a browser, how can we track that the request is handled by which view in our project? e.g. We send a request with this url: http://mywebsite.com:8000/item?id=2 In server , we can see the request as: "GET /item?id=2 HTTP/1.1" 200 How can we track that this request is handled by which view? -
Delete unused tables and fields in django
I'm working on a Django project version 2.2 using Oracle SQL Database. In this database there are some tables that are not managed by Django models and I want to delete these. Because there are nearly 1800 tables in this database, I need to find a way to detect these by some sort of script or query. Also in some tables there are some fields that are always null for any records. Actually, I have got many unusable fields in my database. How can I detect and remove these fields and tables using Django or Oracle SQL? I ran a sql query to list all tables and compare it to output of django command apps.get_models() but it didn't help. -
Forcefully Logout user from frontend in Django
I am using React for frontend and Django for the backend. I have created a button "Force logout" in django admin for each use on click of which I want to logout the user working on the frontend (when he refresh he should be logged out). I want to do this completely in django without touching Reach. I am using djangorestframework-simplejwt for authentication. -
Built-in way to name one specific celery task
I'm using Celery with Django (and django-db as result backend). I know that it's possible to give names to registered tasks using @app.task(name='My Task') but that's only like categorizing. Assume uploading and processing a file "batch-210520.json". I want to be able to identify one running task as the task which is processing that specific file. Obviously I could add my own table to keep track of task ids and their unique names, but if there is a built-in way I want to use it. Unfortunately I only found the solution for naming the whole registered task. -
Add scroll wheel to Ckeditor 5 text editor django
I am quite new to using django. I want to add a rich text editor to my webapp and I saw a tutorial on how to do so using "django-ckeditor-5". I followed these steps: https://pypi.org/project/django-ckeditor-5/ and the editor works fine and everything however, it keeps expanding with the the text, so it just goes of the screen after a while. Is there a way to stop this behavior, and instead add a scroll wheel to the side of the editor so users can use that to see the entire text? I was also wandering how I can install plugins to the editor since I know it's possible but i'm not really sure how. Here is my ckeditor config in the settings.py file: customColorPalette = [ { 'color': 'hsl(4, 90%, 58%)', 'label': 'Red' }, { 'color': 'hsl(340, 82%, 52%)', 'label': 'Pink' }, { 'color': 'hsl(291, 64%, 42%)', 'label': 'Purple' }, { 'color': 'hsl(262, 52%, 47%)', 'label': 'Deep Purple' }, { 'color': 'hsl(231, 48%, 48%)', 'label': 'Indigo' }, { 'color': 'hsl(207, 90%, 54%)', 'label': 'Blue' }, ] CKEDITOR_5_CONFIGS = { 'default': { 'toolbar': ['heading', '|', 'bold', 'italic', 'link', 'bulletedList', 'numberedList', 'blockQuote' ], }, 'extends': { 'blockToolbar': [ 'paragraph', 'heading1', 'heading2', 'heading3', '|', … -
Custom logger Formatter in Python
I need to use 2 different handlers, one for Elasticsearch and the other for Django. The Elasticsearch handler has already custom formatter (json-like), and is set to ERROR level. I need to pass extra args in order to create indexes in Kibana. The Django logs needs a different formatting: '[%(asctime)s] %(name)s %(levelname)-8s --> %(message)s'. But for the ERROR level I need to take care of the extra, because the message will be: f"[{pid}] {func}() - {msg} - {tb} - [{exc_name} - {exc_args}]" For the INFO i need only f"[{pid}] {func}() - {msg}" So I created a Custom Formatter Class, and it works but: I can not find a way to pass the fmt in order to add asctime and name (package.module). The LogRecord doesn't have by default them. LOG_BASE_PATH = BASE_DIR / 'logs/' LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'precise': { '()': utils.DjangoCustomFormatter("[%(asctime)s] %(name)s %(levelname)s: %(message)s"), # 'format': '[%(asctime)s] %(name)s %(levelname)-8s --> %(message)s', }, 'ecs': { '()': 'ecs_logging.StdlibFormatter', }, }, 'handlers': { 'file_django': { 'class': 'logging.handlers.RotatingFileHandler', 'filename': LOG_BASE_PATH / 'django.log', 'formatter': 'precise', 'level': 'INFO', }, 'file_ecs': { 'class': 'logging.handlers.RotatingFileHandler', 'filename': LOG_BASE_PATH / 'test.log', 'formatter': 'ecs', 'level': 'ERROR' }, }, 'loggers': { 'multi_logger': { 'handlers': ['file_ecs', 'file_django'], 'level': … -
Field name `email` is not valid for model `customer`. in Multi User authentication Django Rest Framework
I am trying to create a multiple user authentication system in Django and am using onetoone field and booleans for creating profiles. But when creating serializers it throws the error "Field name email is not valid for model customer." Can someone please clarify what am I doing wrong here? models.py: from django.db import models from django.contrib.auth.models import User,AbstractBaseUser,BaseUserManager # Create your models here. class UserManager(BaseUserManager): def create_user(self, email, password, **extra_fields): if not email: raise ValueError("The email must be set") if not password: raise ValueError("The password must be set") email = self.normalize_email(email) user = self.model(email=email, **extra_fields) user.set_password(password) user.save() return user class user(AbstractBaseUser): is_customer = models.BooleanField(default=False) is_restaurant = models.BooleanField(default=False) email = models.EmailField(max_length=100,unique=True) USERNAME_FIELD = 'email' objects = UserManager class customer(models.Model): user = models.OneToOneField(user,on_delete=models.CASCADE) firstname = models.CharField(max_length=80) lastname = models.CharField(max_length=80) class restaurant(models.Model): user = models.OneToOneField(user,on_delete=models.CASCADE) rest_name = models.CharField(max_length=80) serializers.py:- from rest_framework import serializers from .models import * class userserializer(serializers.ModelSerializer): class Meta: model = user fields = '__all__' class cust_serializer(serializers.ModelSerializer): class Meta: model = customer user = userserializer(read_only=False) email = serializers.StringRelatedField(read_only=False,source = 'user.email') password = serializers.StringRelatedField(source = 'user.password') fields = [ 'id', 'email', 'password', 'firstname', 'lastname', ] def create(self,validated_data): user1 = user.objects.create(self,email=validated_data['email'],password=validated_data['password']) user1.is_customer = True user1.save() instance = customer.objects.create(user=user1,firstname = validated_data['firstname'],lastname = ['lastname']) return … -
Django ORM: LEFT JOIN condition based on another LEFT JOIN
I'm using Django 4.0 and PostgreSQL (13.7) as the backend (upgrading would be possible if its required for a solution) I have two models: Cat and Attribute. The Attribute holds generic key-value pairs describing Cat instances. Cat table: PK name 1 Wanda 2 Aisha 3 Thala Attribute table: PK cat_id key value 1 1 size 10 2 1 age 5 3 2 size 7 4 2 intelligence 75 5 2 children 3 6 3 intelligence 60 7 3 age 9 I'd like to select different attribute values depending on conditions of other attributes for all instances, e.g.: Get size of a Cat if its age is greather than 4 or it has more than 2 children - or if there is no match, get age if intelligence is over 50. Well, the example here contains random attributes and numbers and does not make any sense, but in my application's world the conditions can be overly complex including several recursive AND, OR, EXISTS and NOT conditions. My query would be: SELECT DISTINCT(cat.id), cat.name, COALESCE( result1.key, result2.key ) as result_key COALESCE( result1.value, result2.value ) as result_value FROM cat -- first condition LEFT OUTER JOIN attribute cond1 ON ( cat.id = cond1.cat_id AND … -
create a new model instance automatically in django
I am creating a django + react.js project. I have integrated social auth for google using django social auth. I am able to get the django access token and in the admin panel I can see a new User instance is getting created. However I have a UserProfile model which has a one-to-one relation with the User model and there no new instance is getting created. Following is my model class for UserProfile. class UserProfile(models.Model): user = models.OneToOneField(User,on_delete=models.CASCADE) userName = models.CharField(max_length=26,unique=True) email = models.EmailField(max_length=254,unique=True) profilePhoto = models.ImageField(default="/default.png") rank = models.CharField(max_length=26,default="Novice") def __str__(self): return self.userName My question is, Is there any way that I could automatically create a new instance for UserProfile just whenever a new User instance is getting created. -
Django Models: Different fields in a form depending on a selected option from a selected list
One table has a choices select list, specialization (rocket engines, navigation software, or airports) The other table(s) should create different Forms which have different classes, (I mean college study program classes) and therefore different fields in the Form, depending on what was selected on the other table. Should I create several models, one for each specialization? so that each has different study program classes? How can I make it so that upon having chosen a specialization, the corresponding model is activated and launches me the correct Form? This is my timid visualization, but I have no idea whether that is the right approach or even how to implement that code. So far 4 days and can't get my head around it. I have seen this: Django: Switch a form in template depending on choice field but still can't come full circle. -
Django Postgresql jsonfield queryset
p = Profile(name="Tanner", data={'daily__email': 'a@a.com', 'weekly__email': True}) p.save() Profile model has jsonfield. Profile.objects.filter(data__daily__email='a@a.com') Profile.objects.filter(data__daily__email__startswith='a') how can i find Tanner on queryset?.. how can i find Tanner on queryset? -
Django models.IntegerField
In my Django admin page, I have a dropdown field (Teachers Name) that fills from Teacher_CHOICES. But when I want to Save something, the Teacher's dropdown field has an error "Select a valid choice. 25 is not one of the available choices.". I need to TecherID. class classes_info(models.Model): ClassName = models.CharField(max_length=255, verbose_name="Class name") On = "On" Off = "Off" Status_CHOICES = [ (On, 'On'), (Off, 'Off'), ] Status = models.CharField(max_length=10, choices=Status_CHOICES, default=On) Teacher_CHOICES = [ (0, '-------'), (34, 'Farhad Dorod'), (26, 'Mahsa Ghafarzadeh'), ] TeacherID = models.IntegerField(max_length=200, choices=Teacher_CHOICES) I have a problem and I don't know what's my problem. Please Help me. Thanks. I changed models to CharField: TeacherID = models.CharField(max_length=200, choices=Teacher_CHOICES) And also, I changed Datatype in the Database. From BIGINT to LONGTEXT Please help me. Thanks so much. -
function on entering admin list view
I have an admin list view, that for every row calls an external API and therefore becomes costly. So I am looking for a way to make the call once on entering the admin list view: @admin.display(description = "foo") def some_action(self, obj): return do_some_expensive_call(obj) I want to turn this into: def run_once(self): self.results = {} self.results[key] = some_expensive_list_call() @admin.display(description = "foo") def some_action(self, obj): return self.results[obj] Is there a method that should be used? -
Django: connection of LoginView with template fields
I created a combined registration and login form that is linked to the LoginView, but I ran into a problem relating the fields in the form to the LoginView mechanism (it does not use them). Can anyone suggest if it's possible to use custom template styling instead of using the standard approach with unstyled {{form.username}}, {{form.password} } and the like? Thanx! Here is my template login.html <div class="form-structor"> <div class="signup slide-up"> <h2 class="form-title" id="signup"><span>or</span>SignUp</h2> <form method="post"> {% csrf_token %} <div class="form-holder"> <label> <input id="uname" type="text" class="input" placeholder="Name" required autocomplete="off"/> </label> <label> <input id="pwd" type="password" class="input" placeholder="Password" required autocomplete="off"/> </label> <label> <input id="pwd2" type="password" class="input" placeholder="Retype password" required autocomplete="off"/> </label> </div> <button id="id_signup" class="submit-btn">SignUp</button> </form> </div> <div class="login"> <div class="center"> <h2 class="form-title" id="login"><span>or</span>Login</h2> <form method="post"> {% csrf_token %} <div class="form-holder"> <label> <input name="{{ form.name.name }}" id="id_name" type="text" class="input" placeholder="Name" required autocomplete="off"/> </label> <label> <input name="{{ form.name.name }}" id="id_password" type="password" class="input" placeholder="Password" required autocomplete="off"/> </label> </div> <button id="id_login" class="submit-btn">Login</button> </form> </div> </div> </div> And simple use: class SimpleLoginUser(LoginView): template_name = 'login/login.html' def get_success_url(self): return '/show-person-visits/'+str(self.request.user.person.id)+'/' Does anyone have experience with this? -
Uploaded image in ImageField is not shown by generic CreateView/DetailView/UpdateView
When uploading an image, the image file is stored in the desired folder. Good! But the generic views doesn't show the stored image but only: My code looks like this: model: def tenant_images_path(instance, filename): # generate filename like: return 'data/1/images/2023/03/01/' + filename class ArticleModel(models.Model): product_image = models.ImageField(_('Product image'), upload_to=tenant_images_path) article_create.html template: <h1>{% trans "Create new article" %}</h1> <div class="col-md-10"> <form action="{% url 'article-create' %}" method="post" class="form" enctype="multipart/form-data"> {% csrf_token %} {% bootstrap_form form %} {% buttons %} <button type="submit">{% trans 'Create' %}</button> {% endbuttons %} </form> </div> article_update.html template: <h1>{% trans "Update article" %}</h1> <div class="col-md-10"> <form action="" method="post" class="form" enctype="multipart/form-data"> {% csrf_token %} {% bootstrap_form form %} {% buttons %} <button type="submit">{% trans "Update" %}</button> {% endbuttons %} </form> </div> I expected the generic views to handle the display of the image. Am I wrong? -
Login using social auth
I am trying to integrate social login functionality in my react.js + Django app. I am following this video https://youtu.be/wlcCvzOLL8w and documentation provided by https://github.com/wagnerdelima/drf-social-oauth2 . I have created the custom signIn button and on clicking it I am getting getting the information about my gmail. However, I am not sure how to proceed further as I haven't found any tutorial or good documentation on how to connect the user's gmail with the backend, So the user's progress could be tracked. Can anyone please provide some link that might help me to proceed.