Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Unique validation error with base_field of a django array field during update
I want the phone numbers inside my phones field to be unique across all customers. it works fine during creating a new customer, But during update i got a unique validation error. def prevent_replicated_phone(phone): # Count all customers which own the same number phone_holders = Customer.objects.filter(phones__contains=[phone]).count() if phone_holders > 0 : raise ValidationError( f'The phone number: {phone} already exist', class Customer(models.Model): def __str__(self) : return self.customer_name id = models.BigAutoField(primary_key=True) customer_name = models.CharField(max_length=100, null=False, blank=False, unique=True) phones = ArrayField(models.CharField(max_length=10, validators=[validate_phone_number, prevent_replicated_phone]), default=list, null=True, blank=True) customer_type = models.CharField(max_length=10,default='patient', choices=CUSTOMER_TYPE) Let say i have a customer hold the phones ['0795364588']. I send a put request to update the customer phones with new array ['0795364588', '0668123544']. Updating the customer phones with postman How i can solve this. -
Django return custom HTTP message
I'm trying to be compatible with an app-side bug(). I want to return a response with custom HTTP message For example, I get HTTP/1.1 429 TOO_MANY_REQUESTS now, I want get HTTP/1.1 429 CUSTOM_MESSAGE Howerver, I can get only h2 200 -
I can store password when want to create a user in django
Model this is my extended model with one to one field class Etudiant(models.Model): user = models.OneToOneField(User,on_delete=models.CASCADE,null=True,blank=True) nom = models.CharField(max_length=50) prenom = models.CharField(max_length=50) username = models.CharField(max_length=50) num_cart = models.IntegerField(default=0) email = models.EmailField(max_length=254) date_naissance = models.DateField(auto_now=False, auto_now_add=False,blank=True,null=True) password = models.CharField(max_length=50,null=True,blank=True) groupe = models.ForeignKey("Group", on_delete=models.CASCADE,null=True,blank=True) this is the forms of user form and etudiant form forms.py class UserForm(forms.ModelForm): class Meta: model = User fields = ('username','first_name', 'last_name', 'email','password') widgets = { 'username' : forms.TextInput(attrs={'class':'form-control'}), 'first_name' : forms.TextInput(attrs={'class':'form-control'}), 'last_name' : forms.TextInput(attrs={'class':'form-control'}), 'email' : forms.EmailInput(attrs={'class':'form-control'}), 'password' : forms.PasswordInput(attrs={'class':'form-control'}), } class EtudiantForm(forms.ModelForm): class Meta: model = Etudiant fields = ('num_cart','date_naissance','groupe') widgets = { 'num_cart' : forms.NumberInput(attrs={'class':'form-control'}), 'date_naissance' : forms.DateInput(attrs={'class':'form-control'}), 'groupe' : forms.Select(attrs={'class':'form-control'}), } this views for store data to db all the data stored just the password I see "Invalid password format or unknown hashing algorithm. " #views.py def ajouter_etudiant(request): user_form = UserForm() etudiant_form = EtudiantForm() if request.method == 'POST': user_form = UserForm(request.POST) if user_form.is_valid() : user_form.save() user = User.objects.get(username = request.POST['username']) groupe_name = Group.objects.get(id=request.POST.get('groupe')) Etudiant.objects.create( user = user, username = user.username, nom = user.last_name, prenom = user.first_name, num_cart = 123456789123456789, email = user.email, date_naissance = request.POST.get('date_naissance'), groupe = groupe_name ) return redirect('all_etudiant') return render(request,'etudiant/ajouter-etudiant.html',{'form' : user_form,'form2':etudiant_form}) -
How to use prefetch_related to retrieve multiple rows similar to SQL result
I’ve a question about the usage of prefetch_related. Based on my understanding I need to use prefetch_related for reverse foreign key relationships As an example I have a User(id, name) model and SchoolHistory(id, start_date, school_name, user_id[FK user.id]) model. A user can have multiple school history records. If I’m querying the database using the following SQL query: SELECT user.id, name, start_date, school_name FROM user INNER JOIN school_history ON school_history.user_id = user.id the expected result would be: | User ID | Name | Start Date | School | | 1 | Human | 1/1/2022 | Michigan | | 1 | Human | 1/1/2021 | Wisconsin | This is the current result that I’m getting instead with ORM and a serializer: | User ID | Name | school_history | 1 | Human | [{start_date:1/1/2022 , school:Michigan}, {start_date:1/1/2021 , school:Wisconsin}] | This is the ORM query that I’m using: User.objects.prefetch_related( Prefetch( ‘school_history’ query_set=SchoolHistory.objects.order_by(‘start_date’) ) ) Is there a way for the ORM query to have a similar result as SQL? I want multiple rows if there are multiple schools associated with that user -
DRF SlugRelatedField causes extra queries with the argument `queryset` when making get request
in debug tool bar, I can tell there are duplicate queries pointing to source and target and also workflow. So I decide to make those two fields read_only=True and remove the queryset argument. And things work perfectly. my code looks like: # model class Activity(models.Model): class Meta: db_table = "activity" uuid = serializers.UUIDField(read_only=True) some fields ... class Flow(models.Model): class Meta: db_table = "workflow_flow" objects = FlowManager() source = models.ForeignKey( "Activity", db_index=True, related_name="outgoing", to_field='uuid', db_constraint=False, on_delete=models.CASCADE, max_length=32, null=True, blank=True, default="" ) target = models.ForeignKey( "Activity", db_index=True, related_name="incoming", to_field='uuid', db_constraint=False, on_delete=models.CASCADE, max_length=32, null=True, blank=True, default="" ) workflow = models.ForeignKey( "WorkFlow", db_index=True, related_name="flows", to_field='uuid', db_constraint=False, on_delete=models.CASCADE, max_length=32, ) # serializer class FlowSerializer(ModelSerializer): class Meta: fields = "__all__" model = Flow condition = serializers.CharField( default="", required=False, allow_null=True, allow_blank=True, write_only=True ) # foreign key source = serializers.SlugRelatedField( queryset=api_models.Activity.objects.all(), slug_field="uuid", ) target = serializers.SlugRelatedField( slug_field="uuid", queryset=api_models.Activity.objects.all() ) workflow = serializers.SlugRelatedField(slug_field="uuid", queryset=api_models.WorkFlow.objects.all()) # viewset class FlowViewSet(ModelViewSet): queryset = api_models.Flow.objects.all().select_related("source", "target", "workflow").all() lookup_field = 'uuid' serializer_class = api_serializers.FlowSerializer But I need to create those two fields any idea? I know I can change them to CharField Instead But I want a correct way to handle this. By reading the source code of the SlugRelatedField queryset is used for … -
How to implement a HTTP API with django
I have read that HTTP APIs are faster and more light-weight than REST APIs. However I only find resources that explain how to build REST APIs in django. How do you build a HTTP API and not a REST API in django? -
access URL data in serializers class in Django Rest Framework
I'm getting None while accessing the data of the request. views.py def get(self, request, post_id, post_language_id, user_id): ... paginator = CustomPageNumberPagination() response = paginator.generate_response(language_liked_data, PostLanguageLikedSerializer, request) return response but I need user_id from the URL so I found a way to access data through context. so I can access the value in the serializer. views.py def get(self, request, post_id, post_language_id, user_id): ... language_liked_data = PostLanguageLike.objects.filter(post_language_id=post_in_lang.id) post_language_like_serializer = PostLanguageLikedSerializer(language_liked_data, context={'user_id': user_id}, many=True) return Response({"response": True, "return_code": "success", "result": {"liked_users": post_language_like_serializer.data}, "message": success["success"]}, status=200) serializers.py class PostLanguageLikedSerializer(serializers.ModelSerializer): is_following = serializers.SerializerMethodField() ... class Meta: model = PostLanguageLike fields = [...,'is_following'] def get_is_following(self, obj): # here I want to access URL data. user_id = self.context.get("user_id") user_followings = UserFollowing.objects.filter(user_id=user_id, following_user_id=obj.user.id) is_following = True if len(user_followings) > 0 else False return is_following the issue is I'm not able to use context={'user_id': user_id} with paginator.generate_response is there any better way to get URL data in the serializer? -
Django local variable 'context' referenced before assignment
where is my mistake? Can anyone see it? view.py error -
Swagger not responding when adding urls from another django app
I have a simple Django app and want to include urls to project urls. Project urls look like this: from drf_spectacular.views import ( SpectacularAPIView, SpectacularSwaggerView, ) from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('api/schema/', SpectacularAPIView.as_view(), name='api-schema'), path('api/docs/', SpectacularSwaggerView.as_view(url_name='api-schema'), name='api-docs'), path('api/user/', include('user.urls')), #path('api/', include('LinkTaskApp.urls')), ] And LinkTaskApp urls look like this: from django.urls import path from .views import AccountListView urlpatterns = [ path('account/', AccountListView.as_view(), name='account-list'), ] As soon as I uncomment in the main urls: #path('api/', include('LinkTaskApp.urls')), I get following error when I start Swagger: Failed to load API definition. Errors Hide Fetch error Internal Server Error /api/schema/ In browser, it looks like this: Request URL: http://127.0.0.1:8000/api/schema/ Request Method: GET Status Code: 500 Internal Server Error Remote Address: 127.0.0.1:8000 Referrer Policy: same-origin Any Ideal how to successfully include this url and get swagger to work? -
how to run python manage.py migrate inside a docker container that runs Django with apache2
I'm running Django app inside Docker container with apache2, I need to add the command python manage.py migrate inside the Dockerfile or docker-compose but am unable to run it . Dockerfile FROM ubuntu RUN apt-get update # Avoid tzdata infinite waiting bug ARG DEBIAN_FRONTEND=noninteractive ENV TZ=Africa/Cairo RUN apt-get install -y apt-utils vim curl apache2 apache2-utils RUN apt-get -y install python3 libapache2-mod-wsgi-py3 RUN ln /usr/bin/python3 /usr/bin/python RUN apt-get -y install python3-pip #Add sf to avoid ln: failed to create hard link '/usr/bin/pip': File exists RUN ln -sf /usr/bin/pip3 /usr/bin/pip RUN pip install --upgrade pip RUN pip install django ptvsd COPY www/demo_app/water_maps/requirements.txt requirements.txt RUN pip install -r requirements.txt ADD ./demo_site.conf /etc/apache2/sites-available/000-default.conf EXPOSE 80 WORKDIR /var/www/html/demo_app CMD ["apache2ctl", "-D", "FOREGROUND"] CMD ["python", "manage.py", "migrate", "--no-input"] docker-compose version: "2" services: db: image: postgres volumes: - ./data/db:/var/lib/postgresql/data environment: - POSTGRES_DB=database_innvoentiq - POSTGRES_USER=database_user_innvoentiq - POSTGRES_PASSWORD=mypasswordhere - PGDATA=/tmp django-apache2: build: . container_name: water_maps environment: - POSTGRES_DB=database_innvoentiq - POSTGRES_USER=database_user_innvoentiq - POSTGRES_PASSWORD=mypasswordhere - PGDATA=/tmp ports: - '80:80' volumes: - ./www/:/var/www/html depends_on: - db what happens here is that the container exists after running the last CMD in the Dockerfile -
Why am I getting a No Reverse Match error when submitting using UpdateView?
I'm currently using UpdateView to add edit functionality to my Django project. It's working correctly insofar as I can edit my data, however when I submit the new data, it returns a NoReverseMatch error: NoReverseMatch at /MyHealth/edit/8 Reverse for 'health_hub_history' not found. 'health_hub_history' is not a valid view function or pattern name. I've researched it and added a get_absolute_url to my model, but it isn't working. Any help would be appreciated! models.py: from django.db import models from django.contrib.auth.models import User from django.urls import reverse class HealthStats(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) date = models.DateField(auto_now=True) weight = models.DecimalField(max_digits=5, decimal_places=2) run_distance = models.IntegerField(default=5) run_time = models.TimeField() class Meta: db_table = 'health_stats' ordering = ['-date'] def get_absolute_url(self): return reverse('health_hub_history') def __str__(self): return f"{self.user} | {self.date}" urls.py: from django.urls import path from django.contrib.staticfiles.storage import staticfiles_storage from django.views.generic.base import RedirectView from . import views app_name = 'HealthHub' urlpatterns = [ path('', views.home, name='home'), path('MyHealth/', views.health_hub, name='health_hub'), path('MyHealth/update', views.UpdateHealth.as_view(), name='health_hub_update'), path('MyHealth/history', views.health_history, name='health_hub_history'), path('favicon.ico', RedirectView.as_view(url=staticfiles_storage.url("favicon.ico"))), path('MyHealth/delete/<item_id>', views.delete_entry, name='health_hub_delete'), path('MyHealth/edit/<int:pk>', views.EditHealth.as_view(), name='health_hub_edit'), ] Views.py: class EditHealth(UpdateView): model = HealthStats template_name = 'health_hub_edit.html' fields = ['weight', 'run_distance', 'run_time'] health_hub_edit.html: {% extends 'base.html' %} {% load static %} {%load crispy_forms_tags %} {% block content %} <div class="container-fluid"> <div class="row"> <div … -
Django - multiple context in single view
lune 90 context is working but line 112 context is not working in HTML Page Then, What should I do? code image -
django filter with the properties of the last object
I am trying to refactor this piece of code to improve time complexity by reducing the number of loops. items = DataActionItem.objects.filter(status='resolved', site_id=settings.SITE_ID) resolved = [] for item in items: init = [resolved.history_date for resolved in item.history.filter(status='resolved', history_date__lte=datetime.datetime.today(), history_date__gt=datetime.datetime.today() - datetime.timedelta( days=7)) if getattr(resolved.prev_record, 'status') != 'resolved'] resolved.append(max(init).date()) rc = Counter() rc.update(resolved) So far, this is what I have. DataActionItem.history.filter(site_id =40, status='resolved', history_date__lte=datetime.datetime.today(), history_date__gt=datetime.datetime.today()-datetime.timedelta(days=7)).values('id', 'history_date').distinct().annotate(day=TruncDate('history_date'), ).values('day').annotate(n=Count('id')).order_by('day') While writing this query, I got stuck at the point when I was checking the previous object. See below. getattr(resolved.prev_record, 'status') != 'resolved' I would like to compare each object in the query set to the last object and only return the ones that their previous history objects do not have a resolved status. If someone can help me cut down the number of loops in the original query, that will be great. -
Django4: Ajax AttributeError
I'm trying to create this Ajax request: The views file is as follows: reports/views.py from django.shortcuts import render from profiles.models import Profile from django.http import JsonResponse from .utils import get_report_image from .models import Report from .forms import ReportForm # Create your views here. def create_report_view(request): form = ReportForm(request.POST or None) if request.is_ajax(): image = request.POST.get('image') name = request.POST.get('name') remarks = request.POST.get('remarks') img = get_report_image(image) author = Profile.objects.get(user=request.user) if form.is_valid(): instance = form.save(commit=False) instance.image = img instance.author = author instance.save() # Report.objects.create(name=name, remarks=remarks, image=img, author=author) return JsonResponse({'msg': 'send'}) return JsonResponse({}) utils.py import base64, uuid from django.core.files.base import ContentFile def get_report_image(data): _ , str_image = data.split(';base64') decoded_img = base64.b64decode(str_image) img_name = str(uuid.uuid4())[:10] + '.png' data = ContentFile(decoded_img, name=img_name) return data urls.py from django.urls import path from .views import create_report_view app_name = 'reports' urlpatterns = [ path('save/', create_report_view, name='create-report'), ] forms.py from django import forms from .models import Report class ReportForm(forms.ModelForm): class Meta: model = Report fields = ('name', 'remarks') I'm not sure why but this is the error I'm getting. Does this mean that is_ajax() is no longer accepted with Django 4.1.1? If so how would I need to adjust the code? if request.is_ajax(): AttributeError: 'WSGIRequest' object has no attribute 'is_ajax' [21/Sep/2022 … -
How to pass CSRF token manually for POST requests in ajax Django
We have a Django app which works as an iframe and it works fine in Safari and Chrome Browsers but in Safari it is blocking all the cookies and sessions that causes all the post request to be forbidden due to no CSRF Cookie. So is there any way we can pass this CSRF cookie along with headers using AJAX post. -
How to group ModelMultipleChoiceField with widget CheckboxSelectMultiple into categories?
I have seen some similar questions on this site, but all of them propose an insanely complex solution to such a straight forward task, and it is the same solution that different users have copy/pasted from a single source somewhere. In a forms.Form I have: self.fields['objects'].queryset = Object.objects.all() Should it not be possible to access this objects category field in a template loop for checkboxes so it will be possible to sort them according to which category they belong? If not and one has to create a custom widget or field, it surely must be possible to do with a couple of lines and not 70+ like in other answers here? Thanks for your time and help, it is appreciated. -
how to add for loop in app layout plotly dash
I want to add a for loop in the app layout, but my approach is wrong. Do you have any idea to make this work? for example. app.layout = html.Div(children=[ for x in data: //invalid syntax html.Div([ dcc.Graph( id='my-id', animate=True, figure={'data': graph, 'layout': layout}, ), ]), ] ) it's invalid syntax. But I want to for loop the html.div so that the graph will show repeatedly based on number of data. -
I try to create a superuser but the error is no such table: users_user
the error is : django.db.utils.OperationalError: no such table: users_user this is my model: class User(AbstractUser): pass the settings: AUTH_USER_MODEL = 'users.User' -
Azure App Service: How to run management command for dockerized django application
I've a django applicaiton running in docker-compose in local along with an nginx and frontend applicaiton. I've tried to deploy the applicaiton in azure app service using my custom docker image for the django application. The app deployment was successfull but now i need to run django management command like python manage.py migrate and python manage.py createsuperuser. I tried to use SSH in my django container, but when i tried to connect its showing az webapp create-remote-connection --subscription <id> --resource-group <rg-name> -n <app-anme> & Is there any other way to run django management commands in azure app service with a multi-container application. -
Can't open lib 'ODBC Driver 17 for SQL Server' : file not found (0) (SQLDriverConnect)") on Azure Linux
I'm trying to deploy python django app on azure linux using azure cli and after deployment it is showing me database connectivity error for drivers. error message is "Can't open lib 'ODBC Driver 17 for SQL Server' : file not found (0) (SQLDriverConnect)") on Azure Linux" enter image description here -
What is context_object_name=None in django class CeateView?
Get the name to use for the object. For context_object_name=None Doc:For example Article will be article Why we use context_object_name in createview.We don't have a object,we just have a simple for to show users. def get_context_object_name(self, obj): """Get the name to use for the object.""" if self.context_object_name: return self.context_object_name elif isinstance(obj, models.Model): return obj._meta.model_name else: return None Please somebody help me??? -
Graphene without Django ORM models
I am using 2 DBs (Postgre as primary & Redshift for Big Data). All basic migrations are connected with Postgre DB & ORM based. But, All complex quries for reports & analysis on big data is using Redshift through RAW quries of django. (no Model class or migration on redshift, some external resource dumping data to Redshift). I am struggling to integrate Graphene-Django with my Redshift tables, but Docs mention DjangoObjectType conversion of django model as 1st step, which I don't have in my case. Currently, I am using cursor.execute(query) & cursor.fetchall() to get my results from Redshift tables. How I can bind these tables with Graphene in schema.py. class CategoryType(DjangoObjectType): class Meta: model = Category fields = ("id", "name") -
Django django module not found error no module listings
Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.1776.0_x64__qbz5n2kfra8p0\lib\threading.py", line 1016, in _bootstrap_inner self.run() File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.1776.0_x64__qbz5n2kfra8p0\lib\threading.py", line 953, in run self._target(*self._args, **self._kwargs) File "C:\Users\Acer\Desktop\Project_Real\venv\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) packages\django\core\checks\registry.py", line 88, in run_checks new_errors = check(app_configs=app_configs, databases=databases) File "C:\Users\Acer\Desktop\Project_Real\venv\lib\site-packages\django\core\checks\urls.py", line 42, in check_url_namespaces_unique File "C:\Users\Acer\Desktop\Project_Real\venv\lib\site-packages\django\urls\resolvers.py", line 715, in url_patterns ...... ModuleNotFoundError: No module named 'listings.urls' -
ERROR: Must appear in the GROUP BY clause or be used in an aggregate function "DJANGO"
I get the following error with my queryset: django.db.utils.ProgrammingError: column "u0.color" must appear in the GROUP BY clause or be used in an aggregate function LINE 1: ...."payment_amount"), 0)) AS "owed_amount", (SELECT U0."color"... These are my models: class DebitFileScore(CustomModel): minimum_amount = models.PositiveIntegerField(verbose_name=_("Monto minimo"), help_text=_("Monto minimo para semaforo"),unique=True) color = models.CharField(max_length=8, verbose_name=_("Color asignado"), help_text=_("Color asignado para semaforo")) class DebitFile(CustomModel): debit_file_section = models.ForeignKey(DebitFileSection, on_delete=models.PROTECT, related_name='debit_files', verbose_name=_("Departamento de expediente"), help_text=_("Referencia foranea al modelo 'DebitFileSection'")) debit_amount = models.FloatField(default=0, verbose_name=_("Monto de aduedo")) name = models.CharField(null=True, blank=True, max_length=100, verbose_name=_("Nombre del acredor"), help_text=_("Nombre del acredor")) comments = models.TextField(null=True, blank=True, verbose_name=_("Comentarios"), help_text=_("Comentarios libres")) cut_off_date = models.DateField(default=date.today,verbose_name=_("Fecha de Corte")) phone = models.CharField(null=True, blank=True, max_length=200, verbose_name=_("Teléfono"), help_text=_("Teléfono de acredor")) date = models.DateField(verbose_name=_("Fecha Registro")) timestamp = models.DateTimeField(auto_now=True) objects = querysets.DebitFileQueryset.as_manager() class DebitFilePayment(CustomModel): debit_file = models.ForeignKey(DebitFile, on_delete=models.PROTECT, related_name='debit_file_payments', verbose_name=_("Operador"), help_text=_("Referencia foranea al modelo 'Operator'")) payment_amount = models.FloatField(default=0, verbose_name=_("Monto de aduedo")) comments = models.TextField(null=True, blank=True, verbose_name=_("Comentarios"), help_text=_("Comentarios libres")) date = models.DateField(verbose_name=_("Fecha Registro")) timestamp = models.DateTimeField(auto_now=True) This is the queryset I'm trying to create, it's the withScore() method that fails: class DebitFileQueryset(models.QuerySet): def withPaymentsAmount(self): return self.annotate( owed_amount=models.F("debit_amount") - models.functions.Coalesce(models.Sum("debit_file_payments__payment_amount"),0), ) def withScore(self): from GeneralApp.models import DebitFileScore score = DebitFileScore.objects.filter(minimum_amount__lte=models.OuterRef('owed_amount')).exclude(minimum_amount__gt=models.OuterRef('owed_amount')) return self.annotate( score_color=models.Subquery(score.order_by('minimum_amount','color').values('color')), ).order_by("score_color") I followed the example of the documentation https://docs.djangoproject.com/en/4.1/ref/models/expressions/#subquery-expressions My Django version … -
Create calculated column with if expression django
I want to create a new calculated column on my django queryset (Models.objects) that will be calculated as: field_one if field_one is not null else field two I've tried some like this in django: from models.models import Model from django.db.models import F data = Model.objects.annotate(start_date= F('better_date') if F('better_date') is not None else F('field_2')) data[0].__dict__['start_date'] # Result #'start_date': None But I get a 'start_date' attribute as None How do I create the column mentioned to use later while iterating the objects?