Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
regarding slashes using in urls pattern
i am learning django for some days and i feel overwhelm by slashes using in url pattern like path("login" , login , name='login') sometimes we use slash in the starting , sometime in the end and sometime we use at both side like this (/login, login/, /login/).it is really very confusing question = 1-what are these slashes and what does it do in my pattern 2 - when sould i use slash - in starting , in end or at both side i don't know exactly when to use these slashes in url pattern so please guide me -
Postgresql query error, ERROR: there is no unique constraint matching given keys for referenced table "app_user_user"
I am using Django version 4.2 and I am facing this error while executing the migration file. I made no changes to Django's standard tables "app_user_user_groups" and "app_user_user_user_permissions". In this migration, I changed the primary key(id) field in the "app_user_user" table from int to bigint I used the following command to get the sql output of the related migrate file; python manage.py sqlmigrate app_user 0002_auto_20230607_1447 output; BEGIN; -- -- Alter field extra on user -- -- (no-op) -- -- Alter field id on user -- ALTER TABLE "app_user_user" ALTER COLUMN "id" TYPE bigint USING "id"::bigint; ALTER SEQUENCE IF EXISTS "app_user_user_id_seq" AS bigint; ALTER TABLE "app_user_user_groups" ALTER COLUMN "user_id" TYPE bigint USING "user_id"::bigint; ALTER TABLE "app_user_user_user_permissions" ALTER COLUMN "user_id" TYPE bigint USING "user_id"::bigint; ALTER TABLE "app_user_user_groups" ADD CONSTRAINT "app_user_user_groups_user_id_d117580e_fk" FOREIGN KEY ("user_id") REFERENCES "app_user_user" ("id") DEFERRABLE INITIALLY DEFERRED; ALTER TABLE "app_user_user_user_permissions" ADD CONSTRAINT "app_user_user_user_permissions_user_id_ec2823c7_fk" FOREIGN KEY ("user_id") REFERENCES "app_user_user" ("id") DEFERRABLE INITIALLY DEFERRED; COMMIT; my user model class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField( _('email address'), unique=True ) is_staff = models.BooleanField( default=False ) is_active = models.BooleanField( default=True ) identity = models.CharField( max_length=20, unique=True, null=True, blank=True, verbose_name=_('Identity') ) name = models.CharField( max_length=50, null=True, blank=True, verbose_name=_('Name') ) last_name = models.CharField( max_length=50, null=True, blank=True, verbose_name=_('Last … -
Django Image is not saving
I am working on a website, where you can upload a project. Each project contains a name, description, image and a deadline, that you can set. When i try to upload a project by pressing the "Save Project" button, i get redirected to my homepage, like i wanted to, but the image does not get saved, everything else does. I dont get a error message. Picture of trying to create a project: enter image description here Picture of the homepage after pressing "Save Project": enter image description here In models i defined two models, Project and Image. "Project" handels the project name, description, creation date and the deadline. "Image" contains an Imagefield and has a Foreignkey relationship with Project. Forms has a class called Projectform using a Modelform. I made it associated with the model Project. After that i made an inline formset factory using inlineformset_factory for the Project and Image models, so it can handle many images for one project. In view there are two functions. One of them is homepage which retrieves all projects from the database, passes them to project.html. Which then shows everything, such as name, image... The second function "create_project" handles both GET and POST … -
i want to run django project in vs code after clone it from githup but this error was appear,how can i solve this error? [closed]
I clone the django project from the githup but if i run it in vs code this error was appear (C:\Users\User\AppData\Local\Programs\Python\Python310\python.exe: can't open file 'D:\\adrois\\Django-Email-Sender\\manage.py': [Errno 2] No such file or directory) how can i solve it please my python file is python38 python 39 python 310 -
Showing user specific saved posts
So I'm somewhat of a beginner in Django. I am working with DRF and trying to create a saved posts page while implementing a filter to ensure that a suer only sees the posts he saved, but I tried the normal filter way and it's returning an empty list even though it is showing that there are saved posts in the saved posts table in the admin dashboard here is the code for reference: this is the serializer: class SavedPostSerializer(serializers.ModelSerializer): class Meta: model = SavedPost fields = ('id','post', 'profile', 'created_at', 'updated_at') and this is the Views: class SavedPostListCreateView(generics.ListCreateAPIView): queryset = SavedPost.objects.all() serializer_class = SavedPostSerializer authentication_classes = [TokenAuthentication] permission_classes = [IsAuthenticated] ordering_fields=['created_at'] def get_queryset(self): # Filter queryset to include only saved posts of the authenticated user return SavedPost.objects.filter(profile=self.request.user.profile) I looked everywhere before asking here but didn't really find a solution I even went to chatGPT as a last resort and still the same answer -
Rendering and using self-referencing model objects in nested format without duplicates in Django template
Hope you are doing well... I have a little misunderstanding in using self-referencing model objects in html template. models.py class MyNumber(models.Model): has_bro = models.ForeignKey('self', on_delete=models.CASCADE, null=True, blank=True) numb = models.CharField(max_length=10) def __str__(self) -> str: return self.numb views.py def index(request): context = { 'numbers': MyNumber.objects.all() } return render(request, 'test_folder/test_file.html', context) Let's say I have objects like 1 which has referencing objects too like 1.1 and 1.2. To make it complex let's add also more objects like 1.1.1 and 1.1.2 which are referencing to 1.1. The question is how to get all objects in nested format using <ul></ul> HTML tag without duplicates, like: * 1 * 1.1 * 1.1.1 * 1.1.2 * 1.2 So far, I am getting this result (below) with my little knowledge: * 1 * 1.1 * 1.2 * 1.1 * 1.1.1 * 1.1.2 * 1.2 Help is appreciated! -
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...