Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Error 405 when calling POST in my react native app
After installing SSL certificate to the backend web server (NGINX) of my React Native app, I started encountering Error 405 every time I use the POST method. I've tried multiple solutions offered online, like adding the following line to my NGINX config, but nothing seems to work. error_page 405 =200 $uri; I've attached my NGINX configuration below, # Upstreams upstream wsgiserver { ip_hash; server thebackend:80; } # Redirect to HTTPS server { listen 80; listen [::]:80; server_name thebackend.com; access_log /var/log/nginx/thebackend-access.log; error_log /var/log/nginx/thebackend-error.log; return 301 https://thebackend.com$request_uri; } # HTTPS server server { listen 443 ssl http2; listen [::]:443 ssl http2; server_name thebackend.com; access_log /var/log/nginx/thebackend.com.log; error_log /var/log/nginx/thebackend.com.log; ssl on; ssl_certificate /etc/ssl/thebackend/thebackend.com_bundle.crt; ssl_certificate_key /etc/ssl/thebackend/thebackend.com.key; ssl_session_timeout 5m; ssl_protocols TLSv1 TLSv1.1 TLSv1.2 TLSv1.3; #ssl_dhparam /etc/ssl/certs/dhparam.pem; ssl_ciphers 'EECDH+AESGCM:EDH+AESGCM:AES256+EECDH:AES256+EDH'; ssl_prefer_server_ciphers on; ssl_session_cache shared:SSL:10m; # WSGI server location / { proxy_pass https://wsgiserver/; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-NginX-Proxy true; proxy_set_header Access-Control-Allow-Credentials true; proxy_set_header Content-Encoding gzip; proxy_set_header Host $http_host; proxy_set_header Cookie $http_cookie; proxy_set_header Upgrade $http_upgrade; proxy_pass_header X-CSRFToken; proxy_ssl_protocols TLSv1 TLSv1.1 TLSv1.2 TLSv1.3; proxy_ssl_server_name on; proxy_read_timeout 5m; proxy_redirect default; error_page 405 =200 $uri; } } Did I miss something? Any suggestions would be greatly appreciated. -
Skip FIleNotFoundError in django templates
I encountered the following error in the template. How can skip this error. My code: {% if obj.profile_pictures %} <img src="{{ obj.profile_pictures.url }}" > {% else %} <img src="{% static 'assets/img/alt_img.jpg' %}""> {% endif %} -
ImportError: cannot import name ‘ThreadingUnixStreamServer’ from ‘socketserver’
I am running python manage.py runserver but I keep getting an error ImportError: cannot import name ‘ThreadingUnixStreamServer’ from ‘socketserver’ please what do I do? I am trying to view my website on my browser using my localport. -
i am getting error while sending email through django. i have following settings in my settings.py file . how can i resolve this problem?
@login_required(login_url="/login/") def api_view(request): if request.method == "POST": subs = str(request.POST.get("subs")).capitalize() subs = ast.literal_eval(subs) # javascript true to Python True user_name = request.user.get_username() email = request.user.email if subs: send_mail( "Congratulations for subscription", "Thank you for showing interest!we appreciate your efforts", "fromemail@gmail.com", [email], fail_silently=False,) this is my settings.py file import os EMAIL_HOST = "smtp.gmail.com" Email_PORT = 587 EMAIL_HOST_USER ="fromemail@gmail.com" EMAIL_HOST_PASSWORD = os.environ.get('pass_wd') EMAIL_USE_TLS = True TimeoutError: [WinError 10060] A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond -
Check if the file exists and there are no errors - Django
In my project I encountered the following error. In my view I copies files from one model to another. However, it seems that some files do not have a counterpart and verification shows that they path exist FileNotFoundError at /home/. It seems the path exists but the file on the server does not. How to check if file exists before saving to a new model. My code: if product.img_1: obj_apartment.basic_img = product.img_1 I need something like this: if product.img_1.open(): obj_apartment.basic_img = product.img_1 -
How to make repetitive background task in Django?
When I am accessing an url, the view activate a background task that need to repeat an action for 5 minutes every second, but I have an error and this task repeats only once. I have django4-background-tasks for Django 4.1.2. Here is my code Views.py @csrf_exempt def task(request): return _post_task(request) def _post_task(request): demo_task() return JsonResponse({}, status=302) And here the task is, where I want every second to be displayed '123' for 5 seconds, it means during 5 seconds will be printed five '123' @background(schedule=0) def demo_task(repeat=4, repeat_until=(datetime.datetime.now() + datetime.timedelta(minutes=3))): print('123') Maybe exits other ways to make async background tasks, I tried celery, but it was too hard. -
how to make the django devserver run everytime i create a docker container, instead of when i build the image
tldr version: how do i do x everytime i build a container, instead of everytime i build a new image. im building a very basic docker django example. when i do docker-compose build everything works as i want version: '3.9' services: app: build: context: . command: sh -c "python manage.py runserver 0.0.0.0:8000" ports: - 8000:8000 volumes: - ./app:/app environment: - SECRET_KEY=devsecretkey - DEBUG=1 this runs the django devserver, however only when the image is being built. the containers created by the image do nothing, but actually i want them to run the django devserver. So i figure i should just move the command: sh -c "python manage.py runserver 0.0.0.0:8000" from docker-compose to my dockerfile as an entrypoint. below is my docker file FROM python:3.9-alpine3.13 LABEL maintainer="madshit.com" ENV PYTHONUNBUFFERED 1 COPY ./requirements.txt /requirements.txt COPY ./app /app WORKDIR /app EXPOSE 8000 RUN python -m venv /py && \ /py/bin/pip install --upgrade pip && \ /py/bin/pip install -r /requirements.txt && \ adduser --disabled-password --no-create-home app ENV PATH="/py/bin:$PATH" USER app ENTRYPOINT python manage.py runserver # i added this because i thought it would be called everytime my docker environment was finished setting up. no dice :( The bottom section of the image below is … -
Docker compose issue while building python image, access denied or repository does not exist
I am trying to troubleshoot a tutorial on udemy on Windows 10 but why my compose file is failing to run. I tried relogging into Docker and I am able to run Docker build python:3.9-slim-bullseye successfully. Does anyone here see my issue and help me understand what is happening? I think my issue with with the line: apt-get update && apt-get install --no-install-recommends -y \ build-essential \ libpq-dev The tutorial's original code is here on his github but most of my code is a straight copy from him. Here is a link to the repo I have of what was covered so far. local.yml file version: "3.9" services: api: build: context: . dockerfile: docker/local/django/Dockerfile command: /start container_name: django-api volumes: - .:/app - static_volume:/app/staticfiles - media_volume:/app/mediafiles ports: - "8000:8000" env_file: - ./.envs/.local/.django - ./.envs/.local/.postgres depends_on: - postgres - mailhog networks: - authors-api-live postgres: build: context: . dockerfile: ./docker/local/postgres/Dockerfile container_name: postgres # volumes: # This is also causing issues # - local_postgres_data:/var/lib/postgresql/data # - local_postgres_data_backups:/backups env_file: - ./.envs/.local/.postgres networks: - authors-api-live mailhog: image: mailhog/mailhog:v1.0.0 container_name: mailhog ports: - "8025:8025" networks: - authors-api-live networks: authors-api-live: driver: bridge volumes: local_postgres_data_backups: {} static_volume: media_volume: Django Dockerfile ARG PYTHON_VERSION=3.9-slim-bullseye FROM python:${PYTHON_VERSION} as python # BUILD STAGE … -
Why customer.save() returns None? Isn't it supposed to return objects?
I want to get id of the model that is just created after saving so that I can pass to another view but it returns None even after model being created in database while printing. view def ShippingAddress(request): user=request.user cart=Cart.objects.filter(user=user) # print(cart) amount=0.0 shipping=100.0 tempamnt=0.0 totalamnt=0.0 cart_prod=[p for p in Cart.objects.all() if p.user==user] if cart_prod : for prod in cart_prod: tempamnt=prod.quantity*prod.product.discounted_price amount+=tempamnt totalamnt=shipping+amount if request.method=="POST": name=request.POST.get('name') locality=request.POST.get('locality') city=request.POST.get('city') state=request.POST.get('state') zipcode=request.POST.get('zipcode') customer= Customer.objects.create(user=user, name=name,locality=locality,city=city,state=state,zipcode=zipcode) temp=customer.save() print(temp) context={'carts':cart,'totalamnt':totalamnt,'amount':amount} return render(request,'store/shipping_detail.html',context) Also how do I send that id using redirect to next view. another view ` def checkout(request,): return render(request,'store/checkout.html') Is there any way or should i use intermediate page for that. -
How to use right queryset in django?
There are model: class Employee(models.Model): name = models.CharField(max_length=100) position = models.CharField(max_length=100) hired_at = models.DateField(auto_now=True) salary = models.DecimalField(max_digits = 9, decimal_places= 2) boss = models.ForeignKey('self', null=True,blank=True, on_delete=models.CASCADE) has_boss = models.BooleanField(null=True) is_visited = models.BooleanField(null=True) And there are BAD queryset in view: def get_queryset(self): return reversed(Employee.objects.all()) I want specific query: It should have all employees Only once for queryset. Now i show in template many employees more than 1 time, especially if some employees have the same boss. It should consist of from full chain from lowest employee to highest (main boss). -
How to query hierarchy model and avoid redundancy memory allocation for the same object?
Models used: class Person(models.Model): name = models.CharField(max_length=128) def __str__(self): return self.name class Department(models.Model): president = models.ForeignKey(to=Person, on_delete=models.CASCADE, related_name='+') vice_president = models.ForeignKey(to=Person, on_delete=models.CASCADE, related_name='+') name = models.CharField(max_length=128) def __str__(self): return f'{self.name} lead mainly by {self.president} (and secondly by {self.vice_president})' Query performed: for department in Department.objects.all(): print(hex(id(department.president)), department.president, department) print(hex(id(department.vice_president)), department.vice_president, department) Expected result: 0x1bbeca18960 Joe Marketing lead mainly by Joe (and secondly by Tom) 0x1bbeca18c70 Tom Marketing lead mainly by Joe (and secondly by Tom) <-- SAME instance of "Tom" 0x1bbeca18c70 Tom Financing lead mainly by Tom (and secondly by Bob) <-- as this instance of "Tom" 0x1bbeca18e80 Bob Financing lead mainly by Tom (and secondly by Bob) Actual result: 0x1bbeca18960 Joe Marketing lead mainly by Joe (and secondly by Tom) 0x1bbeca18c70 Tom Marketing lead mainly by Joe (and secondly by Tom) <-- DIFFERENT instance of "Tom" 0x1bbeca18a30 Tom Financing lead mainly by Tom (and secondly by Bob) <-- than this instance of "Tom" 0x1bbeca18e80 Bob Financing lead mainly by Tom (and secondly by Bob) Motivation: When I have 100 Persons, and 100 Departments, I want a total allocation of 100 instances of "Department" and 100 instances of "Person", but instead there is a total allocation of 100 instances of "Department" … -
Is it secure to log in a user without a password? [closed]
I am thinking of logging a user in to my Django website by verifying the email rather than them having to write a password. If this is not clear, this is what I'm thinking: User enters email User gets a email containing a code User enters code in website User is logged in Is this safe to do without hackers accessing the accounts of other users? -
How to remove django-celery-beat models from admin?
I'm trying to remove the default django_celery_ beat models from admin page. I tried to to use unregister method but it giving an error from django_celery_beat.models import ( IntervalSchedule, CrontabSchedule, SolarSchedule, ClockedSchedule, PeriodicTask, ) admin.site.unregister(SolarSchedule) admin.site.unregister(ClockedSchedule) admin.site.unregister(PeriodicTask) admin.site.unregister(IntervalSchedule) admin.site.unregister(CrontabSchedule) Error: raise NotRegistered('The model %s is not registered' % model.name) django.contrib.admin.sites.NotRegistered: The model SolarSchedule is not registered def INSTALLED_APPS(self): rv = [ 'django.contrib.admin', 'django.contrib.auth', ... 'django_celery_beat', ] How can I solve that? -
Representing django table in HTML display custom subset of columns
I want to display a table in django based on a model with lots of columns but only display columns based on a form selection by the user delivered as a get request. The view looks like this: from utils import potential_col_list def display_table(request): cols_to_display = [] model_filter = ModelFilter(request.GET) query_set = model_filter.qs.values(*potential_col_list) for key, value in request.GET.items(): if key in potential_col_list: cols_to_display.append(key) return render(request, 'project/display_table.html', {'queryset': query_set, 'cols_to_display': cols_to_display}) What I want to have displayed is the query set but only the columns that the user has specified in the get request used in the filter. The display_table.html template looks like this. <table> <thead> <tr> {% for col in cols_to_display %} <th> {{ col }} </th> {% endfor %} </tr> </thead> <tbody> {% for item in queryset %} <tr> {% for col in cols_to_display %} <td> {{ item.col }} </td> {% endfor %} </tr> {% endfor %} </tbody> </table> The table headings render correctly but none of the data from the queryset appears. When I try to display everything without the cols_to_display it renders fine. -
Adding data from a form written in vue.js to a Django model
I am building a (relatively simple) booking system for a website using Django. The frontend of the website is written in Vue.js in a single-page format. I need one form that user fills to reserve a given room at a given datetime. Initially, I wanted to create the form myself using Django ModelForms but found it might be hard for the front-end to style it later on. Hence, I'm considering letting the front-end create the form but the question is how do I get the data from that form and input it in my Django model so it appears in the SQLite database. The form should also communicate with my database so the user can book only available timeslots. I am quite new to all this and a bit confused on how to proceed. Any tips or guidance will be very much appreciated. For now I have Reservation model that should be fiiled with data when form is submitted: class Reservation(models.Model): room=models.ForeignKey(Room, on_delete=models.CASCADE) time_slot= models.ForeignKey(TimeSlot, on_delete=models.CASCADE) first_name=models.CharField(max_length=255) last_name=models.CharField(max_length=255) number_of_ppl=models.IntegerField() email= models.EmailField(max_length=255) phone_number=models.CharField(max_length=50) invoice=models.BooleanField(default=False) comments=models.CharField(max_length=255) time_slot references TimeSlot model which contains a datetime linked to a particular room. -
Find queryset where one field is greater than another one
I have model Shop, I want to get all shops which time_open(opening time) is more than time_closed(closing time). For example 23:00:00 is more than 07:00:00 (Shop_2(Night shift shop)). class Shop(models.Model): time_open = models.TimeField() time_closed = models.TimeField() for example i have two objects: shop_1 = { "time_open": "08:00:00", "time_closed": "22:00:00" } shop_2 = { "time_open": "23:00:00", "time_closed": "07:00:00" } My goal is to output queryset in which shop_2 would be. These timestamps in these objects only for visual example, i want to do it without putting any data in sql query. I want to achive this by comparing time_open and time_closed fields. I found similar question in pure SQL: Find rows where one field is greater than another one My goal is to do it with Django ORM. -
How to fiilter isnull false value in Django-filters?
I want to only filter category which has channels__livestream__isnull=False. The Queryset is working fine with this paremter but the Django-filters getting error TypeError: 'FilterSetMetaclass' object is not iterable. filters.py class CategoryFilterSet(django_filters.FilterSet): has_live_stream = django_filters.BooleanFilter( field_name='channels__livestream', lookup_expr='isnull', ) class Meta: model = YTCategory fields = ['has_live_stream'] views.py class CategoryList(generics.ListAPIView): authentication_classes = [] permission_classes = [] queryset = YTCategory.objects.active() pagination_class = Pagination serializer_class = CategorySerializer filter_backends = [DjangoFilterBackend, filters.SearchFilter] filterset_fields = CategoryFilterSet search_fields = ['id', 'name'] -
when I want to put my django app to elastic beanstalk in aws it gives me this error and I do not know how to fix it
when I want to put my Django app to elastic beanstalk in AWS it gives me this error and I do not know how to fix it -
NoReverseMatch at / - not understanding reason
I am trying to create a 'edit settings/ view profile page' drop down item in my navbar. The functionality was working prior to being called from the drop down which now throws the NoReverseMatch error as shown below: Reverse for 'show_profile_page' with arguments '('',)' not found. 1 pattern(s) tried: ['subs/(?P[0-9]+)/profile/\Z'] I am struggling to understand why this error is occuring when I am calling this url in other templates with no issues, but now that I tried putting this in a dropdown, I am getting this. Should I be doing a reverse call in the views.py? Would appreciate any pointers... **urls.py ** (subs app) from django.urls import path from .views import UserRegisterView, UserEditView, PasswordsChangeView, ShowProfilePageView, EditProfilePageView #from django.contrib.auth import views as auth_views from . import views urlpatterns = [ path('register/', UserRegisterView.as_view(), name='register'), path('edit_profile/', UserEditView.as_view(), name='edit_profile'), #path('password/', auth_views.PasswordChangeView.as_view(template_name='registration/change-password.html')), path('password/', PasswordsChangeView.as_view(template_name='registration/change-password.html')), path('password_success', views.password_success, name="password_success"), path('<int:pk>/profile/', ShowProfilePageView.as_view(), name="show_profile_page"), path('<int:pk>/edit_profile_page/', EditProfilePageView.as_view(), name="edit_profile_page") ] views.py (subs app) from django.shortcuts import render, get_object_or_404 from django.views import generic from django.views.generic import DetailView from django.contrib.auth.forms import UserCreationForm, UserChangeForm, PasswordChangeForm from django.urls import reverse_lazy from .forms import SignUpForms, EditProfileForm, PasswordUpdateForm from django.contrib.auth.views import PasswordChangeView from nooz2.models import Profile # Create your views here. class UserRegisterView(generic.CreateView): form_class = SignUpForms template_name … -
How to override the default formfield for a read only foreign keys field in Django ModelAdmin?
I am overriding the default formfield of foreign keys on ModelAdmins as described here. However, I am not overriding it to return a subset, but instead to defer fields in order to optimize the performance. For example: class MyModelAdmin(admin.ModelAdmin): def formfield_for_foreignkey(self, db_field, request, **kwargs): if db_field.name == "car": kwargs["queryset"] = Car.objects.only("name") return super().formfield_for_foreignkey(db_field, request, **kwargs) It works for most of my use cases, but the problem occurres when the foreign key is set as a read only field. While debugging, I noticed that when it is set as read only, the field is never passed through formfield_for_foreignkey method and the query retrieving the foreign key selects all fields instead of only the necessary ones. In my case, some of the fields are too big causing an unecessary terrible performance. I also tried the second method described in the docs, using ModelForm.__init__(), but it is not really useful for my use case. -
WORKON is not recognized as the name of a cmdlet
PS C:\Users\HP\travelproject> workon myproject workon : The term 'workon' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. At line:1 char:1 + workon myproject + ~~~~~~ + CategoryInfo : ObjectNotFound: (workon:String) [], CommandNotFoundException + FullyQualifiedErrorId : CommandNotFoundException your text Already installed virtual enivronment in cmd . -
How to change model attribute in template django?
There are model: class Employee(models.Model): name = models.CharField(max_length=100) position = models.CharField(max_length=100) hired_at = models.DateField(auto_now=True) salary = models.DecimalField(max_digits = 9, decimal_places= 2) boss = models.ForeignKey('self', null=True,blank=True, on_delete=models.CASCADE) has_boss = models.BooleanField(null=True) def __str__(self): return f'<{self.pk}> {self.name} - {self.position}' And there are template for nested bosses: {%if employee.has_boss %} <div class="nested_leaf" <ul> {% include "tree_view_template.html" with employee=employee.boss employee.has_visited = True %} </ul> </div> {% endif %} <div class="leaf"> {% if not employee.has_visited %} <li> <{{ employee.id }}>{{ employee.name }} - {{employee.position}} </li> {% endif %} </div> Can i change attribute in django template? In this configuration i have an error with employee.has_visited=True -
django foreignkey and create index
Im currently working on a DRF api, and need to remove ForeignKey from model in models Note and Comment. I was told i need to replace the FK with an index in that column instead. Ive looked into the relationship and can't think of a way to maintain the many to one. Im working with a Postgresql db and Note as the parent model and comment as the child. My question- Is there an altenative way of making this happen(removeing the FK on both models and still maintaining the ManyToOne? and how would i replace the FK column with an index?) thank you for any possible help. Models.py class Note(models.Model): creator = models.CharField(auth.models.User, on_delete = models.CASCADE) content = models.TextField(max_length= 200) def __str__(self): return self.content class Comment(models.Model): content = models.TextField(max_length= 200) creator = models.ForeignKey( auth.models.User, related_name="comments", on_delete=models.CASCADE note = models.ForeignKey("Note", related_name="comments", on_delete=models.CASCADE) serializer.py class CommentSerializer(serializers.ModelSerializer): creator = serializers.ReadOnlyField(source="creator.username") class Meta: model = Comment fields = ["uuid", "content", "creator", "notes"] class NoteSerializer(serializers.ModelSerializer): creator = serializers.ReadOnlyField(source="creator.username") comments = serializers.PrimaryKeyRelatedField(many=True, read_only=True) class Meta: model = Note fields = ["type", "content", "creator", "comments"] -
Why django filter is not working for not case sensitive search
I am trying to fetch the data from django models, where as TaskBlockers.objects.filter(task__project=1,task__team='Backend') gives queryset with 3 objects TaskBlockers.objects.filter(task__project=1,task__team='backend') gives empty queryset. it was supposed to return same for both the queries isn't it? if now why is this happening and how can I rectify it for both type of input. here are my models. class TaskBlockers(models.Model): task = models.ForeignKey(ProjectTask,on_delete=models.SET_NULL,null=True,related_name='task_id_related') blocker = models.CharField(max_length=100,null=False) class ProjectTask(models.Model): project = models.ForeignKey(Projects,on_delete=models.SET_NULL,null=True) team = models.CharField(max_length=10) task_title = models.CharField(max_length=200,null=False) task_desc = models.TextField(blank=True) -
How to give the data to serializer with JSONField
I have model and serializer with JSONField class Profile(models.Model): user = models.OneToOneField(User,on_delete=models.CASCADE) detail = models.JSONField(default=dict) def __str__(self): return self.user.username class ProfileSerializer(ModelSerializer): class Meta: model = m.Profile fields = '__all__' Then,I want to set the data to serializer class, However some how serializer.is_valid() faild. I have tested two pettern data1 data2 temp_data = {"data":"test"} data1 = {"detail":temp_data} # test_data1 data2 = {"detail":json.dumps(temp_data)} # test_data2 print(data1) # {'detail': {'data': 'test'}} print(data2) # {'detail': '{"data": "test"}'} instance = self.get_object() serializer = self.get_serializer(instance,data = data1) # or data2 if serializer.is_valid(): # serializer else: print("is_valid failed") What data should I give to this serializer? And is there any method to debug is_valid()?