Django community: Django Q&A RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Given a SQL query, can we find django code that generated it?
Given a SQL query, can we find django code that generated it? (reverse engineering database query to django code e.g. opposite/reverse of following operation) q = Item.objects.all() print(q.query) Input = db query = "SELECT * FROM table.Item" Output = django code = Item.objects.all() -
Django: Can I restore the live version of views.py if the file has been corrupted?
My django views.py somehow got corrupted. The live django site is still just fine. Is there some way to restore the version of views.py that is currently live? My last backup is 3 days ago. Otherwise, I'm out 3 days of work. -
Unable to reach Docker containerized Django Nginx Gunicorn app
I've clonned my git repo to the server (ubuntu 20.04) (for example it will be servername.com) and I can't reach it without any errors IDK, any ready FAQs don't help, and this is the first but not the only problem here. Dockerfile FROM python:3.10-alpine WORKDIR /Ritem ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 COPY reqs.txt . RUN apk add --no-cache postgresql-client build-base postgresql-dev gcc \ libc-dev linux-headers RUN python -m venv /venv && source /venv/bin/activate && \ pip install --upgrade pip && pip install --no-cache-dir -r reqs.txt COPY . . docker-compose.yml version: '3' services: web-backend: build: context: . command: sh -c 'source /venv/bin/activate && gunicorn --bind 0.0.0.0 absconfig.wsgi:application' volumes: - .:/Ritem - static_data:/Ritem/static expose: - 80000 nginx: image: nginx:1.25.0-alpine depends_on: - web-backend ports: - 80:8000 volumes: - static:/Ritem/static - ./nginx-conf.d:/etc/nginx/conf.d volumes: static_data: static: nginx .conf file server localhost:8000; } error_log /var/log/nginx/error.log; server { listen 80; server_name servername.com; root /www/data/; access_log /var/log/nginx/access.log; location / { proxy_pass http://ritem; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $host; proxy_redirect off; } error_page 500 502 503 504 /50x.html; location = /50x.html { root /usr/share/nginx/html; } } how is it running in docker? ok I'll tell you. It is running abs fine. The issue is not with gunicorn, because … -
How can I access Property Owner Details in Django
I have a Django View where all users (Landlord, Agent and prospect) can access and on this view, I want to display the name of the property owner on my template but I am only getting None displayed whenever a Prospect user is on the view. Understand that the three users have their Models with a OneToOneField relationship with the User Model. And I also have a Profile Model with the same relationship with the User Model. See the view code below: def property_detail(request, property_id): user = request.user #Check if user is authenticated if user.is_authenticated: #Check if user is Landlord if hasattr(user, 'landlord'): properties = Property.objects.filter(landlord=user.landlord).prefetch_related('agent').order_by('-last_updated')[:4] property_owner = user.landlord.profile if hasattr(user.landlord, 'profile') else None #Check if user is Agent elif hasattr(user, 'agent'): properties = Property.objects.filter(agent=user.agent).prefetch_related('landlord').order_by('-last_updated')[:4] property_owner = user.agent.profile if hasattr(user.agent, 'profile') else None else: properties = Property.objects.order_by('-last_updated')[:4] property_owner = None #Get the Property by its Product key from DB property_instance = get_object_or_404(Property, pk=property_id) #Send Notification to property owner if request.method == 'POST': form = MessageForm(request.POST) if form.is_valid(): content = form.cleaned_data['content'] subject = form.cleaned_data['subject'] Message.objects.create(property=property_instance, sender=user, recipient=property_owner, subject=subject, content=content) messages.success(request, 'Notification sent successfully with your Contact Details.') else: form = MessageForm() context = { 'form':form, 'properties':properties, 'property_owner': property_owner, 'page_title': 'Property Detail', … -
Static files won't load when using Vercel
When I host my project locally, everything works. My stylesheet loads without a problem, however when I deploy it to Vercel neither the admin static files nor my own load. Here is my settings.py: STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles_build', 'static') MEDIA_URLS ='/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') and my vercel.json: { "builds": [{ "src": "social/wsgi.py", "use": "@vercel/python", "config": { "maxLambdaSize": "15mb", "runtime": "python3.9" } }, { "src": "build_files.sh", "use": "@vercel/static-build", "config": { "distDir": "staticfiles_build" } }], "routes": [ { "src": "/static/(.*)", "dest": "/static/$1" }, { "src": "/(.*)", "dest": "social/wsgi.py" } ] } So far I have run the collect static command and I have tried changing the root and the url, but I am very lost and do not fully understand why it will not work. -
opencv and django !_src.empty() in function 'cv::cvtColor'
I use django and opencv to make picture gray after i press the button from django.shortcuts import render from .models import RawPhoto from django.http import Http404 import cv2 import numpy import os from django.conf import settings from PIL import Image # Create your views here. def main(request): if request.method == 'POST': prod = RawPhoto() prod.title = request.POST.get("title") if len(request.FILES) !=0: prod.img = request.FILES['photo'] prod.save() return render (request,'main.html') def detail(request,photo): photo =RawPhoto.objects.get(id=photo) if photo is not None: if request.method =="POST": mamont = cv2.imread("photo\media\maw_images"+str(photo.img)) gray = cv2.cvtColor(mamont, cv2.COLOR_BGR2GRAY) photo.img = Image.fromarray(gray) return render(request,'detail.html',{'photo':photo}) else: raise Http404('MOvie does not exist ') i want it so give back to frontend gray picture.In future im going to replace making gray to facial recognition,but i have started with such simple function,just to understand how does it work. -
No POST/create form in DRF Browsable API?
I am using Django Rest Framework (Django version=4.0.4, I know I need to upgrade, but I'm still learning the ropes and djangorestframework~=3.14.0) and Viewsets for an API, but I can't get the Browsable API POST form to show up on the list page. I can see the list of ParameterKeys (so I think urls.py and serializers.py are correct) and I'm using a superuser account so I don't think it's a permissions thing. What's wrong with my setup? I did notice that the Brave browser Agent request has 'text/html' and some 'application/xml', but no 'application/json'...not sure if that's it? Here is the relevant portion of the model: class ParameterKey(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) name = models.CharField(max_length=200) owner = models.ForeignKey(get_user_model(), on_delete=models.CASCADE, related_name='parameter_keys') def __str__(self): return self.name Here is the relevant portion of urls.py: from django.urls import path, include from rest_framework import routers from . import api_views router = routers.DefaultRouter() router.register(r'', api_views.ParameterViewSet) urlpatterns = [ path('', include(router.urls)), ] Here is the relevant portion of api_views.py: from rest_framework import viewsets, parsers from .models import ParameterValue, ParameterKey from .serializers import ParameterValueSerializer, ParameterKeySerializer from parameters.permissions import IsOwnerOrPublic # from django.http import JsonResponse # from django.views.decorators.csrf import csrf_exempt from rest_framework.permissions import AllowAny class ParameterKeyViewSet(viewsets.ModelViewSet): permission_classes = … -
Nested loop for foreign key in Django
Newby to Django here. I need to list some music genres and their subgenres. I got the genres just fine, but I'm not sure how to list the subgenres. This is my model: class Genre(models.Model): genre_id = models.AutoField(primary_key=True) code = models.CharField(unique=True, max_length=4) description = models.CharField(max_length=25, blank=False, null=False) class Meta: managed = False db_table = 'genre' db_table_comment = 'Music genre catalog' def __str__(self): return self.description class Subgenre(models.Model): subgenre_id = models.AutoField(primary_key=True) code = models.CharField(unique=True, max_length=6) description = models.CharField(max_length=25, blank=False, null=False) genre = models.ForeignKey(Genre, on_delete=models.CASCADE) class Meta: managed = False db_table = 'subgenre' db_table_comment = 'Music subgenre catalog' def __str__(self): return self.description This is what I have in views.py: def new_playlist(request): genres = Genre.objects.all().order_by('description') subgenres = Subgenre.objects.all() context = { 'genres':genres, 'subgenres':subgenres } return render(request,"applications/ecommerce/playlists/new-playlist.html",context) And this is my HTML code: {% for genre in genres %} <div class="card"> <div class="card-header"> <h5 class="mb-0">{{genre.description}}</h5> </div> <div class="card-body"> {% for subgenre in subgenres.genre.all %} <div class="row"> <label>{{subgenre.description}}</label> </div> {% endfor %} </div> </div> {% endfor %} -
ImproperlyConfigured( django.core.exceptions.ImproperlyConfigured: AUTH_USER_MODEL refers to model 'authen.CustomUser' that has not been installed
I wanted to customize default user model. that's why i created a fresh django project and haven't done migrations. i just wrote the code and saved it settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'authen', ] AUTH_USER_MODEL = 'authen.CustomUser' manager.py from django.contrib.auth.base_user import BaseUserManager class UserManager(BaseUserManager): use_in_migrations = True def create_user(self, email, password=None, **extra_fields): if not email: raise ValueError("Email is required") email = self.normalize_email(email) user = self.model(email=email,**extra_fields) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, password, **extra_fields): extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser',True) extra_fields.setdefault('is_active',True) if extra_fields.get('is_staff') is not True: raise ValueError("Super user must have is_staff true") return self.create_user(email, password, **extra_fields) models.py of authen app from django.db import models from django.contrib.auth.models import AbstractUser from .manager import UserManager class CustomUser(AbstractUser): email = models.EmailField(unique=True) phone = models.CharField(max_length=20) nid = models.CharField(max_length=17,unique=True) profile_picture = models.ImageField(upload_to='profile_pics', blank=True, null=True) objects = UserManager() REQUIRED_FIELDS=[] USERNAME_FIELD = 'email' class Meta: app_label = 'CustomUser' i haven't done any migrations and i'm using latest django and python3.1. i had to create several project for this reason. Ask me if more info is needed. -
CKEditor5Field not displaying correctly in read-only mode for restricted user roles in Django Admin
I'm encountering an issue with the CKEditor5Field in Django Admin when it's set to read-only mode for users with restricted roles. Specifically, when I log in with a user role that has write permissions, the CKEditor5Field works perfectly and displays the formatted text as expected. However, when I log in with a user role that only has read permissions, the CKEditor5Field does not render the HTML content properly. Instead, it displays the raw HTML tags without any formatting. models.py class SalesInfo(models.Model): feature_id = models.OneToOneField( FeatureFilm, on_delete=models.CASCADE, null=True, blank=True, editable=False ) ... sales_info = CKEditor5Field( verbose_name="Vertriebs Notizen", config_name="extends", null=True, blank=True ) ... admin.py class SalesInfoSetInLine(admin.StackedInline): raw_id_fields = [ "feature_id", "tv_movie_id", "tv_serie_season_id", "special_project_id", ] read_only_fields = [ "feature_id", "tv_movie_id", "tv_serie_season_id", "special_project_id", ] model = SalesInfo exclude = ["is_sound_restoration_offer"] classes = ["collapse"] extra = 1 # 1 is here ok formfield_overrides = { models.TextField: {"widget": Textarea(attrs={"rows": 12, "cols": 150})}, } I have also confirmed that I have correctly configured the CKEditor5 static files. I would greatly appreciate any assistance in understanding why the CKEditor5Field does not properly render the HTML content when set to read-only mode for users with restricted roles in Django Admin. If you have any suggestions or insights, please let … -
InvalidOperation at [<class 'decimal.InvalidOperation'>] in Django
I'm developing an app in Django and I'm having this error when the form is submitted: I'll share you my code This is my model: class Oferta(models.Model): titulo = models.CharField(verbose_name='Título', max_length=100, null=False, blank=False) descripcion = models.TextField(verbose_name='Descripción', null=True, blank=True) cantidad = models.PositiveSmallIntegerField(verbose_name='Cantidad', null=False, blank=False, default=1) valor = models.DecimalField(verbose_name='Valor', max_digits=3, decimal_places=2, null=False, blank=False) material = models.CharField(verbose_name='Material', max_length=20, null=False, blank=False, choices=MATERIAL_CHOICES) imagenes = models.ManyToManyField(ImagenesOferta, verbose_name='Imagenes de la Oferta', blank=True) usuario = models.ForeignKey(Usuario, verbose_name='Usuario', null=False, blank=False, on_delete=models.CASCADE) is_active = models.BooleanField(verbose_name='Activo/Inactivo', default=True) vendido = models.BooleanField(verbose_name='Vendido', default=False) fecha_creacion = models.DateTimeField(verbose_name='Fecha de Creación', auto_now_add=True) def __str__(self): return self.titulo class Meta: verbose_name = 'Oferta' verbose_name_plural = 'Ofertas', ordering = ['-fecha_creacion'] This is my view: login_required(login_url='login') def publish_offer(request): if request.method == 'POST': titulo = request.POST['titulo'] descripcion = request.POST['descripcion'] cantidad = request.POST['cantKilos'] valor = request.POST['valor'] material = request.POST['material'] imagenes = request.FILES['imagenes'] usuario = request.user oferta = Oferta(titulo=titulo, descripcion=descripcion, cantidad=cantidad, valor=valor, material=material, usuario=usuario) oferta.save() for imagen in imagenes: img = ImagenesOferta.objects.create(imagen=imagen) oferta.imagenes.add(img) And this is the fragment of my form that I think that could be tha problem: <div class="col-xl-4"> <div class="form-group"> <label for="valor" class="form-label">Agregar valor</label> <input type="number" class="form-control form-control-user" id="valor" name="valor" placeholder="0.00$"> </div> </div> By aesthetic and styling questions i decided to use a normal form -
Django list of users with count of events (appointments)
In my Django scheduling application in models.py I have a User class and an Appointment class. How can I display a table of users with the number of users and information on how many appointments the patient had in total in the html page. Table like: (number of patient/name of patient/number of appointments) and result like: (1/user1/3; 2/user2/5 ....) models.py class Pricelist(models.Model): service=models.CharField('Name of service', max_length=60) price=models.DecimalField(max_digits=6, decimal_places=2) valid=models.BooleanField("Valid", default=False) def __str__(self): return f"{self.service} = {self.price} EUR" class Patient(models.Model): name=models.CharField('Name and Surname', max_length=60) date_of_birth=models.CharField('Date of Birth', max_length=30, blank=True) address=models.CharField("Address", max_length=300) date_of_application=models.DateField(default=timezone.now) is_active=models.BooleanField(default=False) description = models.TextField(blank=True) def __str__(self): return self.name class Appointment(models.Model): id = models.AutoField(primary_key=True) user=models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True, limit_choices_to={'active': True},) appointment=models.ForeignKey(Pricelist, on_delete=models.CASCADE, null=True, blank=True) day=models.DateField(default=date) time_service = models.CharField(max_length=10, choices=TIME-CHOICE, default="16:00") is_paid = models.BooleanField(default=False) def __str__(self): return f"{self.user.name} | dan:{self.day} | time:{self.time_service} | service:{self.service.price}" class Meta: db_table = "tblappointment" i get information for every patient in view.py by id: def patient_statistics(request, patient_id): patient = Patients.objects.get(pk=patient_id) appointments = patient.appointment_set.all() appointment_count = patient.appointment_set.all().count() total_price = terms.aggregate(sum=Sum('treatment__price'))['sum'] return render(request, 'patients/patient_statistics.html', {"appointment_count":appointment_count, "patient":patient, 'terms':terms, 'total_price':total_price}) but I don't know how to make a summary table of patients and the number of treatments. I am asking for help. -
Django makemessages command warning: lone surrogate
I have a problem with django v4.2. When I use the command django-admin makemessages -d djangojs -l de I get a bunch of lines of this: .\venv\Lib\site-packages\django\contrib\admin\static\admin\js\vendor\xregexp\xregexp.min.js:136: warning: lone surrogate U+D820 .\venv\Lib\site-packages\django\contrib\admin\static\admin\js\vendor\xregexp\xregexp.min.js:136: warning: lone surrogate U+DC00 .\venv\Lib\site-packages\django\contrib\admin\static\admin\js\vendor\xregexp\xregexp.min.js:136: warning: lone surrogate U+DFFF .\venv\Lib\site-packages\django\contrib\admin\static\admin\js\vendor\xregexp\xregexp.min.js:136: warning: lone surrogate U+D821 .\venv\Lib\site-packages\django\contrib\admin\static\admin\js\vendor\xregexp\xregexp.min.js:136: warning: lone surrogate U+DC00 .\venv\Lib\site-packages\django\contrib\admin\static\admin\js\vendor\xregexp\xregexp.min.js:136: warning: lone surrogate U+DFEC Not sure why that happens but I think that because of that, djangojs.po is not created and I need it to translate inside javascript. Files: # urls.py urlpatterns = [ path('django-admin/', admin.site.urls), path('admin/', include('django.contrib.auth.urls')), ] urlpatterns += i18n_patterns( path('', include('website.urls', namespace='website')) ) urlpatterns += i18n_patterns( path("jsi18n/", JavaScriptCatalog.as_view(), name="javascript-catalog"), ) if 'rosetta' in settings.INSTALLED_APPS: urlpatterns += [ re_path(r'^rosetta/', include('rosetta.urls')) ] urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) # settings.py LANGUAGE_CODE = 'hr' TIME_ZONE = 'UTC' USE_I18N = True USE_TZ = True LANGUAGES = ( ('hr', _('Hrvatski')), ('en', _('Engleski')), ('de', _('Njemački')) ) LOCALE_PATHS = ( os.path.join(BASE_DIR, 'locale'), ) I tried different combinations with the command and a bunch of similar things but even when I manage to get rid of those warnings djangojs.po is not created which is my goal. -
error in importing pip installed libraries in django
I was trying to include map in my django project using folium module. I have installed folium in my virtualenvpip list in the virtualenv when i am writing "import folium" i get this I have tried to import another libraries after installing them through pip but they are also not working , I tried to find a solution online but failed , can you please help... -
Is the server running on that host and accepting TCP/IP connections?&
I am trying to create a superuser via: sudo docker-compose up python3 manage.py createsuper user In a minute i get this: django.db.utils.OperationalError: connection to server at "8500" (0.0.33.52), port 5432 failed: Connection timed out Is the server running on that host and accepting TCP/IP connections? Next, I check if my containers are running: sudo docker-compose ps And i get: NAME IMAGE COMMAND SERVICE CREATED STATUS PORTS credo1-db-1 postgres:latest "docker-entrypoint.s…" db 6 minutes ago Up 6 minutes 0.0.0.0:8500->5432/tcp, :::8500->5432/tcp credo1-web-1 credo1-web "python manage.py ru…" web 6 minutes ago Up 6 minutes 0.0.0.0:8000->8000/tcp, :::8000->8000/tcp In my settings: 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'clothing_store', 'USER': 'postgres', 'PASSWORD': 'postgres', 'HOST': 8500, 'PORT': 5432, } } docker-compose: `version: '3' services: db: image: postgres:latest volumes: - postgres_data:/var/lib/postgresql/data/ environment: - POSTGRES_USER=postgres - POSTGRES_PASSWORD=postgres - POSTGRES_DB=clothing_store ports: - "8500:5432" web: build: context: . dockerfile: Dockerfile command: python manage.py runserver 0.0.0.0:8000 volumes: - .:/code ports: - "8000:8000" depends_on: - db volumes: postgres_data:` I am trying to create a superuser via: sudo docker-compose up python3 manage.py createsuper user -
Handling delayed responses from server - Django Web App
I have a situation where a user is filling in a form on a django web app. Under normal circumstances the user will submit the form, the server will store the form in the db and display a success message. But, under the assumption that there are multiple users trying to submit the form at the same time and the server is timing out due to large amount of requests, I want to find and integrate a solution that acts as a queue and stores the data of the users when it is free instead of giving timeouts to the users. I want to do this since I do not want the users to fill in the form again from scratch. So, what is the best solution to this problem apart from increasing the server timeout settings? What package or method do I need to use to avoid the user's request from timing out and to be able to successfully store the user's form regardless of the delays. Note: I want to host my webapp on a single shared server, due to budget limitations I cannot afford a Load Balancer and multiple servers even though adding multiple servers will solve … -
Getting Error In Swagger(drf_yasg library) For Nested Serializers in Django
I'm using drf_yasg library in django. Normally everything was working correctly. When I use the nested serializer, I get the following error in the swagger interface. **Error: ** Internal Server Error: /swagger/ Traceback (most recent call last): File "C:\Users\userx1\OneDrive\Desktop\projectx_backend\venv\Lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) ^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\userx1\OneDrive\Desktop\projectx_backend\venv\Lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\userx1\OneDrive\Desktop\projectx_backend\venv\Lib\site-packages\django\views\decorators\csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\userx1\OneDrive\Desktop\projectx_backend\venv\Lib\site-packages\django\views\generic\base.py", line 70, in view return self.dispatch(request, *args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\userx1\OneDrive\Desktop\projectx_backend\venv\Lib\site-packages\rest_framework\views.py", line 509, in dispatch response = self.handle_exception(exc) ^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\userx1\OneDrive\Desktop\projectx_backend\venv\Lib\site-packages\rest_framework\views.py", line 469, in handle_exception self.raise_uncaught_exception(exc) File "C:\Users\userx1\OneDrive\Desktop\projectx_backend\venv\Lib\site-packages\rest_framework\views.py", line 480, in raise_uncaught_exception raise exc File "C:\Users\userx1\OneDrive\Desktop\projectx_backend\venv\Lib\site-packages\rest_framework\views.py", line 506, in dispatch response = handler(request, *args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\userx1\OneDrive\Desktop\projectx_backend\venv\Lib\site-packages\drf_yasg\views.py", line 94, in get schema = generator.get_schema(request, self.public) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\userx1\OneDrive\Desktop\projectx_backend\venv\Lib\site-packages\drf_yasg\generators.py", line 246, in get_schema paths, prefix = self.get_paths(endpoints, components, request, public) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\userx1\OneDrive\Desktop\projectx_backend\venv\Lib\site-packages\drf_yasg\generators.py", line 404, in get_paths operation = self.get_operation(view, path, prefix, method, components, request) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\userx1\OneDrive\Desktop\projectx_backend\venv\Lib\site-packages\drf_yasg\generators.py", line 446, in get_operation operation = view_inspector.get_operation(operation_keys) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\userx1\OneDrive\Desktop\projectx_backend\venv\Lib\site-packages\drf_yasg\inspectors\view.py", line 32, in get_operation body = self.get_request_body_parameters(consumes) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\userx1\OneDrive\Desktop\projectx_backend\venv\Lib\site-packages\drf_yasg\inspectors\view.py", line 82, in get_request_body_parameters return self.get_request_form_parameters(serializer) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\userx1\OneDrive\Desktop\projectx_backend\venv\Lib\site-packages\drf_yasg\inspectors\view.py", line 134, in get_request_form_parameters return self.serializer_to_parameters(serializer, in_=openapi.IN_FORM) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\userx1\OneDrive\Desktop\projectx_backend\venv\Lib\site-packages\drf_yasg\inspectors\base.py", line 448, … -
Is Django Template legacy?
Django, as a backend framework, has the main purpose of returning JSON-format data to the frontend developer. So why do we need templates to render HTML with Django? We can use React for the frontend and Django for the backend to provide data via API. The problem is: is this technology a legacy? Does anyone or the company use templates to render the frontend using Django for now in a real project? Also, I am a noob in backend development, so can anybody tell me what backend developers work on exactly except create APIs and make databases? -
Django: cant relate my comment to a specific product
I dont know how to link comments to specific product(object). Maybe there is something to do with slugs. P.S. All the comments can be successfully uploaded to the database, but the problem is only with linking them with one product views.py class ProductDetail(DetailView): model = Product template_name = 'store/product-single.html' context_object_name = 'product' def get_context_data(self, **kwargs): context = super().get_context_data() products = Product.objects.all()[:4] context['products'] = products product = Product.objects.get(slug=self.kwargs['slug']) context['title'] = product.title context['comment_form'] = CommentForm() context['comments'] = Comment.objects.all() return context def save_comment(request): form = CommentForm(request.POST) if form.is_valid(): comment = form.save(commit=False) # comment.product = Product.objects.filter() comment.save() return redirect('index') urls.py path('save_comment/', save_comment, name='save_comment') product-single.html <div class="container"> <form action="{% url 'save_comment' %}" method="POST"> {% csrf_token %} {{ comment_form.as_p }} <button type="submit" class="btn btn-primary btn-lg">Submit</button> </form> </div> models.py class Comment(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE, null=True) user = models.CharField(default='', max_length=255) text = models.TextField(default='') forms.py class CommentForm(forms.ModelForm): class Meta: model = Comment fields = ['user', 'text'] widgets = { 'user': forms.TextInput(), 'text': forms.Textarea() } -
Django Websocket giving error when connecting in video call app
I am using Django websocket for making a real video chat app and I am beginner in Websocket. I/m trying that user first give the room name and then the username and then it will be connected to the meeting room. I've written it like below For Routing.py from django.urls import re_path from . import consumers websocket_urlpatterns = [ re_path(r'ws/(?P<room_name>\w+)/(?P<name>\w+)/$', consumers.ChatVideoConsumer.as_asgi()) ] For urls.py from django.urls import path from . import views urlpatterns = [ path('<str:room_name>/<str:name>/', views.index, name='index'), ] For Views.py from django.shortcuts import render # Create your views here. def index(request, *args, **kwargs): return render(request, "chat/room.html") For Room.js console.log("Hello World from room.js"); console.log(window.location.pathname); let wsStart = "ws://"; const loc = window.location; if(loc.protocol === "https:") { wsStart = "wss://"; } const endpoint = wsStart + loc.host + loc.pathname; console.log("Endpoint", endpoint); const websocket = new WebSocket(endpoint); websocket.onopen = (e) => { console.log("Open", e); }; // websocket.onmessage = (e) => { // console.log("Message", e); // }; websocket.onclose = (e) => { console.log("Close", e); }; For Consumers.py from channels.generic.websocket import AsyncWebsocketConsumer import json class ChatVideoConsumer(AsyncWebsocketConsumer): async def connect(self): print("connect") await self.accept() self.send(text_data=json.dumps({ "type" : "Message.Accept", "message" : "Hello Connect Established" })) async def disconnect(self, close_code): pass asgi.py import os from channels.routing import ProtocolTypeRouter, … -
How to Mock test for sending email post signup using celery in DRF
Post signup of an user in RegisterUserAPIView, i'm using a celery task to send email for verification. views.py class RegisterUserAPIView(generics.GenericAPIView): serializer_class = RegisterUserSerializer def post(self, request): serializer = self.serializer_class(data = request.data) if serializer.is_valid(): serializer.save() # Get the email from serializer and use it to send email for email verification. user_email = serializer.validated_data['email'] send_verification_email_task.delay(user_email = user_email) return Response(serializer.data, status = status.HTTP_201_CREATED) return Response(serializer.errors, status = status.HTTP_400_BAD_REQUEST) task.py def send_verification_email_task(user_email): ... response = send_verification_email(user_email=user_email) ... return "Successfully sent verification email to %s" % user_email email.py def send_verification_email(user_email): ... try: email_message = EmailMultiAlternatives( subject = email_subject, body = text_content, from_email = email_from, to = [email_to] ) email_message.attach_alternative(html_content, "text/html") email_message.send() response = { "status" : 200 } except Exception: response = { "status" : 400 } return response I tried the following test scenarios I called post request using the client api but that sends an email each time test cases are run. I tried the following mock test scenario but that still shows that my code lines are not covered. This is the test case i tried here. class EmailTestCase(TestCase): def test_send_verification_email_task_success(self): with patch('auth_service.views.send_verification_email_task.delay') as mock_task: user_email = 'testuser@example.com' # Mock the send method of the send_verification_email_task mock_task.return_value = 'Successfully sent verification email … -
Django QuerySet union() is not giving the desired output
I have written the following code views.py room_list = Room.objects.all() time_slot_list = TimeSlot.objects.none() for room in room_list: time_slots = TimeSlot.objects.filter(room=room) for time_slot in time_slots: time_slot_list.union(time_slot_list, time_slot) print(time_slot_list) models.py class Room(models.Model): class Meta: ordering = ['number'] number = models.PositiveSmallIntegerField( validators=[MaxValueValidator(550), MinValueValidator(1)], primary_key=True ) CATEGORIES = ( ('Regular', 'Regular'), ('Executive', 'Executive'), ('Deluxe', 'Deluxe'), ) category = models.CharField(max_length=9, choices=CATEGORIES, default='Regular') CAPACITY = ( (1, '1'), (2, '2'), (3, '3'), (4, '4'), ) capacity = models.PositiveSmallIntegerField( choices=CAPACITY, default=2 ) advance = models.PositiveSmallIntegerField(default=10) manager = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE ) class TimeSlot(models.Model): class Meta: ordering = ['available_from'] room = models.ForeignKey(Room, on_delete=models.CASCADE) available_from = models.TimeField() available_till = models.TimeField() When I am printing time_slot_list, I am getting empty QuerySet but I want it to contain the list of timeslots. Can someone please tell me what I am doing wrong? -
django login url with param
a third party authentication requires api must be called in the index view, for example my domain is zzd.com, then they only provide api to zzd.com, which means we cannot have route specified for a signin view, which unable to put all login stuff into zzd.com/login/ however, index view is designed to shows some other important info primarily rather than login QR, which only contains a login button, to use js to display the QR when click. here's the issue, I have followed declared in settings.py: my index view serves all stuff in one template, including trending info, and login qr code if user is not auth-ed. javascript looks like this: const url = new window.URL(window.location.href); let mode = url.searchParams.get('mode'); if(mode === 'login'){ showLoginQrCodeScanner(); } which login qr img would only show if index/?mode=login specified, otherwise would display trending info instead. and my settings.py: LOGIN_REDIRECT_URL = 'index' LOGIN_URL = 'index' the issue is that, I have some of my views @login_required, but, an anonymous user, would get redirected to the index/?next=particular/url, without the mode=login part, which does not show the qr primarily. is there a way to declare login url with the param, for a much better user experience? -
How to associate a django url with a bootstrap modal popup
I have a django view which create an form within a modal popup. When clicking to lithat triger the modal, nothing happen. I seems it is because I am not in the page. Because when I was in another page, I see the popup firing. Is it possible to add url cooresponding to the view in the modal button here is my navbar.html <div> <ul> <li> <a class="dropdown-item" data-bs-toggle="modal" data-bs-target="#formModal" href="{% url 'create_campaign_naming_tool' %}">Modal</a> </li> </ul> </div> My form template: {% extends 'navbar.html' %} {% block content %} <div class="modal fade" id="formModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalCenterTitle" aria-hidden="true"> <div class="modal-dialog modal-dialog-centered" role="document"> <div class="modal-content"> <div class="modal-header"> </div> <div class="modal-body"> <form class="" action="#" method="post" enctype="multipart/form-data"> {% csrf_token %} {{form}} <!-- Modal footer --> <div class="modal-footer"> <button type="submit" class="btn btn-success" name="button">Create</button> <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button> </div> </form> </div> </div> </div> </div> {% endblock %} -
Integrating tailwindcss with django
am trying to integrate tailwindcss with django. django seems to have located my tailwindcss and even the default font for tailwindcss is implemented, but none of the tailwind classes seems to work in my project. What could be the reason why? I tried passing classes mx-auto, font-semibold into my div as seen in this image but both the classes failed to respond as seen in this image. And when i tried to add another css property (background-color:blue) in the tailwind output file, that property works. So the question is, how comes other css properties work but tailwind classes won work for me?