Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to validate unique attribute values of an object in respect to that object's other attributes?
I am making a school management system where each student takes 6 subjects. After trying to make dependent dropdown lists, I felt like it wasn't suited for what I was trying to achieve and I failed to implement them. I want to validate that each student's attributes concerning the subjects they're taking is unique, so that there aren't any subjects being taken twice (e.g. to prevent having Chemistry in science and Chemistry in science2) models.py from unittest.util import _MAX_LENGTH from django.db import models from django.utils.translation import gettext_lazy as _ from students.choices import * from django.core.exceptions import ValidationError # Create your models here. class Student(models.Model): def __init__(self, student_number, first_name, last_name, email, english, math, language, science, science2): self.student_number = student_number self.first_name = first_name self.last_name = last_name self.email = email self.english = english self.math = math self.language = language self.science = science self.science2 = science2 def __len__(self): return len(vars(self)) student_number = models.PositiveIntegerField() first_name = models.CharField(max_length=50) #Attribute containing student's first name, cannot exceed 50 characters last_name = models.CharField(max_length=50) #Attribute containing student's last name, cannot exceed 50 characters email = models.EmailField(max_length=100) #Attribute containing student's email, cannot exceed 100 characters #Subjects english = models.CharField(max_length=2, choices=English.choices, null=True, blank=False) math = models.CharField(max_length=2, choices=Math.choices, null=True, blank=False) language = models.CharField(max_length=1, … -
How can I update node version in docker container?
Now, I am developing some personal fullstack project using react, django, postgres and docker. I first use node version 8 but now I try to use node version 16. I tried like this. FROM buildpack-deps:bullseye ENV NODE_VERSION 16.18.0 RUN mkdir /code WORKDIR /code But when I check node version in docker shell, it still shows node 8.17.0 How can I fix that? I look forward to your great help. -
How to make REST API for booking 30 min slots. I have tried using django but it is confusing. any link would be helpful
REST API 30-minute timeslots available to schedule an appointment with a particular room. -
Django many to many field keeps adding every instance to itself
I have model "post" and model "profile". I need to add likes to the post, so I did "ForeignKey" at first, now I have ManyToMany relationship, but I keep seeing how every possible instance of "profile" is automatically being added to every instance of "post". Why is it happening? I didnt have problems like that in my previous projects. models.py for profile from django.db import models from django.conf import settings from django.contrib.auth.models import User class Profile(models.Model): """Fields that can be used to modify the profile page""" name = models.CharField(max_length=50, null=True, blank=True) bio = models.TextField(max_length=160, null=True, blank=True) profilePicture = models.ImageField(null=True, blank=True, upload_to='profiles/', default='default/default-pfp.jpg') """Technical fields unaccessable for users""" owner = models.OneToOneField(User, on_delete=models.CASCADE, related_name='account') following = models.ForeignKey("self", on_delete=models.DO_NOTHING, blank=True, null=True, unique=False) def __str__(self): str=self.owner.username str=str + "'s profile" return str model.py for pot from django.db import models from django.conf import settings from django.contrib.auth.models import User class Post(models.Model): title = models.CharField(max_length=360) body = models.TextField() image = models.ImageField(null=True, blank=True) likes = models.ManyToManyField(User, related_name="blog_posts") author = models.ForeignKey(User, on_delete=models.CASCADE) date = models.DateTimeField(auto_now=False, auto_now_add=True) def __str__(self): str=self.author.username str= self.date.strftime("%d/%m %H:%M ") + str + "'s post" return str def date_posted(self): str = self.date.strftime('%H:%M %d/%m/%y') return str [![Admin panel][1]][1] [1]: https://i.stack.imgur.com/rwgBP.png -
How to set a field different from id as primary key in django rest model
I am new to django_rest framework and I am having a problem with setting another field as primary key and then use that field as foreign key in another model. These are my models: class Test(models.Model): test_id = models.CharField(max_length=50, default="A10", primary_key=True) issue_date = models.DateField() total_amount = models.FloatField(max_length=50, default=1.0) class AnotherModel(models.Model): test_identifier = models.ForeignKey(Test, on_delete=models.CASCADE) #The identifier refered_date = models.DateField(auto_now_add=True, blank=True) But when I try to create an AnotherModel in admin page it shows this error: IntegrityError at /admin/api/anothertest/add/ FOREIGN KEY constraint failed My question is how can I make the test_id primary key and use it as foreign in second model? -
Django-Extra-Views: Inlines child model gets author none. How do I set it the same as the parent?
I have been spinning my wheels on this issue for a day or two. I have django web application that has 3 models users/models.py: from django.db import models from django.db.models.signals import post_save from django.dispatch import receiver from django.contrib.auth.models import User # Create your models here. class ExtendedUser(models.Model): user=models.OneToOneField(User,null=True, on_delete=models.CASCADE) def full_name(self): return (self.user.get_full_name()) def __str__(self): return self.user.get_full_name() @receiver(post_save, sender=User) def create_or_update_user_extendeduser(sender, instance, created, **kwargs): if created: ExtendedUser.objects.create(user=instance) instance.extendeduser.save() playground/models.py: class Customer(models.Model): def __str__(self): return self.Customer_Name Customer_Name = models.CharField(max_length=100) SFDC_Customer_Record_Number = models.IntegerField(default='') Zone = models.CharField(max_length=50, default='') Government = models.BooleanField(default=False) date_posted = models.DateTimeField(default=timezone.now) customerauthor = models.ForeignKey(ExtendedUser, on_delete=models.DO_NOTHING,default=ExtendedUser) def get_absolute_url(self): return reverse('playground-home') class Vue_Quote(models.Model): def __str__(self): return self.Quote_Name Quote_Name = models.CharField(max_length=100) SFDC_Golden_Opp_ID = models.IntegerField() Vue_System_Count = models.IntegerField() date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(ExtendedUser, on_delete=models.DO_NOTHING,default=ExtendedUser,blank=True,null=True) Quote_Type = models.CharField(max_length=100) Customer = models.ForeignKey(Customer, on_delete=models.DO_NOTHING, default='') def get_absolute_url(self): return reverse('quote-detail',kwargs={'pk': self.pk}) I am using the 3rd party application django-extra-views to create a single form which allows a user to create a customer and quote at the same time. Views.py: class QuoteInline(InlineFormSetFactory): model = Vue_Quote fields = ['Quote_Name','SFDC_Golden_Opp_ID','Vue_System_Count','Quote_Type',] factory_kwargs = {'extra':1} class CreateQuoteInlinesView(CreateWithInlinesView): model = Customer inlines = [QuoteInline] fields = ['Customer_Name','SFDC_Customer_Record_Number','Zone','Government'] template_name= 'quote_and_customer.html' def forms_valid(self, form, inlines): form.instance.customerauthor = ExtendedUser.objects.get(user=self.request.user) return super().forms_valid(form,inlines) All of this is working … -
When to use savepoint = False in django transactions?
I can use inner atomic blocks as savepoints and catch inner savepoint errors. This way, we proceed within the atomic outer scope, just rolling back the inner atomic block, as explained in this question, but there is this argument savepoint=False that I don't see any use case for. In the docs: You can disable the creation of savepoints for inner blocks by setting the savepoint argument to False. If an exception occurs, Django will perform the rollback when exiting the first parent block with a savepoint if there is one, and the outermost block otherwise. Atomicity is still guaranteed by the outer transaction. This option should only be used if the overhead of savepoints is noticeable. It has the drawback of breaking the error handling described above. If I understand correctly, it will just change the fact that even catching an error from the inner block, the outer scope will still rollback. Is it correct? -
Serializer user "Invalid data. Expected a dictionary, but got User"
I am trying to display the fields of my user model but I always get that my serializer is not valid { "non_field_errors": [ "Invalid data. Expected a dictionary, but got User." ] } this is my model from django.db import models from django.contrib.auth.models import BaseUserManager, AbstractBaseUser, PermissionsMixin class UserManager(BaseUserManager): def _create_user(self, username, password, is_staff, is_superuser, **extra_fields): user = self.model( username=username, is_staff=is_staff, is_superuser=is_superuser, **extra_fields ) user.set_password(password) user.save(using=self.db) return user def create_user(self, username, password=None, **extra_fields): return self._create_user(username, password, False, False, **extra_fields) def create_superuser(self, username, password=None, **extra_fields): return self._create_user(username, password, True, True, **extra_fields) class User(AbstractBaseUser, PermissionsMixin): username = models.CharField(max_length=255, unique=True) email = models.EmailField( max_length=255, blank=True, null=True) name = models.CharField(max_length=255, blank=True, null=True) age = models.PositiveIntegerField() is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) objects = UserManager() USERNAME_FIELD = 'username' REQUIRED_FIELDS = [] def __str__(self): return f"{self.id} {self.name} {self.username} {self.age}" this is my serializer class UserUpdateSerializer(serializers.ModelSerializer): class Meta: model = User fields = ['id', 'email', 'username', 'name', 'age'] this is my view class UserUpdateApiView(APIView): def get(self, request, pk): try: queryset = User.objects.get(pk=pk) serializer = UserUpdateSerializer(data=queryset) if serializer.is_valid(raise_exception=True): return Response(data=serializer.data) except User.DoesNotExist: return Response(data={"error": "User no found"}, status=status.HTTP_404_NOT_FOUND) -
How can i access the count of a field in Django model?
I want to display the total revenue which equals total price, and total price is a field in the appointments model i want the count of that specific field so i can display it in the html. HELP! The Appointment model -
Insert an HTML icon within a Javascript new div
In this Django project, there is a Javascript function creating a new div in which we display some data. for (var i = 0; i < files.length; i++) { var newDiv = document.createElement('div'); newDiv.setAttribute("class","files_div"); //Call the helper function to check if it's a PDF newDiv.setAttribute("onclick","check_files(this)") console.log(files[i]) //Print the files newDiv.innerHTML = files[i]; divParent.appendChild(newDiv); } I need to add icons next to this data. For example, a pdf icon if it's a pdf file. How do you add icons in Javascript once a new div is created? -
Mock Chained DB query in Django unit test
I have a function that allows users to create a new entry in DB. But before that, I had a check if the user's existing records are less than the permissible range. Below is the function implementation def is_allowed_to_create(permissible_range): count = MyModel.objects.filter(query)[:permissible_range].count() return not count >= permissible_range Inside the test file, I am doing @mock.patch('MyApp.models.MyModel.objects') def test_is_allowed_to_create(self, mock_qs, *args, **kwargs): mock_qs.filter.return_value = mock_qs mock_qs.count.return_value = 10 self.assertTrue(is_allowed_to_create(5)) And the error I am getting is TypeError: '>=' not supported between instances of 'MagicMock' and 'int'. So what I understood from the error is, my code is not setting the proper return value for the entire DB query ie MyModel.objects.filter(query)[:permissible_range].count() . How can I set mock value for MyModel.objects.filter(query)[:permissible_range].count() as an integer. Thanks! -
Django - Aggregate into array
I have the a django model with the below data: Name Value A 1 B 2 B 4 C 7 C 5 I would like to use an aggregate my table so that I can get my data in the below format: Name Value A 1 B [2,4] C [7,5] How do I do this with Django. I'm thinking this may be the answer but Django doesn't seem to have ArrayAgg. This looks to be a Django Postgres function Test_Model.objects.annotate(dname=ArrayAgg('name')).values() Do you know how I can achieve this using native Django functions and solutions? Thank you! -
Django CharField with dynamic default value
I want to add a new field to a PostgreSQL database. It's a not null and unique CharField, like dyn = models.CharField(max_length=50, null=False, unique=True) The database already has relevant records, so it's not an option to delete the database reset the migrations wipe the data set a default static value. How to proceed? -
What does Ajax really look like?
I just researching about Ajax for afew day (To use with Django Python framwork) But I found many result about Ajax. 1. function loadDoc() { var xhttp = new XMLHttpRequest(); xhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { document.getElementById("demo").innerHTML = this.responseText; } }; xhttp.open("GET", "ajax_info.txt", true); xhttp.send(); } $.ajax({ type: "POST", url: actionUrl, .... }); fetch("api/xxx", { method: "post", } .then(...) Does 3 of these is the same? -
How can I re-build my Django Framework Sitemap?
I did my Django Sitemap, and it works in its sitemap.xml file, but I made some changes by adding more URLs to the map, even if I migrate them, my sitemap does not update. I've tried to create another branch and recreate everything, I've tried refresh_sitemap but it is not accepted. I really do not know how to rebuild it and I tried many things. -
using contents within a Django Zip File
I was sent a Django Project from a friend and want to start working on it. I'm mostly a JS developer but was wondering if there was an npm i equivalent for django that will download everything I need? Thanks in advance -
How to add a dropdown select to the django admin search form?
Is it possible to customize the django admin search form by adding a custom select input based on which later filter the queryset? 1 - Extended search_form.html for a given model admin {% load i18n static %} {% if cl.search_fields %} <div id="toolbar"><form id="changelist-search" method="get"> <div><!-- DIV needed for valid HTML --> <label for="searchbar"><img src="{% static "admin/img/search.svg" %}" alt="Search"></label> <input type="text" size="40" name="{{ search_var }}" value="{{ cl.query }}" id="searchbar" autofocus> <input type="submit" value="{% trans 'Search' %}"> # start of custom code <label for="search-type">Typ vyhledávání:</label> <select name="search-type" id="search-type" form="changelist-search"> <option value="all">Vše</option> <option value="pn">PN</option> <option value="email">Email</option> <option value="order-id">Id objednávky</option> </select> # end of custom code {% if show_result_count %} <span class="small quiet">{% blocktrans count counter=cl.result_count %}{{ counter }} result{% plural %}{{ counter }} results{% endblocktrans %} (<a href="?{% if cl.is_popup %}_popup=1{% endif %}">{% if cl.show_full_result_count %}{% blocktrans with full_result_count=cl.full_result_count %}{{ full_result_count }} total{% endblocktrans %}{% else %}{% trans "Show all" %}{% endif %}</a>)</span> {% endif %} {% for pair in cl.params.items %} {% if pair.0 != search_var %}<input type="hidden" name="{{ pair.0 }}" value="{{ pair.1 }}">{% endif %} {% endfor %} </div> </form> </div> {% endif %} 2 - I need to get the selected option from the select html tag when submitted. … -
Unicode error when running my django view hosted on apache2
So I have deployed my django app on my ubuntu server using apache2. However, one view is now giving me an error which was not present on my windows computer. Traceback (most recent call last): File "/home/tinytoes/survey/venv/lib/python3.8/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/home/tinytoes/survey/venv/lib/python3.8/site-packages/django/core/handlers/base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/tinytoes/survey/venv/lib/python3.8/site-packages/sentry_sdk/integrations/django/views.py", line 67, in sentry_wrapped_callback return callback(request, *args, **kwargs) File "/home/tinytoes/survey/venv/lib/python3.8/site-packages/django/contrib/auth/decorators.py", line 21, in _wrapped_view return view_func(request, *args, **kwargs) File "/home/tinytoes/survey/questionnaire/views.py", line 760, in results_export writer.writerow(row_list) Exception Type: UnicodeEncodeError at /survey/results/export/1QbfjRgEEbLNyqV/ Exception Value: 'ascii' codec can't encode character '\u2019' in position 783: ordinal not in range(128) I have looked at my locale and everything seems to be okay LANG=en_GB.UTF-8 LANGUAGE= LC_CTYPE="en_GB.UTF-8" LC_NUMERIC="en_GB.UTF-8" LC_TIME="en_GB.UTF-8" LC_COLLATE="en_GB.UTF-8" LC_MONETARY="en_GB.UTF-8" LC_MESSAGES="en_GB.UTF-8" LC_PAPER="en_GB.UTF-8" LC_NAME="en_GB.UTF-8" LC_ADDRESS="en_GB.UTF-8" LC_TELEPHONE="en_GB.UTF-8" LC_MEASUREMENT="en_GB.UTF-8" LC_IDENTIFICATION="en_GB.UTF-8" LC_ALL= I'm not entirely sure if i need to change something in the apache configurations. Any help would be much appreciated -
Celery worker stop without any error after task completion
Celery worker running in ubuntu stops without any error after the process completion But The celery beat keeps running without any issues. Recently this problem occurs when deployed to the new server the DB schema and some code also were changed previously it was running fine both worker and beat. Comand use to run celery worker celery -A base worker -l info --detach --logfile=logs/celery.log -n celery_worker No error after the process completes which takes around 80, 90 min to complete. After completion, there is no celery worker process running and the next task doesn't execute. What might be the issue here how can I debug it? -
Python get list of o365 users through MS Graph. Missing infomtion
from O365 import Account credentials = ('hidden', 'hidden') # the default protocol will be Microsoft Graph account = Account(credentials, auth_flow_type='credentials', tenant_id='hidden') users_list=[] directory = account.directory() for user in directory.get_users(): print(dir(user)) I am connected to O365 and can gather users. I would like to see the users last password change date but the class is returning a None type. is this a MS graph permissions error or is it now supported in this API. see the bellow result. ['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_base_url', '_build_date_time_time_zone', '_cc', '_cloud_data_key', '_endpoints', '_gk', '_parse_date_time_time_zone', '_parse_resource', 'about_me', 'account_enabled', 'age_group', 'assigned_licenses', 'assigned_plans', 'birthday', 'build_base_url', 'build_url', 'business_phones', 'city', 'company_name', 'con', 'consent_provided_for_minor', 'country', 'created', 'department', 'display_name', 'employee_id', 'fax_number', 'full_name', 'get_profile_photo', 'given_name', 'hire_date', 'im_addresses', 'interests', 'is_resource_account', 'job_title', 'last_password_change', 'legal_age_group_classification', 'license_assignment_states', 'mail', 'mail_nickname', 'mailbox_settings', 'main_resource', 'message_constructor', 'mobile_phone', 'my_site', 'new_message', 'new_query', 'object_id', 'office_location', 'other_mails', 'password_policies', 'password_profile', 'past_projects', 'postal_code', 'preferred_data_location', 'preferred_language', 'preferred_name', 'protocol', 'provisioned_plans', 'proxy_addresses', 'q', 'responsibilities', 'schools', 'set_base_url', 'show_in_address_list', 'sign_in_sessions_valid_from', 'skills', 'state', 'street_address', 'surname', 'type', 'update_profile_photo', 'usage_location', 'user_principal_name', 'user_type'] -
Django genecric.FormView: 'NoneType' object is not callable
i'm trying to render a really basic FormView but it says it cant get the form model. full error: Traceback (most recent call last): File "/usr/local/lib/python3.10/site-packages/django/core/handlers/exception.py", line 55, in inner response = get_response(request) File "/usr/local/lib/python3.10/site-packages/django/core/handlers/base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/usr/local/lib/python3.10/site-packages/django/views/generic/base.py", line 103, in view return self.dispatch(request, *args, **kwargs) File "/usr/local/lib/python3.10/site-packages/django/views/generic/base.py", line 142, in dispatch return handler(request, *args, **kwargs) File "/usr/local/lib/python3.10/site-packages/django/views/generic/edit.py", line 144, in get return self.render_to_response(self.get_context_data()) File "/usr/local/lib/python3.10/site-packages/django/views/generic/edit.py", line 74, in get_context_data kwargs["form"] = self.get_form() File "/usr/local/lib/python3.10/site-packages/django/views/generic/edit.py", line 39, in get_form return form_class(**self.get_form_kwargs()) Exception Type: TypeError at /new-game/ Exception Value: 'NoneType' object is not callable Form: class NewGameForm(ModelForm): class Meta: model = models.Game fields = ['title', 'bank_money', 'player_starting_money', 'golden_card_amount'] View: class NewGameView(generic.FormView): template_name = 'games/create_game.html' form = forms.NewGameForm Note that django development server is running on a linux docker container with python 3.10.7 -
Sorting dynamic data with multiple parameters and distribute them equally in python dango
I wanted to sort a list of users based on some field parameters and distribute them into a list equally, I am trying to make an automated way to help schools distribute students into classrooms as part of a bigger system. Explaining functionality: let's assume there are 100 students registered for 4th grade and within the grade, there are 4 sections{A, B, C, D}, when the function is run I want to take all the students registered for 4th grade and put them in a list afterward the function should iterate through the list and try(because there will be closely related values and might not be exactly similar) to equally distribute them in 4 lists(number of sections) or directly save them with there respective section instance, the effect should in some way resemble a magnet in which similarities repulse each other and difference attracts each other until the lists are refined to the best they can be. it's not much of a problem if the method is slow because there will not be a lot of students in one list since it's going to execute at grade level, please point me to a resource, share a snipper or explain the … -
Updating formset in Django
I am using formset to save data into my database. The form creation part works fine, However, the form update only returns the instance of the parent model but that of the child model is not returned, any help would be appreciated Here are my code snippets: Model.py class Sale(models.Model): billno = models.AutoField(primary_key=True) supplier = models.ForeignKey(WorkerDetails, on_delete=models.SET_NULL, null=True) created = models.DateTimeField(auto_now_add=True) class SaleDetails(models.Model): billno = models.ForeignKey(Sale, on_delete = models.CASCADE) producttype = models.ForeignKey(Producttype, on_delete=models.SET_NULL, null=True) quantity = models.DecimalField(default=0,decimal_places = 5, max_digits = 30) perprice = models.DecimalField(default=1,decimal_places = 5,max_digits = 30) totalprice = models.DecimalField(default=1,decimal_places = 5, max_digits = 30) Forms.py class SalesForm(forms.ModelForm): ..... class Meta: model = Sale fields = '__all__' class SalesDetailsForm(forms.ModelForm): ........ class Meta: model = SaleDetails fields = ['quantity', 'perprice','producttype','totalprice'] SalesFormset = formset_factory(SalesDetailsForm, extra=1) views.py class SalesUpdateView(View): template_name = 'sales/sales-edit.html' def get(self, request,pk): try: billno = Sale.objects.get(pk=pk) except Sale.DoesNotExist: raise Http404 #details = SaleDetails.objects.filter(billno=pk) form = SalesForm(request.GET or None, instance=billno) formset = SalesFormset(request.GET or None,) context = { 'form' : form, 'formset' : formset, } return render(request, self.template_name, context) def post(self, request): form = SalesForm(request.POST) formset = SalesFormset(request.POST) if form.is_valid() and formset.is_valid(): billobj = form.save(commit=False) for form in formset: billitem = form.save(commit=False) billitem.billno = billobj billobj.save() billitem.save() messages.success(request, "Sold … -
django queryset filter check if ManyToMany Field contains specific object
I have these two models : class Project(models.Model): name = models.CharField(max_length=50) users = models.ManyToManyField(User) class User(models.Model): name = models.CharField(max_length=25) I want to get a queryset containing all the Projects with a specific user in the 'users' ManyToManyField I tried this : Project.objects.filter(users__contains=user), but it's not working Does someone know how can I do it ? -
Database admin page
After uploading the site to hosting I tried to access the admin page But I was not allowed to enter Error: FATAL: password authentication failed for user "postgres" Do I have to change my data in settings.py ? DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'dbtst', 'USER': 'postgres', 'PASSWORD':'******', 'HOST': 'localhost', 'PORT': '5432', } }