Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
UNIQUE constraint failed: home_profile.user_id - Django
I am just trying to mix my Profile model with my User one. I was following this Django series: https://www.youtube.com/watch?v=KXunlJgeRcU&list=PLCC34OHNcOtoQCR6K4RgBWNi3-7yGgg7b I accidentally deleted one of my users, so I tried recreating them again and got this error: UNIQUE constraint failed: home_profile.user_id I tried solving the issue with this answer: https://stackoverflow.com/a/60282442/19641902 ... but it gave me another error: 'User' object has no attribute 'profile' Also when I create the users in the database manually, it automatically creates three-four profiles in the User section of my database. The following is the code after following the above StackOverflow answer models.py from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save # Create A User Profile Model class Profile(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="user") follows = models.ManyToManyField("self", related_name="followed_by", symmetrical=False, blank=True) def __str__(self): return self.user.username # Create Profile When New User Signs Up #@receiver(post_save, sender=User) def create_profile(sender, instance, created, **kwargs): if created: user_profile = Profile(user=instance) user_profile.save() # Have the user follow themselves user_profile.follows.set([instance.profile.id]) user_profile.save() post_save.connect(create_profile, sender=User) admin.py from django.contrib import admin from django.contrib.auth.models import User from .models import Profile # Mix Profile info into User info class ProfileInline(admin.StackedInline): model = Profile # Extend User Model class UserAdmin(admin.ModelAdmin): model = User # Just display … -
Reset Password by retrieving Email from Forget Password View django
in the following code when "forget password" runs it takes "email" input from the user and generates token, using that email and token the user can change their password but what i want is: the user only needs to enter "new_password" and "reconfirm_password" and not the email to change the password, the email should be get from "forget password view" the following code gives this error while executing: cannot access local variable 'email' where it is not associated with a value views.py class ChangePasswordView(APIView): def get(self, request, token, email): context = {} try: profile_obj = UserAccount.objects.filter( forget_password_token=token).first() if profile_obj: context['email'] = email else: return JsonResponse({'message': 'Invalid token.'}) except Exception as e: print(e) return JsonResponse({'message': 'An error occurred.'}) return JsonResponse(context) def post(self, request, **kwargs): try: context = {} profile_obj = UserAccount.objects.filter( email=email).first() if profile_obj: context['email'] = email new_password = request.data.get('new_password') confirm_password = request.data.get('reconfirm_password') email = request.data.get('email') print(new_password) if email is None: return JsonResponse({'message': 'No user email found.'}) if new_password != confirm_password: return JsonResponse({'message': 'Both passwords should be equal.'}) user_obj = UserAccount.objects.get(email=email) user_obj.set_password(new_password) user_obj.save() return JsonResponse({'message': 'Password changed successfully.'}) except Exception as e: print(e) return JsonResponse({'message': 'An error occurred.'}) @method_decorator(csrf_exempt, name='dispatch') class ForgetPasswordView(View): def post(self, request): try: data = json.loads(request.body) email = … -
Calling QuerySet.only() after union() is not supported
I'm a newbie to django here. I'm getting the following error on my django backend: Calling QuerySet.only() after union() is not supported The error producing code is the following : post_notification_target_users = Post.get_post_comment_notification_target_users(post=post, post_commenter=post_commenter).only( 'id', 'username', 'notifications_settings__post_comment_notifications') upon further inspection, the following code is related to it : def comment_post_with_id(self, post_id, text): Post = get_post_model() post = Post.objects.filter(pk=post_id).get() return self.comment_post(post=post, text=text) I searched where .union() is used with regards to the above and this is what I found : def get_participants(self): User = get_user_model() # Add post creator post_creator = User.objects.filter(pk=self.creator_id) # Add post commentators post_commenters = User.objects.filter(posts_comments__post_id=self.pk, is_deleted=False) # If community post, add community members if self.community: community_members = User.objects.filter(communities_memberships__community_id=self.community_id, is_deleted=False) result = post_creator.union(post_commenters, community_members) else: result = post_creator.union(post_commenters) return result and def get_post_comment_notification_target_users(cls, post, post_commenter): """ Returns the users that should be notified of a post comment. This includes the post creator and other post commenters :return: """ # Add other post commenters, exclude replies to comments, the post commenter other_commenters = User.objects.filter( Q(posts_comments__post_id=post.pk, posts_comments__parent_comment_id=None, ) & ~Q( id=post_commenter.pk)) post_creator = User.objects.filter(pk=post.creator_id) return other_commenters.union(post_creator) I read other stack posts of what is allowed and what isn't after using union() but i'm unable to arrive at the right way … -
Unable to create user -Django.conrib.auth
I am Trying to create a Login system using Django inbuilt django.contrib.auth.models.user i am not getting any error in the code all files are check, but when i am trying the save the user in the database i can't see the user which i created in the django admin panel i am getting all the details through html form and exxtracting that values in views.py, but even after migrations signup.html <form method="POST" action="home/"> {% csrf_token %} <input type="text" name="username" placeholder="Username" required/> <input type="email" name="email" placeholder="Email" required/> <input type="password" name="password" placeholder="Password" required/> <input type="password" name="confirm_password" placeholder="Confirm Password" required/> <input type="submit" name="submit" value="Sign Up"/> </form> views.py from django.shortcuts import render from django.http import HttpResponse from django.contrib.auth.models import User # Create your views here. def signup(request): if request.method=='POST': username=request.POST.get('username') email=request.POST.get('email') password=request.POST.get('password') confirm_password=request.POST.get('confirm_password') the_user=User.objects.create_user(username=username,email=email,password=password) the_user.save() return render(request,'signup.html') def home(request): return HttpResponse('Login Successfull') This Is Django Admin Panel -
can't access to tenant schemas in Django-tenant
I'm having problems accessing tenant schemas. So far I have been able to create schemas and tenants in the database. I'm creating tenants using tenant.localhost (no port) as domain, for localhost testing. I have successfully created tenant superusers, but so far I can only get the public schema to work. i.e. login, admin, and all the views of the app. But when I try tenant.localhost:8000 where I run my local server, I can't get it to work. Hopefully someone can help me out here. Thanks in advance. # Please note that only the relevant sections of the settings.py file are included here. SHARED_APPS = ( 'django_tenants', # mandatory 'customers', # you must list the app where your tenant model resides in # Other shared apps ) TENANT_APPS = ( # your tenant-specific apps 'django.contrib.auth', 'django.contrib.sessions', 'django.contrib.contenttypes', # Other tenant-specific apps ) INSTALLED_APPS = list(SHARED_APPS) + [app for app in TENANT_APPS if app not in SHARED_APPS] TENANT_MODEL = "customers.Client" # app.Model TENANT_DOMAIN_MODEL = "customers.Domain" # app.Model DATABASES = { 'default': { 'ENGINE': 'django_tenants.postgresql_backend', 'NAME': config('NAME'), 'USER': config('USER'), 'PASSWORD': config('PASSWORD'), 'HOST': config('HOST'), 'PORT': '5432', } } DATABASE_ROUTERS = ( 'django_tenants.routers.TenantSyncRouter', ) AUTH_USER_MODEL = "accounts.User" MIDDLEWARE = [ 'django_tenants.middleware.main.TenantMainMiddleware', # Other middleware ] … -
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, …