Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django model with multiple foreign keys
I want to create a list of products that are categorized by area, need, and product category. I created 3 separate models that reply on each other so users will easily add categories and select from the dropdown list area and need. For now, I have 3 areas and under each area I have needs. What I want is to render a list of items from Area model, under each item from Area model all items from Need model and under each item from Need model all items from Product model (only titles). ProductCategory model is not used here but I need it somewhere else and it is a connector between products and areas/needs. It is much easier to define categories and just select them from the dropdown list when adding a new product. I need to create a loop that will show me something like above. I know it will not work but I wanted to show the logic. My question is what is the best approach to render something like this? How can I get the title from Area model and title from Need model in my views.py file and show product titles under these objects? What is … -
Getting Error in Django Application on Azure App Service
I am getting since yesterday on appliction from yesterday it's working fine early some upgradtion on cloud breaks the application This is the error Error : module 'typing' has no attribute '_ClassVar' My python env is 3.7 and Django version 2.1.3 -
Problem with Jquery in django project template
am facing a problem in this Django project where I am working to get a dynamic dependent drop-down.This part of the script is not sending any Ajax request. As a beginner, I am trying to do random projects.I didn't know more about Ajax and Javascript. Is there any problem in this code? enter image description here -
VSCode not autocompleting all Django modules
It looks like autocompleting is not working for all the functions for some Django modules? For example, I am importing from django.contrib.auth.models import User but when trying to create a new user: user = User.objects.create_user(etc) is not showing the create_user function. Any thoughts please? FYI: I am running VSCode on Ubuntu and django is installed in a venv. Interpreter is set to .../venv/bin/python3.10 -
How to properly use asyncio semaphore in djangos views? and where i can trace if it works?
I have to limit the number of calls to this run_annotation function to a maximum of 3 because the server does not support it, the below code works but i don't know how can i check if i am doing it in the right way LIMIT = 2 async def run_annotation(self, id): sem = asyncio.Semaphore(LIMIT) do_something() -
Django's UserCreationForm's Errors isn't working?
few months ago i made a website where it worked but similar code this time isn't working! it returns : **ValueError at /registration/ The User could not be created because the data didn't validate.** this is my form.py in bottom: class CreateUserForm(UserCreationForm): class Meta: model = User fields = ["username", "email", "password1", "password2"] my views: from .form import CreateUserForm def registrationPage(request): form = CreateUserForm() if request.method == "POST": form = CreateUserForm(request.POST) if form.is_valid: form.save() return redirect("login") else: form = CreateUserForm() context = {"form": form} return render(request, "store/registration.html", context) in HTML previously i used : {{form.errors}} & it used to show me work on the page but not anymore -
AttributeError: 'Request' object has no attribute 'query_param'
Views.py - @api_view(['GET']) def view_items(request): if request.query_params: items = Item.objects.filter(**request.query_param.dict()) #error line else: items=Item.objects.all() serializer=ItemSerializer(items,many=True) if items: return Response(serializer.data) else: return Response(status=status.HTTP_404_NOT_FOUND) -
Django, using GraphQL, Problem with 3rd party auth
So I'm working on a Django app where I'm using GraphQL instead of REST. And I have got auth to work using Django-GrapQL-auth, but it is using the local database (SQLite). What I want to do is have a 3rd party services like Firebase, AWS cognito, auth0 or similar to store passwords, since I don't want to store that locally. SO in the end I want to be able to do authentication by a 3rd party. How do I do this in Django? Any library that can help me? Or recommendation? Thanks. -
File Sharing in Django Application between admin and other user
I have a user_type named a staff_user and Admin here the admin in supposed to share the file with staff_user.On the file_list page of admin we are supposed to have an option called share_with_staff_user when clicked it will display the list of staff_users when selected and shared the file should be displayed on the page of staff_user file page. how can i acheive this. models.py class StaffUserDocument(BaseModel): staffuser = models.ForeignKey(StaffUser, related_name='documents', on_delete=models.CASCADE) uploaded_by = models.ForeignKey('User', related_name='+', null=True, on_delete=models.SET_NULL) name = models.CharField(max_length=255) file = models.FileField(upload_to='protected/') class AdminDocument(BaseModel): uploaded_by = models.ForeignKey('User',related_name='+',null=True, on_delete=models.SET_NULL) name = models.CharField(max_length=255, unique=True) slug = models.SlugField(max_length=255, unique=True) file = models.FileField() views.py class AdminDocumentListView(LoginRequiredMixin, CustomPermissionMixin, TemplateView): template_name = 'admin_document_list.html' permission_classes = [IsStaff] def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['urlParams'] = self.request.GET context['instanceData'] = {} return context @login_required def staff_user_profile_documents(request): staffuser = request.user.person.staffuser data = {'neutral': staffuser, 'documents': staffuser.documents.all()} return render(request, template, data) -
Celery Limit the Number of Tasks Running per User
I have a task in Celery that looks like this: @app.task(name='task_one') def task_one(user_id, *args, **kwargs): # Long running task This task is created in views every time a user submits a form, the task requires a lot of resources and takes around 10 minutes on average to complete. (views.py) ... if request.method == 'POST': task_one.delay(user.id) ... I want to limit the number of task_one tasks created per user to one (either active or reserved) What I'm doing so far, is checking if there is a task active or reserved for that user before creating the task: def user_created_task(active_tasks, reserved_tasks, user_id): for task in list(active_tasks.values())[0] + list(reserved_tasks.values())[0]: if task['name'] == 'task_one' and task['args'][0] == user_id: # Check if there is a `task_one` task created for the user return True return False def user_tasks_already_running_or_reserved(user_id): inspect = app.control.inspect() active_tasks = inspect.active() reserved_tasks = inspect.reserved() if active_tasks is None and reserved_tasks is None: # Celery workers are disconnected return False return user_created_task(active_tasks, reserved_tasks, user_id) (views.py) ... if request.method == 'POST': if not user_tasks_already_running_or_reserved(user.id): task_one.delay(user.id) ... I was wondering if there is a more efficient way of doing this, instead of inspecting all the workers on every user request, maybe there's a way of adding … -
Django model with multi foreign key takes too long to load with forms.ModelChoiceField
My first question after years of searching in stackoverflow ! I have a django project for student marks. Models: class Registration(CMTracking): student = models.ForeignKey(Student, on_delete=models.CASCADE) academic_year = models.ForeignKey(AcademicYear, on_delete=models.CASCADE) school = models.ForeignKey(School, on_delete=models.CASCADE) grade = models.CharField(max_length=5, choices=Grade.choices) school_class = models.ForeignKey(SchoolGradeClass, on_delete=models.CASCADE, blank=True, null=True) last_year_result = models.PositiveSmallIntegerField(choices=RESULT.choices, blank=True, null=True) last_grade = models.CharField(max_length=5, choices=Grade.choices, null=True) date_of_join = models.DateField(null=True, blank=True) type_of_registration = models.PositiveSmallIntegerField(choices=TypeOfRegistration.choices, default=0, null=True) type_of_attendance = models.PositiveSmallIntegerField(choices=TypeOfAttendance.choices, null=True) transfer_from = models.PositiveSmallIntegerField(choices=TransferFrom.choices, blank=True, default=1) status = models.PositiveSmallIntegerField(choices=RequestStatus.choices, default=0) class Exam(CMTracking): fa_name = models.CharField(max_length=70, null=False) en_name = models.CharField(max_length=70, null=False) ar_name = models.CharField(max_length=70, null=False) total_mark = models.DecimalField(max_digits=5, decimal_places=2, default=0) exam_type = models.PositiveSmallIntegerField(choices=ExamType.choices) academic_year = models.ForeignKey(AcademicYear, on_delete=models.CASCADE) class ExamSubject(CMTracking): exam = models.ForeignKey(to=Exam, on_delete=models.CASCADE) subject = models.ForeignKey(to=SubjectMaster, on_delete=models.CASCADE) teacher = models.ForeignKey(Staff, related_name='ExamSubjectList', on_delete=models.CASCADE) # Namavar school_class = models.ForeignKey(SchoolGradeClass, on_delete=models.CASCADE, blank=True, null=True) min = models.PositiveSmallIntegerField(null=True) max = models.PositiveSmallIntegerField(null=True) class MarkDescriptive(CMTracking): subject = models.ForeignKey(ExamSubject, on_delete=models.CASCADE) student = models.ForeignKey(Registration, related_name='mark_list_descriptive', on_delete=models.CASCADE) goal = models.ForeignKey(to=SubjectGoalsMaster, on_delete=models.CASCADE) point = models.FloatField(null=True, blank=True) t2point = models.FloatField(null=True, blank=True) form: class MarkDescriptiveModelForm2(forms.ModelForm): student = forms.ModelChoiceField(queryset=Registration.objects.all().select_related('student__person').filter(school_id=106), required=False) # student = forms.IntegerField() # only shows the id goal = forms.ModelChoiceField(queryset=SubjectGoalsMaster.objects.all(), required=False) point = forms.ChoiceField(choices=DescriptivePoint5.choices) t2point = forms.ChoiceField(choices=DescriptivePoint5.choices) class Meta: model = MarkDescriptive fields = ['id', 'student', 'point', 't2point'] View : @login_required() @require_http_methods(['POST', 'GET', 'PUT']) def mark_descriptive_update(request, exam_subject_id=None, goal_id=None): … -
redirect on the same post_id after edit post
I have created a forum website in Django where users can post Questions/Answers and edit them. After editing the reply I want to redirect the user to the currently edited post page. like if user edit reply which has been posted on the question with id 4 (which url is (http://127.0.0.1:8000/discussion/4)) then after edited it should redirect to the same url Post view.py def forum(request): user = request.user profile = Profile.objects.all() if request.method=="POST": form=PostContent(request.POST) if form.is_valid(): user = request.user image = request.user.profile.image content = request.POST.get('post_content','') post = Post(user1=user, post_content=content, image=image) post.save() messages.success(request, f'Your Question has been posted successfully!!') return redirect('/forum') else: form=PostContent() posts = Post.objects.filter().order_by('-timestamp') form= PostContent() context={ 'posts':posts, 'form':form } return render(request, "forum.html",context) reply view.py def discussion(request, myid): post = Post.objects.filter(id=myid).first() replies = Replie.objects.filter(post=post) if request.method=="POST": form=ReplyContent(request.POST) if form.is_valid(): user = request.user image = request.user.profile.image desc = request.POST.get('reply_content','') post_id =request.POST.get('post_id','') reply = Replie(user = user, reply_content = desc, post=post, image=image) reply.save() messages.success(request, f'Your Reply has been posted successfully!!') return redirect(f'/discussion/{post_id}') else: form=ReplyContent() form= ReplyContent() return render(request, "discussion.html", {'post':post, 'replies':replies,'form':form}) Edit reply view def edit_reply(request, pk): reply = Replie.objects.get(id=pk) if request.method == 'POST': form = UpdateReplyForm(request.POST, instance=reply) if form.is_valid(): form.save() messages.success(request,"Reply updated successfully!") return redirect('/forum') else: form = UpdateReplyForm(instance=reply) context … -
An error while changing text with javascript
I'm using google recaptcha with my django project. But it is not English. So I want to change its writing with javascript. html {% extends 'base.html' %} {% block content %} <div class="form-body"> <div class="row"> <div class="form-holder"> <div class="form-content"> <div class="form-items"> <h1>Registration</h1> <br><br> <form class="requires-validation" method="POST" novalidate> {% csrf_token %} {{form.as_p}} <div class="form-button"> <button id="submit" type="submit" class="btn btn-primary">Register</button> </div> </form> </div> </div> </div> </div> </div> <script type="text/javascript"> document.querySelector('recaptcha-anchor-label').innerHTML = "I'm not a robot"; </script> {% endblock %} After I did that it won't apply the html in browser. Below the error message: Cannot set properties of null (setting 'innerHTML') -
I have to create a website to decode Invoice QR codes
I have to create a website to decode Invoice QR codes. Is there any module using Python, Java, and JavaScript? I searched more for Python and I also have created a website using the python module which is pyzbar to decode QR codes and then I used jwt module which has a decode function to decode the QR code into a readable format such as '{'data': '{"SellerGstin": "27AAACB5724H1ZU", "BuyerGstin": "27AAHCS2420A1ZX", "DocNo": "MK20040946"}'. -
Is it possible to store images as BLOB in MySQL database using Django models?
I want to store images in MySQL Database (not the path, the actual image) using Django as the backend and React js as the frontend. Is it possible to do that? Please help me in resolving this issue. Thanks in advance. -
How does django-simple-captcha really work?
I have been trying to implement django-simple-captcha to my Django project for a while and I just can't get it in. Many of the questions related to it are many years old, so I wonder if it is still functional. I tried following the docs but that was no better than some of the questions here. A lot of people remark on how easy it is to install but I've tried so many times and ways that I am confused. This question here is just one of many like I described earlier. Using django-simple-captcha with django-lazysignup? Can someone please tell me what I am doing wrong? I suspect that I am not validating the captcha properly in my views.py. I have added 'captcha' to my installed apps in my settings.py. settings.py INSTALLED_APPS = [ 'blog.apps.BlogConfig', 'users.apps.UsersConfig', 'crispy_forms', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.sites', 'django.contrib.staticfiles', 'taggit', 'crispy_forms_gds', 'captcha', 'django.forms', ] In my forms.py I added it just like I've seen in the docs and other questions. forms.py from captcha.fields import CaptchaField, CaptchaTextInput class PostForm(forms.ModelForm): captcha = CaptchaField() class Meta: model = Post fields = [ 'title', 'content', 'image', 'video', 'url', 'tags', ] views.py class PostCreateView(LoginRequiredMixin, CreateView): model = Post fields = … -
I'm trying to build a Django query that will sum multiple categories in to one distinct category
I have a model called Actuals with a field called category which is unique, and another model called Budget which is a many to many field in the Actuals Model. A user can select a unique category in budget and select it in actuals so there can be many actuals to a budget. I am trying to create a query that will group and Sum 'transaction_amount' by category in Actuals model. class Actuals(models.Model): category = models.ForeignKey(Category,on_delete=models.CASCADE) date = models.DateTimeField(auto_now_add=False) transactions_amount = models.IntegerField() vendor = models.CharField(max_length = 255,default="") details = models.CharField(max_length = 255) budget = models.ManyToManyField('budget') def __str__(self): return self.category.category_feild This is the query that I currently have. However it still gives me multiple categories lub = Actuals.objects.filter(category__income_or_expense = 'Expense', date__year = "2022" ,date__month = "01").values('category__category_feild','date').order_by('category__category_feild').annotate(total_actuals = Sum('transactions_amount')).annotate(total_budget = Sum('budget__budget_amt')) This is the output. There should only be one line for "Fun" and one line for "Paycheck". <QuerySet [<Actuals: Fun>, <Actuals: Fun>, <Actuals: Paycheck>, <Actuals: Paycheck>]> -
Employee model details not showing in navbar in django template
I have an issue showing my Employee name and picture in navbar.html I have a CustomUser model from accounts app structure as below core |_accounts |_models.py (CustomUser is in here) | |_employees |_models.py (Employee model in here) My CustomUser is as below class CustomUser(AbstractBaseUser, PermissionsMixin): email = models.EmailField(_('email address'), unique=True) is_staff = models.BooleanField(default=False) is_active = models.BooleanField(default=True) date_joined = models.DateTimeField(default=timezone.now) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] objects = CustomUserManager() def __str__(self): return self.email and my employee model is class Employee(models.Model): # PERSONAL DATA user = models.ForeignKey(User,on_delete=models.CASCADE, related_name="employees") title = models.CharField(_('Title'), max_length=10, default='Mr', choices=TITLE, blank=False, null=True) image = models.ImageField(_('Profile Image'), upload_to='avatars/', blank=True, null=True, help_text='upload image < 2.0MB')#work on path username-date/image firstname = models.CharField(_('Firstname'), max_length=125, null=False, blank=False) lastname = models.CharField(_('Lastname'), max_length=125, null=False, blank=False) In my navbar template I have <img alt="image" src="{{ request.user.employees.image.url }}" class="user-img-radious-style"> and <div class="dropdown-title">Hello {{ request.user.firstname }}</div> My template is not showing the desired results -
503 error while uploading django project in server
I've program written in django and tried to upload in server i've uploaded the project in cpanel and tried to setup in python app in first image there is command to run in terminal i've also tried doing that now i'm getting 503 service unavailable This is my first time hosting so i dont know that is going wrong!! https://prnt.sc/Dy4PiphauS1c https://prnt.sc/aRVB9NDgdWzx https://prnt.sc/osZW-oDow123 -
Gunicorn does not display updated logs. But once I restart gunicorn service it shows all the logs
I went through multiple stack overflow questions and blogs for this issue and tried the answers available but no success. Below is my gunicorn service socket and ngnix config settings. Please help me out have been stuck on this for almost 1 week. gunicorn.socket [Unit] Description=IPU socket [Socket] ListenStream=/run/IPU.sock [Install] WantedBy=sockets.target gunicorn.service [Unit] Description=IPU daemon Requires=IPU.socket After=network.target [Service] User=ubuntu Group=ubuntu WorkingDirectory=/project/path ExecStart=/../../venv/bin/gunicorn \ --bind unix:/run/IPU.sock \ --capture-output \ --workers 4 \ --worker-class gevent \ --worker-connections 1000 \ --timeout 300 \ --access-logfile /path/to/log/access.log \ --error-logfile /path/to/log/error.log \ IPU.wsgi:application [Install] WantedBy=multi-user.target nginx.conf server { listen 9000 default_server; listen [::]:9000 default_server; server_name ip_address; rewrite_log on; location = /favicon.ico { access_log off; log_not_found off; } location /IPU/ { include proxy_params; proxy_pass http://unix:/run/IPU.sock:/; } } -
Filter on single element transformed value of ArrayField
Assuming I have the following Models defined: from django.db import models from django.contrib.postgres.fields import ArrayField from django.db.models import Func, F class SingleDayEvent(models.Model): title = models.TextField() day = models.DateField() class MultiDayEvent(models.Model): title = models.TextField() days = ArrayField(models.DateField(), default=list) If I want a queryset with all SingleDayEvent in a given calendar week, I would do: SingleDayEvent.objects.filter(day__week = week) How can I achieve the same for the MultiDayEvent defined above? -
How can I use two Django authentication backends and give different access depending on which is used?
I have two different classes of user for a Django-based event registration system. Let's call them "Registrant" and "Staffer". These two are not mutually exclusive, and I see no reason not to use the same User model for both classes (with a flag to distinguish them). A Registrant can sign in by verifying their identity with a third-party API, and can then register for an event. A Staffer has access to Django Admin, and can manage events. I do not trust the third-party API to sufficiently authenticate somebody who has Staffer access as, while it does request personal information to identify someone, it doesn't ask for anything as secure as a password. I therefore want Staffers to enter in a password instead of authenticate via the third-party API. I see that I can write a custom auth backend in Django, and I can customise the default User model to suit my needs regarding aforementioned flags (though I suspect the default is_staff) flag might be sufficient). Unfortunately, while I know that I can use multiple authentication backends, I am quite stuck working out how to: a) determine which authentication backend to use (e.g. use the Registrant auth backend in the frontend, … -
Django-Graphql mutation works in Playground but Returns null in ReactJS-Apollo
I making a simple update mutation from Graphql Playground, and I believe that if the mutation is working from playground, Hence there is no issue in backend. mutation{ emwCustomMessageToCustomerUpdate( id:"RU1XQ3VzdG9tSW5mb3JtYXRpb25Gb3JDdXN0b21lcjoxNQ==", input:{ isActive:false, allowClose:false, message:"asdfssdf", displayLocation:"S1", messageHeader:"Dsfsdf" }){ eMWInformationForCheckout{ message } errors{ message } } } Which returns this response indicating call is success, I could verify that. { "data": { "emwCustomMessageToCustomerUpdate": { "eMWInformationForCheckout": { "message": "asdfssdf" }, "errors": [] } } } But when I call this mutation from reactjs-apollo, It is not mutating the data, I am mutating a single key, But it makes other keys to null. The mutation i am using from react is : export const UpdateMessageForCustomer = gql` mutation UpdateMessageForCustomer( $id: ID! $message: String $startDate: DateTime $endDate: DateTime $allowClose: Boolean $displayLocation : String $buttonText : String $screenPlacement : String $messageHeader : String $isActive : Boolean ){ emwCustomMessageToCustomerUpdate(id: $id, input:{ message: $message startDate: $startDate, endDate: $endDate, allowClose: $allowClose, displayLocation : $displayLocation buttonText : $buttonText screenPlacement : $screenPlacement messageHeader : $messageHeader isActive : $isActive }){ eMWInformationForCheckout{ message } errors{ message } } } ` function used to mutate in react component const [UpdateMessageForCustomerMutation] = useMutation(UpdateMessageForCustomer, { onCompleted({ emwCustomMessageToCustomerUpdate }) { if (emwCustomMessageToCustomerUpdate.errors.length) { notify({ text: intl.formatMessage({ defaultMessage: … -
How to fetch webcam data from client side and send to django server for storage and face recognition?
I want to create an app where I can store images and then detect faces. I am using Django. Now I don't know how to send this webcam data to the Django server for further processing with OpenCV. It would be appreciated if someone can write tell how to proceed when the attain img button is clicked. <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible"> {% load static %} <link rel="stylesheet" href={% static 'camera.css' %}> <title>Capture</title> </head> <body> <div class="cameraElement"> <video id="webcam" width="1200" height="600" autoplay></video> </div> <div class="buttonElement-train"> <button type="submit" class="btn-hover color-1" id="train">Train Images &#x2192</button> </div> <div class="buttonElement-back"> <button type="submit" class="btn-hover color-2" id ="back" onclick="window.location.href = '{% url 'reg' %}' ">&#x2190 Back</button> </div> Script part:- <script> let video=document.querySelector("#webcam"); if (navigator.mediaDevices.getDisplayMedia) { navigator.mediaDevices.getUserMedia({ video:true}) .then(function (stream) { video.srcObject = stream; }) .catch(function (error) { console.log("ERROR") }) } </script> views part:- def train_img(request): return render(request, "camera.html") -
Querying a relational table in Django database
I have an database with a relational table created by my Models. This table has all the information I'm trying to query, but I'm having a difficult time getting the values from it that aren't objects of the Model. Models.py class Ingredient(models.Model): '''All ingredients for any recipe or individual selection''' ingredient = models.CharField(max_length=50) department = models.ForeignKey(Department, null=True, on_delete=models.SET_NULL) def __str__(self): return self.ingredient class IngredientDetail(models.Model): '''A class to identify variable quantities of ingredients''' recipe = models.ForeignKey('Recipe', null=True, on_delete=models.SET_NULL) ingredient = models.ForeignKey(Ingredient, null=True, on_delete=models.SET_NULL) quantity = models.CharField(max_length=1) class Meta: verbose_name_plural = 'Ingredient Details' def __str__(self): return self.quantity class Recipe(models.Model): '''A Recipe class to input new recipes''' recipe = models.CharField(max_length=50) ingredients = models.ManyToManyField(Ingredient, through=IngredientDetail) instructions = models.TextField(null=True) cuisine = models.ForeignKey(Cuisine, null=True, on_delete=models.SET_NULL) picture = models.ImageField(upload_to= 'media/', null=True, blank=True) def __str__(self): return self.recipe It creates the following table, which has the info I need: ID quantity ingredient_id recipe_id 1 1 5 5 2 1 6 5 3 2 7 5 When I try to query Ingredient details with IngredientDetails.objects.filter(recipe_id='5'), it only gives me the values for quantity, and I also need the ingredient_id. Did I structure my models incorrectly, or have I overlooked an obvious solution to this? Ideally, I'd like to be able …