Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings
views.pyI want to test the function. An error occurs when starting the DEBUG mode. manage.py In manage.py ш didn't change anything -
How to display categories and subcategories that belong to their categories in django?
My scenario: I'm having three tables, Category, Subcategory, Products. While inserting new product, there are two select boxes 1st select is for Category (its working) 2nd is for Subcategory, which should be relevant to the 1st select. Needs to show subcategory table inside bets categories. (it doesn't work properly) Subcategory table has category id as a foreign key. I am a beginner, please somebody help. My models.py from django.db import models from django.urls import reverse class Category(models.Model): cat_name = models.CharField(max_length=25, verbose_name='Categ', db_index=True) cat_slug = models.SlugField(max_length=255, unique=True, db_index=True, verbose_name="SLUG") def __str__(self): return self.cat_name def get_absolute_url(self): return reverse('category', kwargs={'cat_slug': self.cat_slug}) class Meta: ordering = ['cat_name'] class SubCategory(models.Model): category = models.ForeignKey('Category', on_delete=models.SET_NULL, related_name='category', null=True, blank=True, db_index=True, verbose_name='Categ') scat_name = models.CharField(max_length=25, unique=True, db_index=True, verbose_name='Name') scat_slug = models.SlugField(max_length=255, unique=True, db_index=True, verbose_name="SLUG") def __str__(self): return self.scat_name def get_absolute_url(self): return reverse('subcategory', kwargs={'scat_slug': self.scat_slug}) class Meta: ordering = ['scat_name'] class Product(models.Model): price = models.IntegerField(default=0, verbose_name="Price") category = models.ForeignKey('Category', on_delete=models.SET_NULL, related_name='products', null=True, verbose_name="Categ") subcategory = models.ForeignKey('SubCategory', on_delete=models.SET_NULL, related_name='products', null=True, verbose_name="SubCateg") title = models.CharField(max_length=255, db_index=True, verbose_name="Title") slug = models.SlugField(max_length=255, unique=True, db_index=True, verbose_name="URL") content = models.TextField(blank=True, verbose_name="Text") photo = models.ImageField(upload_to="images/%Y/%m/%d/", verbose_name="Photo") time_create = models.DateTimeField(auto_now_add=True, verbose_name="Created") time_update = models.DateTimeField(auto_now=True, verbose_name="Updated") is_published = models.BooleanField(default=True, verbose_name="Published") def __str__(self): return self.title def get_absolute_url(self): return reverse('product', … -
how to make fields required in django restframework
I build a blog API and the Post model is: the problem is when i want to create a post with no body content the error is class Post(models.Model): STATUS_CHOICES = [ ('P', _('Published')), ('D', _('Draft')), ('R', _('reject')) ] title = models.CharField(verbose_name=_("title"), max_length=255) slug = models.SlugField(null=True, unique=True, allow_unicode=True) lead = models.CharField(verbose_name=_( "lead"), max_length=1024, blank=True, null=True) body = models.TextField(verbose_name=_("context")) thumbnail = models.ImageField(verbose_name=_( "thumbnail"), upload_to='posts', blank=True, null=True) author = models.ForeignKey(UserAccount, verbose_name=_( "author"), on_delete=models.CASCADE) status = models.CharField( _("status"), max_length=1, choices=STATUS_CHOICES, default=STATUS_CHOICES[1][0]) publish_time = models.DateTimeField( verbose_name=_("published at"), default=timezone.now) created_at = models.DateTimeField( verbose_name=_("created at"), auto_now_add=True) updated_at = models.DateTimeField( verbose_name=_("updated at"), auto_now=True) category = models.ManyToManyField( Category, verbose_name=_("Categorys"), related_name='Categorys') like_count = models.IntegerField(verbose_name=_("like"), default=0) dislike_count = models.IntegerField(verbose_name=_("dislike"), default=0) def save(self, *args, **kwargs): self.slug = slugify(self.title) super(Post, self).save(*args, **kwargs) class Meta: ordering = ['-publish_time'] def __str__(self): return self.title class PostListSerializer(ModelSerializer): dietale_url = HyperlinkedIdentityField( view_name='api:Post_detail' ) author = SerializerMethodField() class Meta: model = Post fields = [ 'title', 'author', 'lead', 'dietale_url', ] def get_author(self, obj): return obj.author.name the problem is when i want to create a post it return the erorr: { "title": [ "This field is required." ] } There are more fields required like author body and ... whay just the title is the required field what happens … -
Unrecoverable error: TypeError in celery on heroku
I deployed my django application to heroku and I need periodic tasks in it. versions: django-celery-beat==2.4.0, celery==5.2.7, redis==4.4.2, kombu==5.2.4 I tried different versions of celery, redis, kombu and nothing worked -
Using Django JWT authorization for FastAPI endpoint
I have a Django app where I use SIMPLE_JWT to authenticate users. I use Django to work with the admin panel, in addition, I use the Django rest framework to transfer data to the React frontend application. During authorization, the React application receives a JWT token, which is then passed along with any requests to Django rest framework endpoints. Now there is a need to create a new FastAPI endpoint. Is there any way to make FastAPI use the same JWT tokens that the Django application accepts (and creates) to check whether the user is authorized and has access rights to the FastAPI endpoint? How to do it most correctly? -
Docker enrtypiont not found on django app with alpine python
This is my Dockerfile: FROM python:alpine3.17 # Keeps Python from generating .pyc files in the container ENV PYTHONDONTWRITEBYTECODE=1 # Turns off buffering for easier container logging ENV PYTHONUNBUFFERED=1 WORKDIR /app # install psycopg2 dependencies RUN apk update \ && apk add postgresql-dev gcc python3-dev musl-dev COPY Pipfile /app COPY Pipfile.lock /app RUN pip install pipenv RUN pipenv install --system COPY . /app USER root RUN chmod +x /app/entrypoint-prod.sh ENTRYPOINT ["/app/entrypoint-prod.sh"] When I run the image, this is the output: exec /app/entrypoint-prod.sh: no such file or directory This error occured only when I moved from FROM python:3.10 to FROM python:alpine3.17 I tried the following but didn't work also: USER root RUN chmod +x entrypoint-prod.sh ENTRYPOINT ["./entrypoint-prod.sh"] -
Django how to use a ModelChoiceField in a formset_factory
I am trying to use a modelchoicefield from the form in a formset_factory but i dont understand the error and don't know how to solve it. views.py def routecreate_view(request): orderformset = formset_factory(OrdersRouteForm, can_delete=False, extra=1) if request.method == 'POST': form = RouteForm(request.POST) formset = orderformset(request.POST) if form.is_valid() and formset.is_valid(): # process the data in form.cleaned_data as required messages.success(request, "You succesfully created an route.") return HttpResponseRedirect(reverse('planner.dashboard')) else: form = RouteForm() formset = orderformset() return render(request, 'planner/route.html', {'form': form, 'formset': formset}) forms.py class OrdersRouteForm(forms.ModelForm): route = ModelChoiceField( queryset=Order.objects.filter(status=1, delivery_until__gte=datetime.datetime.now(), deleted_at=None), label='Order') class Meta: model = Order fields = ("route",) def __init__(self, *args, **kwargs): super(OrdersRouteForm, self).__init__(*args, **kwargs) for visible in self.visible_fields(): visible.field.widget.attrs['class'] = 'form-control m-2' self.fields['route'].label_from_instance = self.label_from_instance @staticmethod def label_from_instance(obj): return "pallets: %s, %s, %s, %s" % (obj.pallet_amount, obj.street, obj.city, obj.postal_code) template: {% extends 'base.html' %} {% block base %} <div class="container rounded bg-white mt-5 mb-5"> <div class="row"> <div class="col-md-5 border-right mx-auto"> planner//route <div class="p-3 py-5"> <form id="form-container" method="POST"> {% csrf_token %} {{ form }} {{ formset }} <button id="add-form" type="button">Add Another Bird</button> <button class="btn btn-danger profile-button mt-3" onclick="window.history.back()">Cancel </button> <button class="btn btn-primary float-end mt-3" type="submit">Order</button> </form> </div> </div> </div> </div> {% endblock %} error: Cannot assign "<Order: Order object (2)>": "Order.route" must … -
Djongo - how to add custom migration using raw mongodb command
I have a legacy mongodb database. And I create a django application witch uses it. Djongo is used as a database provider. I want to add a custom update in my migration file: db.collection1.updateMany({}, [{$set:{"field2": "$field1.id"}}]) I trid to add this command to migration file but it leads to an error: operations = [ migrations.RunSQL(""" update collection1 set field2 = "$field1._id" """), ] What is the correct way to add this command to migration? -
Safely store data from GET request - Django
Alright, Let's say we need to create a website with Django where people can book a lodge for the weekends. We add a search form on the homepage where people can fill in the check-in and check-out date to filter for all available lodges. We use a generic Listview to create an overview of all the lodges and we overwrite the queryset to grab the search parameters from the GET request to create a filtered view. views.py class ListingsView(ListView): """Return all listings""" model = Listing template_name = 'orders/listings.html' def get_queryset(self): """ Visitors can either visit the page with- or without a search query appended to the url. They can either use the form to perform a search or supply an url with the appropriate parameters. """ # Get the start and end dates from the url check_in = self.request.GET.get('check_in') check_out = self.request.GET.get('check_out') queryset = Calendar.objects.filter( date__gte=check_in, date__lt=check_out, is_available=True ) return queryset Now this code is simplified for readability, but what I would like to do, is store the check-in and check-out date people are searching for. Updated views.py class ListingsView(ListView): """Return all listings""" model = Listing template_name = 'orders/listings.html' def get_queryset(self): """ Visitors can either visit the page with- or … -
Prevent RawSQL injection in Django
In my Django application I am using RawSQL queries as an additional security layer, I want to parse every RawSQL query to prevent delete or update operation. example : There are some automated jobs scheduled from django admin panel which utilise the RawSQL queries while execution I need a method to add a validation layer over the rawsql execution so that I can prevent execution of any delete, update etc queries. -
request.user.is_authenticated does not work after changing urls
So my code looked like this at first: views.py from django.shortcuts import render, redirect from django.http import HttpResponse from .models import Information from django.db.models import Q from django.contrib import messages from django.contrib.auth import authenticate, login, logout from .forms import MyForm # rooms = [ # {'id': 1, 'name': 'Lets learn python!'}, # {'id': 2, 'name': 'Design with me'}, # {'id': 3, 'name': 'Frontend developers'}, # ] def home(request): q = request.GET.get('q') if request.GET.get('q') !=None else '' information_search = Information.objects.filter( Q(host__icontains=q) | Q(hostname__icontains=q) | Q(port__icontains=q) | Q(platform__icontains=q) | Q(username__icontains=q) | Q(password__icontains=q) | Q(groups__icontains=q) ) sort_info = [] informations = Information.objects.all() for i in informations: if i.groups not in sort_info: device_group = i.groups sort_info.append(device_group) information_count=information_search.count() context = {'informations':informations, 'information_search':information_search, 'information_count':information_count, 'sort_info':sort_info} return render(request, 'polls/home.html', context) def view_data(request, pk): information = Information.objects.get(id=pk) context = {'information':information} return render(request, 'polls/view_data.html', context) def loginPage(request): if request.method == 'POST': username = request.POST.get('username') password = request.POST.get('password') try: user = User.objects.get(username=username) except: messages.error(request, 'User does not exist') user = authenticate(request, username=username, password=password) if user is not None: login(request, user) return redirect('home') else: messages.error(request, "Username or password does not exist") context = {} return render(request, 'polls/login_register.html', context) def logoutUser(request): logout(request) return redirect('home') def edit_data(request, pk): information = Information.objects.get(id=pk) form = … -
django calender tools missing (not shown) when loaded via ajax call
I need to have a model change_form that will call a 'child form' when a change is detected in it's select field. This is from admin.py class SuratAdmin(admin.ModelAdmin): change_form_template = 'surat_form_htmx.html' admin.site.register(Surat, SuratAdmin) and this is template 'surat_form_htmx.html' {% extends "admin/change_form.html" %} {% block after_field_sets %} <!--- add htmx --> {% load static %} <script src="https://unpkg.com/htmx.org@1.6.0"></script> <script src="{% url 'js-catlog' %}"></script> <!--script src="{% static '/admin/js/core.js' %}"></script--> <!--link rel="stylesheet" href="{% static 'admin/css/base.css' %}"--> <link rel="stylesheet" href="{% static 'admin/css/widgets.css' %}"> <script src="{% static '/admin/js/calendar.js' %}"></script> <script src="{% static '/admin/js/admin/DateTimeShortcuts.js' %}"></script> <style> /* DivTable.com */ .divTable{ display: table; width: 100%; } .divTableRow { display: table-row; } .divTableCell, .divTableHead { border: 1px solid #999999; display: table-cell; padding: 3px 10px; } .divTableHeading { display: table-header-group; font-weight: bold; } .divTableFoot { background-color: #EEE; display: table-footer-group; font-weight: bold; } .divTableBody { display: table-row-group; } </style> <!-- dummy hidden input needed for js --> <input id="loaded_object" type="hidden" size="20" readonly {% if not add %} value="{{ original.pk }}" {% endif %}> <p> <!-- eof ndummy hidden input needed for js --> <div id="htmx_get_result"> </div> <!-- evt listener id_template change--> <script> const selectElement = document.querySelector("#id_template"); const url_base = "/mst/htmx/child_form"; selectElement.addEventListener('change', (event) => { var template_id = document.getElementById("id_template").value ; var surat_id … -
How to use two different ports for frontend and backend with the same domain name
I am very new to django and nginx and trying to host my application using nginx as server. I am able to setup the frontend with domain name and 80 as the port but i am unable to setup backend with the domain name serving on port 8000. But when i use the IP address it seems to work fine but not with the domain name. I have been trying since two days and nothing seems to work . Any help would be much appreciated. Frontend Config server{ listen 80; listen [::]:80; listen 443 ssl; include snippets/snakeoil.conf; server_name example.com; location = /favicon.ico { access_log off; log_not_found off; } location / { # reverse proxy for next server proxy_pass http://localhost:3000; proxy_http_version 1.1; proxy_headers_hash_max_size 512; proxy_headers_hash_bucket_size 128; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection 'upgrade'; proxy_set_header Host $host; proxy_cache_bypass $http_upgrade; } } Config For Backend server { listen 8000; server_name example.com; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /root/backend/lithexBackEnd; } location / { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } } -
DJango admin is serving static files from /media instead of /static
When I run my django app in production mode (ie without DEBUG), my admin site tries to serve static files from "/media" instead of "/static", which causes 404s This is what it's trying to serve. GET https://<domain>/media/admin/css/base.css But if I manually type in https://<domain>/static/admin/css/base.css It serves the static file correctly. So my "collectstatic" is working fine, but somehow the admin site is trying to serve from /media. I don't understand what settings would cause this. Everything I search for related to this is from before django 1.4 where there was a specific setting for admin media url. Other than that I don't see anyone else having this issue. I'm loosely following https://github.com/cookiecutter/cookiecutter-django and I'm on the latest version of django right now. I'm not sure what else to look for -
Is it possible to filter form field according to another field?
I want to choose only a car_model related to the selected vehicle_brand. Is it possible to do in django? Or need to use JS? Code example below: vehicle_brand = forms.ModelChoiceField(label='Brand', queryset=VehicleBrand.objects.all(), widget=forms.Select(attrs={'class': 'select form-select'})) car_model = forms.ModelChoiceField(label='Model', queryset=CarModel.objects.all(), widget=forms.Select(attrs={'class': 'select form-select'})) -
ModuleNotFoundError: No module named 'caching.base'
I am Adam Jon. Now, I am learning Django Framework. Yesterday I got a sample project from my boss. So Today I installed Django framework and ruined. But in installation, I discover mistake like ModuleNotFoundError: No module named 'caching.base'. But I couldn't find solve the way. So, I wish that you help me... Please Thank you I I researched Python tutorial and W3.school. -
cannot connect to the backend server running port 8000 using nginx, django and docker
I've spent two days trying to figure this out. I'm running docker containers that host a django+react website from a docker compose file. I can access the website on port 80 (IP: http://52.90.163.11:80), but I can't seem to access the django admin panel on port 8000 (IP should be http://52.90.163.11:8000 but it doesn't work). I'm using AWS to host my website. I simply want the backend container accessible via port 8000. I have two docker compose files. One I build on my local machine. After building on local machine, I push the images to dockerhub. The second dockerfile resides on the AWS server, and uses images from the first build. Here is my docker-compose file on my local machine to create the images. version: '3' services: backend: build: context: ./backend/src command: gunicorn djreact.wsgi --bind 0.0.0.0:8000 ports: - 8000:8000 depends_on: - pgdb pgdb: image: postgres environment: POSTGRES_HOST_AUTH_METHOD: trust volumes: - pgdata:/var/lib/postgresql/data frontend: build: context: ./frontend/gui volumes: - react_build:/frontend/build nginx: image: nginx:latest ports: - 80:8080 volumes: - ./nginx/nginx_setup.conf:/etc/nginx/conf.d/default.conf:ro - react_build:/var/www/react depends_on: - backend - frontend volumes: react_build: pgdata: Here is my dockerfile on my AWS server. It uses the images created on my local machine. version: '3' services: backend: image: ansariuminhaj/mynacode:mynacode-backend command: … -
OSError: [Errno 99] Address not available - sending e-mail from django app with gmail smtp
I am trying to send the email using smtp with django application. It is working on my local environment, but not working on production environment. File "/usr/local/lib/python3.9/site-packages/django/core/mail/message.py", line 298, in send return self.get_connection(fail_silently).send_messages([self]) File "/usr/local/lib/python3.9/site-packages/django/core/mail/backends/smtp.py", line 124, in send_messages new_conn_created = self.open() File "/usr/local/lib/python3.9/site-packages/django/core/mail/backends/smtp.py", line 80, in open self.connection = self.connection_class( File "/usr/local/lib/python3.9/smtplib.py", line 255, in __init__ (code, msg) = self.connect(host, port) File "/usr/local/lib/python3.9/smtplib.py", line 341, in connect self.sock = self._get_socket(host, port, self.timeout) File "/usr/local/lib/python3.9/smtplib.py", line 312, in _get_socket return socket.create_connection((host, port), timeout, File "/usr/local/lib/python3.9/socket.py", line 844, in create_connection raise err File "/usr/local/lib/python3.9/socket.py", line 832, in create_connection sock.connect(sa) OSError: [Errno 99] Address not available My settings files has credentials as below: EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_USE_TLS = True EMAIL_PORT = 587 DEFAULT_FROM_EMAIL = '********' EMAIL_HOST_USER = '*******' EMAIL_HOST_PASSWORD = '******' Tried with different credentials, but getting the same error. I tried to print the email credentials from django setting and it is correct. -
We can swap the order of the answers every time a quiz game is started
ich möchte, dass die antworten ({{q.op1}},{{q.op2}},{{q.op3}},{{q.op4}}) nich immer an der selben stelle sind sondern gemischt werden. Zum Beispiel einmal : ({{q.op4}},{{q.op3}},{{q.op1}},{{q.op2}}) und der nächsten Frage wieder anders. Wie kann ich das machen? I want the answers ({{q.op1}},{{q.op2}},{{q.op3}},{{q.op4}}) are not always in the same place but are mixed. For example once : ({{q.op4}},{{q.op3}},{{q.op1}},{{q.op2}}) and the next question again different. How can I do that? html {% for q in questions %} {% if q.kategorie == category and q.flaag == True %} {% if questions.has_next %} <br/> <div class="flex-container"> <div class="container1"> <div class="game_options_top"> <div class="option"> <p><button class="option_btn" name="next" value="{{q.op1}}" formaction="{% url 'quiz' %}?page={{ questions.next_page_number }} " type="submit">A: <span id="option_span">{{q.op1}}</span></button></p> </div> <div class="option"> <p><button class="option_btn" name="next" value="{{q.op2}}" formaction="{% url 'quiz' %}?page={{ questions.next_page_number }} " type="submit">B: <span id="option_span">{{q.op2}}</span></button></p> </div> </div> <div class="game_question"> <h1 class="display_question">{{q.question}}</h1> </div> <div class="game_options_bottom"> <div class="option"> <p><button class="option_btn" name="next" value="{{q.op3}}" formaction="{% url 'quiz' %}?page={{ questions.next_page_number }} " type="submit">C: <span id="option_span">{{q.op3}}</span></button></p> </div> <div class="option"> <p><button class="option_btn" name="next" value="{{q.op4}}" formaction="{% url 'quiz' %}?page={{ questions.next_page_number }} " type="submit">D: <span id="option_span">{{q.op4}}</span></button></p> </div> </div> </div> models.py question = models.CharField(max_length=200, null=True,) op1 = models.CharField(max_length=200, null=True) op2 = models.CharField(max_length=200, null=True) op3 = models.CharField(max_length=200, null=True) op4 = models.CharField(max_length=200, null=True) ans = models.CharField(max_length=200, null=True) flaag = models.BooleanField('Aprroved', default=False) views.py if … -
Django ORM not releasing memory even when garbage collector is called explicitly
It seems like ORM objects are not releasing memory - please refer code below. I tried various approaches like, but nothing helped: Manually call gc.collect() Manually disable and enable gc Use queryset Use iterators Use lists In actual case, I query about 60K articles, and would like the memory to be released as soon as I am out of the function. The memory is not released even after days. So, I guess its not an issue with garbage collector. Please suggest. import gc import os import django import psutil from api.models import Article os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'mysite.settings') django.setup() def fetch_articles(): # gc.disable() # no help articles = Article.objects.order_by('-id')[:10].iterator() # articles = Article.objects.order_by('-id')[:10] # similar memory consumption # articles = list(Article.objects.order_by('-id')[:10]) # similar memory consumption for article in articles: pass del article del articles # gc.enable() # no help gc.collect() # gc.collect() # no help process = psutil.Process(os.getpid()) print(process.memory_info().rss / (1024 * 1024), "MB") # 41.203125 MB fetch_articles() # gc.collect() # no help print(process.memory_info().rss / (1024 * 1024), "MB") # 44.21875 MB -
Looks like your app is listening on 127.0.0.1. You may need to listen on 0.0.0.0 instead. Railway Deployment Django Sqlite3 db
Can anyone help me with this? How to change port from localhost to 0.0.0.0. -
How to add "Edit Function" in django
I need to add an edit button to my django app but it only redirects me to the homepage and no edit is saved. this is my views.py code, i think that's where the issue is coming from def editPhoto (request, pk): photo = Photo.objects.get(id=pk) categories = Category.objects.all() if request.method == 'POST': description = request.FILES.get('description') photo.save() return redirect ('/') context = {'categories': categories, 'photo': photo} return render(request, 'photos/edit.html', context)` models.py class Category(models.Model): name = models.CharField(max_length=100, null=False, blank=False) def __str__(self): return self.name class Photo(models.Model): category = models.ForeignKey( Category, on_delete=models.SET_NULL, null=True, blank=True) image = models.ImageField(null=False, blank=False) description = models.TextField() def __str__(self): return self.description` edit.html <div class="container"> <div class="row justify-content-center"> <div class="col"> <a href="{% url 'gallery' %}" class="btn btn-dark my-3">Go Back</a> <form method='POST' action="" enctype="multipart/form-data"> {% csrf_token %} <div style="height: 90vh;"> <img style="max-width: 100%; max-height: 100%;" src="{{photo.image.url}}" class="center" > </div> <div> <input required name="description" class="input" value="{{photo.description}}" type="text" size="60"></input> </div> <div class="center"> <button type="submit" class="btn btn-primary m-3; center">Update</button> </div> </div> </div> </div>` -
Why isn't the filename property getting set on my FileField instance?
This code is creating and updating objects with empty filename attributes: def _database_path(project, filename): return f'{project.id}/{filename}' database = models.FileField(upload_to=_database_path, storage=FileSystemStorage(location=/tmp/project_bucket)) The files are saved and retrieved without a problem, but the filename property is blank for this field. Why isn't this working (and what can I do to fix it)? -
django channels: notifications of message not working properly
I am writing a django module that handles real time message paired with notification. So far: a conversation can only take place between no more than 2 users. a notification should be sent after each message. I am currently working on getting the notifications to show up and the issue is that the notification gets rendered in the sender profile page and not in the recipient profile. I cant see where my error is Here is what I have done: consumers.py import json from channels.generic.websocket import AsyncWebsocketConsumer from channels.db import database_sync_to_async from .models import Chat, ChatRoom from accounts.models import User from asgiref.sync import sync_to_async from django.contrib.auth import get_user_model from django.shortcuts import get_object_or_404 from asgiref.sync import async_to_sync class ChatConsumer(AsyncWebsocketConsumer): async def connect(self): self.room_id = self.scope['url_route']['kwargs']['room_id'] self.room_group_name = 'chat_%s' % self.room_id await self.channel_layer.group_add( self.room_group_name, self.channel_name ) await self.accept() async def disconnect(self, close_code): await self.channel_layer.group_discard( self.room_group_name, self.channel_name ) async def receive(self, text_data): text_data_json = json.loads(text_data) message = text_data_json['message'] recipient = text_data_json['recipient'] self.user_id = self.scope['user'].id # Find room object room = await database_sync_to_async(ChatRoom.objects.get)(pk=self.room_id) print('ok1') # Create new chat object chat = Chat( content=message, sender=self.scope['user'], room=room, ) print('ok2') await database_sync_to_async(chat.save)() print("ok3") # get the recipient user recipient_user = await database_sync_to_async(User.objects.get)(id=recipient) print("ok4") await sync_to_async(chat.recipient.add)(recipient_user.id) print("ok5") await … -
django.db.utils.ProgrammingError: relation "pdf_conversion" does not exist
I am trying to add in a conversion model that is referenced in the fileurl model that calls my customuser model. But for some reason, I get the following error when loading the admin panel. Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. Internal Server Error: /admin/pdf/conversion/ Traceback (most recent call last): File "/home/john/PycharmProjects/pdf/venv/lib/python3.8/site-packages/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql, params) psycopg2.errors.UndefinedTable: relation "pdf_conversion" does not exist LINE 1: SELECT COUNT(*) AS "__count" FROM "pdf_conversion" ^ The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/home/john/PycharmProjects/pdf/venv/lib/python3.8/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/home/john/PycharmProjects/pdf/venv/lib/python3.8/site-packages/django/core/handlers/base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/john/PycharmProjects/pdf/venv/lib/python3.8/site-packages/django/contrib/admin/options.py", line 616, in wrapper return self.admin_site.admin_view(view)(*args, **kwargs) File "/home/john/PycharmProjects/pdf/venv/lib/python3.8/site-packages/django/utils/decorators.py", line 130, in _wrapped_view response = view_func(request, *args, **kwargs) File "/home/john/PycharmProjects/pdf/venv/lib/python3.8/site-packages/django/views/decorators/cache.py", line 44, in _wrapped_view_func response = view_func(request, *args, **kwargs) File "/home/john/PycharmProjects/pdf/venv/lib/python3.8/site-packages/django/contrib/admin/sites.py", line 232, in inner return view(request, *args, **kwargs) File "/home/john/PycharmProjects/pdf/venv/lib/python3.8/site-packages/django/utils/decorators.py", line 43, in _wrapper return bound_method(*args, **kwargs) File "/home/john/PycharmProjects/pdf/venv/lib/python3.8/site-packages/django/utils/decorators.py", line 130, in _wrapped_view response = view_func(request, *args, **kwargs) File "/home/john/PycharmProjects/pdf/venv/lib/python3.8/site-packages/django/contrib/admin/options.py", line 1697, in changelist_view cl = self.get_changelist_instance(request) File "/home/john/PycharmProjects/pdf/venv/lib/python3.8/site-packages/django/contrib/admin/options.py", line 736, in get_changelist_instance return ChangeList( File "/home/john/PycharmProjects/pdf/venv/lib/python3.8/site-packages/django/contrib/admin/views/main.py", line 100, in __init__ self.get_results(request) File …