Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django : How to check a list of values is exists in a table or not in a single query in django?
user entered category = [1,2,3,............] for catId in categoryIds: if Category.objects.filter(id = catId).exist(): -------------- ----single opertions like adding value in to dict.----- else: -------------- I need to avoid unnecassary iteration by checking it in a single query. check the entered values is valid and then I can add to dict in a single step. how can I do it with django ORM ? -
Django Q objects vs python code better performance?
What would provide better performance using filtering conditions with Q in django ORM or simply fetching unfiltered objects and comparing in python. employee_qs = employee.objects.filter(state=States.ACTIVE, topic_assn__topic_id=instance.ss_topic_id).select_related('c_data').filter( Q(c_data__is_null=True) | Q(c_budget__gt=F('c_data__budget_spent') + offset_amt)) V/s employee_qs = employee.objects.filter(state=States.ACTIVE, topic_assn__topic_id=instance.ss_topic_id).select_related('c_data') for employee in employee_qs: if not employee.c_data or float(employee.budget)-employee.c_data.budget_spent > offset_amt: #do something... Which of these two choices would be better performance wise? -
Serializer class as property of Model class - is it bad practice?
I want to write a custom command that requires separate serializers for multiple Model classes. In order to make that iterable, I thought it might be a good idea to add a custom property to the Models involved. Following is a short example of what I envisioned, inside an app: # models.py from django.db import models class Foo(models.Model): # field properties, etc. command_serializer_class = FooCommandSerializer # serializers.py from rest_framework.serializers import ModelSerializer class FooCommandSerializer(ModelSerializer): class Meta: model = Foo # management/commands/foo_command.py from django.core.management.base import BaseCommand class FooCommand(BaseCommand): for model_class in [Foo, OtherModels]: qs = Foo.objects.all() # do things serializer = model_class.command_serializer_class(qs, many=True) print(f"Model has {len(serializer.data)} records.") At a first glance, it seems redundant to specify the Serializer to the Model, since it's a one-to-one association the other way around - as in, a Serializer must have one specific Model defined in the metaclass. However, I've found no way to list Serializers using a specific Model, so this seems to cleanest solution for me. Is it good practice, or can bite me in the long run? Is there any reason for me not to do it, or find another way to iterate through Models this way? -
Error: No file was submitted. Check the encoding type on the form
Please I’m having issue with register vendor, all was working fine before, so I just decided to retest everything have done, to my surprise the code thats working perfectly before is no more working. please help me out guys............................................................................................................................................................. views.py def registerRestaurant(request): # this restrict user from going to Vendor Registration Page after Logged in if request.user.is_authenticated: messages.warning(request, "You are already logged in!") return redirect('dashboard') if request.method == 'POST': form = UserForm(request.POST, request.FILES) v_form = vendorForm(request.POST, request.FILES or None) if form.is_valid() and v_form.is_valid(): password = form.cleaned_data['password'] # clean_data will return 'dict value' user = form.save(commit=False) user.set_password(password) user.role = User.VENDOR user.save() vendor = v_form.save(commit=False) vendor.user = user user_profile = UserProfile.objects.get(user=user) vendor.user_profile = user_profile vendor.save() mail_subject = 'Please Activate your Account' email_template = 'accounts/emails/account_verification_email.html' send_verification_email(request, user, mail_subject, email_template) #send_verification_email is function created in utils.py messages.success(request, "Your Account has been Registered Successfully, Please Wait for Approval") return redirect('registervendor') else: messages.error(request, 'An Error occurred during registration!') else: form = UserForm() v_form = vendorForm() context = { 'form': form, 'v_form': v_form, } return render(request, 'vendor/registervendor.html', context) model.py (vendor) class Vendor(models.Model): user = models.OneToOneField(User, related_name='user', on_delete=models.CASCADE) user_profile = models.OneToOneField(UserProfile, related_name='userprofile', on_delete=models.CASCADE) vendor_name = models.CharField(max_length=50) vendor_lincense = models.ImageField(upload_to='vendor/lincense') is_approved = models.BooleanField(default=False) created_at = models.DateTimeField(auto_now_add=True) modified_at = models.DateTimeField(auto_now_add=True) … -
Django: how to do a group by on a field that is an indexed varchar?
I have a model Product like this: class Product(models.Model): manufacturer = models.CharField(max_length=32, null=True, blank=True) product_model = models.CharField(max_length=32, null=True, blank=True) description = models.CharField(max_length=32, null=True, blank=True) The field manufacturer is not a primary key, but it's an index. I would like to do a query that group all the products by manufacturer. Something like: Product.objects.all().group_by(manufacturer). (This is for use in Django Rest Framework where I have to return an array of manufacturer and for each manufacturer, an array of all the Product's of the manufacturer). How would yo do? -
AttributeError: module 'django.contrib.gis.db.models' has no attribute 'JSONField'
I'm using a Postgis database for my Django Project which has a field of JSONField in its database. When I run it, I get this error AttributeError: module 'django.contrib.gis.db.models' has no attribute 'JSONField' How to solve this issue? -
unable to specify the fields in drf queryset using drf-yasg
class ABC(generics.ListCreateApiView): @swagger_auto_schema( operation_description="THIS API IS TO CREATE MESSAGES IN A LIST ", auto_schema=AcceptFormDataSchema, request_body=MessageGetSerializer ) def get_queryset(self): data =self.request.GET.get("code") ... @swagger_auto_schema( operation_description="THIS API IS TO CREATE MESSAGES IN A LIST ", request_body=openapi.Schema( type=openapi.TYPE_OBJECT, required=["data"], properties={ "code": openapi.Schema(type=openapi.TYPE_STRING), def post(self, request): brand_code = request.data.get("code") ..... #serializer.py class MessageSerializer(serializers.ModelSerializer): class Meta: model = Messages fields = ("message_id", "content", "description") My post method is working fine with the fields which I required using the same serializer but it's not working for the get_queryset method. Can anyone please suggest something on how I will get the fields using drf-yasg? -
Django Form doesn't update when using Jquery signature framework
I'm using Jquery's signature framework in my form page that I wrote with Django. When I use this, it does not update when I make changes in any field in the form. update.py def updateAmbulanceCaseForm(request,id): ambulanceCase = AmbulanceCase.objects.get(id=id) form = AmbulanceCaseForm(data=request.POST, instance=ambulanceCase) if form.is_valid(): form.save() messages.success(request,"Kayit Basarili...") print(form.data) context={'AmbulanceCase':AmbulanceCase.objects.all()} return render(request,"tables/ambulance_case.html", context) else: print("basarisiz") return render(request,"forms/update_forms/ambulance_case.html",{"AmbulanceCase": ambulanceCase}) update.html $(function() { if($('#sigtext')) { var sig = $('#get_sig').signature(); sig.signature('draw', $('#sigtext').val()); sig.signature('disable'); $('#get_sig').signature({disabled:true}); } else{ var sig = $('#get_sig').signature(); } }); <div class="mb-3 col"> <label for="doctor_username" class="form-label">DOKTOR/PARAMEDİK ADI SOYADI</label> <input type="text" class="form-control" id="doctor_username" name="doctor_username" value="{{AmbulanceCase.doctor_username}}"> <div class="container row mb-3 col" style="display: block;"> <label for="doctor_signature" class="form-label">İMZA</label> <div class="container border border-5" id="doctor_signature" > </div> <textarea name="doctor_signaturetext" id="doctor_signaturetext" cols="30" rows="10" style="display: none;">{{AmbulanceCase.doctor_signaturetext}}</textarea> </div> -
group the serialized data according to particular field value (Django rest framework)
models.py class InviteUser(models.Model): invite_id = models.AutoField(primary_key=True) invite_code = models.CharField(max_length=100, unique=True) invite_type = models.CharField(max_length=100) invited_user_role = models.CharField(max_length=100) invited_user = models.ForeignKey('users.User', on_delete=models.CASCADE, db_column='invited_user') number_of_invites = models.PositiveIntegerField(null=True, blank=True) invite_expiry_date = models.CharField(max_length=100, null=True, blank=True) remaining_invites = models.PositiveIntegerField(null=True, blank=True) phone_number = models.CharField(max_length=15, null=True, blank=True) veiws.py class GetAllInvitesCreatedByOneUser(generics.RetrieveAPIView): def get(self, request, *args, **kwargs): user_id = self.kwargs['user_id'] user_invite_instance = InviteUser.objects.filter(Q(invited_user=user_id) & (Q(invite_type='MEMBER') | Q(invite_type='SELLER'))) serializer = GetAllInvitesCreatedByOneUserSerializer(user_invite_instance, many=True) return Response({"message": "success", "invited_user": user_id, "data": serializer.data}, status=status.HTTP_200_OK) serializers.py class GetAllInvitesCreatedByOneUserSerializer(serializers.ModelSerializer): class Meta: model = InviteUser fields = ['invite_code', 'invite_type', 'phone_number'] Above code gives result: { "message": "success", "invited_user": 77, "data": [ { "invite_code": "M-ASWA-6721", "invite_type": "MEMBER", "phone_number": "9387907555" }, { "invite_code": "M-ASWA-3289", "invite_type": "MEMBER", "phone_number": "9999907772" }, { "invite_code": "S-ASWA-6411", "invite_type": "SELLER", "phone_number": "8099907772" } ] } I want this to be grouped by invite_type field: "message": "success", "invited_user": 77, "data": [ { "MEMBER": [ { "invite_code": "M-ASWA-6721", "invite_type": "MEMBER", "phone_number": "9387907997" }, { "invite_code": "M-ASWA-3289", "invite_type": "MEMBER", "phone_number": "9999907772" } ], "SELLER": [ { "invite_code": "S-ASWA-6411", "invite_type": "SELLER", "phone_number": "8099907772" } ] } ] } -
Make django app aware of local network IP camera
I have a django app running in a server, it can access the users usb and integrated cameras and show the live feed in the html, but now I need to access the users local IP cameras (connected directly to the Ethernet port in the PC), if possible I would like to achieve this without installing 3rd party software but any solution is valid, is this possible at all? I can access the cameras locally using python but I can't find a way to make the Django app aware of the users local IP cameras. The cameras are type GigE and I am using pylon to access them locally -
i want send emails by filtering datas from django table to multiple reciepent
i am just creating a recruitment app in django.So i want send scheduled mails to companies Hr after they adding vacancies.The datas are the student skill,email,name, from student table. Total 3 models student , vacancy, company. -
Django interaction between two projects deployed in azure in two different ports
In django I am having two projects project1 will take care of user registration, login, authentication(token based authentication) and project 2 have one application running in it. Now my problem is for project2 I am unable to provid security if someone know the url anyone can use for free. In project1 by using some code i am sending request to project2 and returning response Now i need an approach to protect project2 from unauthorised usage(for security reasons) Note: I can't club both as a single project(for some reason) -
Pandas read_csv function to handle both utf-8 and utf-16 issue
User can upload both UTF-8 and UTF-16 CSV file which is the attendance file of Microsoft teams that they download from there. To handle the case I have written the following code but there is some strange issue that I am not able to fix. excel_file = request.FILES['excel-file'] try: print('try case') df = pd.read_csv(excel_file) csv_type = 'a' print(df) except UnicodeDecodeError: print('except case') from io import BytesIO df = pd.read_csv(BytesIO(excel_file.read().decode('UTF-16').encode('UTF-8')), sep='\\') csv_type = 'b' print(df) except Exception as e: print("Incorrect CSV file format", e) Here first 'try case' handle the UTF-8 and 'except case' handle the UTF-16 CSV file. Both case work fine if I run them separately, But when I put them in try except block then the code fails. Here in the above code UTF-8 case works but UTF-16 gives No columns to parse from file error. Now if I move the except code to try then UTF-16 will work but it will also run for UTF-8 giving wrong data. So how can I handle this case haven't found any way to get file encoding also. -
Docker Django services not communicating
I am trying to get my listener service to POST at an API in the app service. The app service is running at 0.0.0.0:8000 and the listener service is trying to post at this address but the data isn't getting added to the db. I am not sure if I have configured this correctly, help would be much appreciated. docker-compose.yml services: db: image: postgres:13.4 env_file: - ./docker/env.db ports: - 5432:5432 volumes: - db_data:/var/lib/postgresql/data app: build: context: . dockerfile: ./docker/Dockerfile env_file: - ./docker/env.db - ./.env volumes: - .:/opt/code ports: - 8000:8000 - 3000:3000 depends_on: - db command: bash ./scripts/runserver.sh listener: image: scooprank_app env_file: - ./.env container_name: listener command: npm run listen depends_on: - app restart: always -
Django with Aws Application load balancer
What is the deployment flow to achieve load balancing using multiple Ec-2 instances? do I have to configure my project with both ec2 manually first and then use them with the App Load balancer? -
Key Error while trying to register user Django
Imm getting a key error "password" on serializer.py while validating the data. Imm using Django's built in User model and Token Authentication to register a user. here's how my serializer.py looks like. from django.contrib.auth.models import User from rest_framework import serializers class RegistrationSerializer(serializers.Serializer): password2 = serializers.CharField(style={"input_type" : "password"}, write_only=True) class Meta: model = User fields = ["username", "email", "password", "password2"] extra_kwarg = { "password": { "write_only": True, } } def validate(self, data): if data["password"] != data["password2"]: return serializers.ValidationError("Your password must be same!") if data.objects.filter(email=data["email"]).exists(): return serializers.ValidationError("This Email is already registered!") return data views.py from rest_framework.response import Response from user_app.api.serializer import RegistrationSerializer from rest_framework.decorators import api_view @api_view(["POST",]) def register_user(request): if request.method == "POST": serializer = RegistrationSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) else: return serializer.error_messages()``` Errors serializer.py", line 22, in validate if data["password"] != data["password2"]: KeyError: 'password' -
Can't import models in Python shell
I'm doing the Django official tutorial (documentation). I've created two database models (Question, Choice). I'm trying to import them by first entering the python shell by using python manage.py shell Then I run from polls.models import Question,Choice and nothing happens, it just enters an empty line. In the documentation, it's showed that I'm supposed to see some information regarding the database. I've done the migration and also put the app config in settings.py -
why it is not displaying slug field on the address bar?
I am new to Django. I encountered an error while practicing on the slug field adding to the model. it is not working after I run the program. The browser is not displaying any error. I have written the code below please have a look and anybody help me out? feel free to ask me if you have any questions. Thank you for your help. models.py from django.db import models from django.db.models.signals import pre_save from django.dispatch import receiver from django.utils.text import slugify import string,random from temp1.util import unique_slug_generator STATUS_CHOICES = ( ('draft', 'Draft'), ('published', 'Published'), ) class Post(models.Model): title = models.CharField(max_length = 250) slug = models.SlugField(max_length = 250, null = True, blank = True) text = models.TextField() published_at = models.DateTimeField(auto_now_add = True) updated = models.DateTimeField(auto_now = True) status = models.CharField(max_length = 10, choices = STATUS_CHOICES, default ='draft') class Meta: ordering = ('-published_at', ) def __str__(self): return self.title @receiver(pre_save, sender=Post) def pre_save_receiver(sender, instance, *args, **kwargs): if not instance.slug: instance.slug = unique_slug_generator(instance) urls.py from django.urls import path from .views import detail urlpatterns = [ path("posts/",detail,name="home") ] util.py import string, random from django.db.models.signals import pre_save from django.dispatch import receiver from django.utils.text import slugify def random_string_generator(size = 10, chars = string.ascii_lowercase + string.digits): return … -
home.html isn't displaying tags
The tags aren't showing in the home page. but it appears in post_detail.html. Its not working as I want it to work. Can anyone fill me up with mistakes here and solutions? blog/views.py: def home(request, tag_slug=None): posts = Post.objects.all() # tag post tag = None if tag_slug: tag = get_object_or_404(Tag, slug=tag_slug) posts = posts.filter(tags__in=[tag]) context={ 'posts': posts, #introduces the content added in Post Class 'tag':tag, } return render(request, 'blog/home.html', context) class PostListView(ListView): model=Post template_name = 'blog/home.html' # <app>/<model>_<viewtype>.html context_object_name= 'posts' ordering = ['-date_posted'] class PostDetailView(DetailView): model=Post blog/urls.py: urlpatterns = [ path('', PostListView.as_view(), name='blog-home'), path('post/<int:pk>/', PostDetailView.as_view(), name='post-detail'), path('tag/<slug:tag_slug>/',views.home, name='post_tag'), templates/blog/base.html <div class="col-md-4"> <div class="content-section"> <h3>Sidebar</h3> <p class='text-muted'>Informations <ul class="list-group"> <li class="list-group-item list-group-item-light" style="text-align:center"> <div class="dropdown"> <button class="btn btn-secondary dropdown-toggle" type="button" id="dropdownMenuButton" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> Tags </button> <div class="dropdown-menu" aria-labelledby="dropdownMenuButton"> {% for tag in post.tags.all %} <a class="dropdown-item" href="{% url 'post_tag' tag.slug %}">{{tag.name}}</a> {% endfor %} </div> </div> </li> </ul> -
Django Class Based View (FormView)
class ReviewView(FormView): form_class = ReviewForm template_name = "review/review.html" success_url = "/thank-you" def form_valid(self, form): form.save() return super().form_valid(form) this is the error how can I fix it AttributeError at / 'ReviewForm' object has no attribute 'save' -
Dynamic Dropdown values django
I want to create a dropdown Course of Trainee where only options of values in CourseName of Course model would be shown. Currently I have tried some soulutions after browsing. But its not working. My course dropdown disappeared after editing in forms.py. If i remove this line Course = forms.ChoiceField(widget=forms.Select(attrs={'class':'col-sm-4'}), choices=course_obj.get_course_name(), label='Course :') Then the dropdown would show but with no options model.py class Course(models.Model): CourseID = models.AutoField(primary_key=True) CourseName = models.CharField(max_length=20) class Meta(): db_table = "Courses" def get_course_name(self): return self.CourseName class Trainee(models.Model): Name = models.CharField(max_length=50) Course = models.CharField(max_length=40) class Meta(): db_table = "Trainee" forms.py class TraineeForm(forms.ModelForm): course_obj = Course() Name = forms.CharField(widget=forms.TextInput(attrs={'class':'col-sm-4'}), label='Name :') Course = forms.ChoiceField(widget=forms.Select(attrs={'class':'col-sm-4'}), choices=course_obj.get_course_name(), label='Course :') ........................ edit.html <form method="post" class="form-group" type="multipart/form-data"> {%csrf_token%} {% for Name in form.Name %} <div class="form-group row"> <label class="col-sm-3 col-form-label">{{ form.Name.label }}</label> {{ Name }} </div> {% endfor %} {% for Course in form.Course %} <div class="form-group row"> <label class="col-sm-3 col-form-label">{{ form.Course.label }}</label> {{ form.Course }} </div> {% endfor %} The Page appears like this -
django summernote how to limit the number of images or total image size
I'm touching a Django summernote. But there's a problem. I can limit the size of one image, but how do I set the total number of images per post or the total image size? plaese help me -
How to avoid 'callback' error page in django-allauth( GoogleAuth)?
I am developing some django app and implemented authentication via Google. Everything works fine, but if user logins via Google, goes back to Google-login page with browser`s 'previous page' button, hi might login again and see this error page: Page I don`t want users to see that. How can I avoid this 'error' page? -
How can I serve staticfiles in Django in Railway app when Debug is False
When I set DEBUG to False on Railway's variables my images from uploads are not loading. How can I fix that? my settings.py MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', ... ] STATIC_ROOT = BASE_DIR / 'staticfiles' STATIC_URL = 'static/' STATICFILES_DIRS = [ BASE_DIR / 'static' ] MEDIA_ROOT = BASE_DIR / "uploads" MEDIA_URL = "/uploads/" my urls.py has + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) \ + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) and I used python manage.py collectstatic -
The terminal gives me as error a path that I don't have in my code with Django
I'm working on Django, developing a site This gives me an error: Not Found: /plans/investment_per_plan_chart Not Found: /plans/active_running_plans I have searched with VSC but I can't find anything in my code that looks like this error. Please help me I'm lost