Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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? -
How to sort queryset by another table's record count in Django
I have a Product table and order table the Product table record product info,and the Order table record customer's purchases records Now I want to get the products queryset and sort by the store with the most purchases in a customer's order history Product Model id product_name store_id store_name price ..... 1 iPhone 14 1 Amazon 100 ..... 2 iPhone 14 2 Shopee 1 ..... 3 iPhone 12 3 Taobao 100 ..... 4 iPhone 13 1 Amazon 80 ..... 5 iPhone 14 3 Taobao 100 ..... Order Model id product_id customer_id customer_name 1 1 1 Mike 2 2 1 Mike 3 4 1 Mike 4 1 2 Jhon 5 3 3 Simon in my case,I want to get the product's queryset and sort by the store with the most purchases in a customer's order history For example: when customer_id is 1(Mike),the product queryset should be like below because Mike have spent the most times on Amazon, so the ordering of products should put Amazon's products first id product_name store_id store_name price ..... 1 iPhone 14 1 Amazon 100 ..... 4 iPhone 13 1 Amazon 80 ..... 2 iPhone 14 2 Shopee 1 ..... 3 iPhone 12 3 Taobao 100 ..... … -
How to get logged in user ID and pass to backend or set via backend. Djano, DRF, Vue.js, Djoser
So when a user submits a form via frontend (Vue.js), I want to be able to set the created_by attribute in the backend. What is the best way of achieving this? Views class ProjectView(generics.RetrieveAPIView): queryset = Project.objects.order_by('-created_at') def get(self, request): queryset = self.get_queryset() serializer = ProjectsSerializer(queryset, many=True) return Response(serializer.data) def post(self, request): if request.method == 'POST': serializer = ProjectsSerializer if serializer.is_valid(): serializer.save() return JsonResponse(serializer.data, status=201) return JsonResponse(serializer.errors, status=400) Serializer class ProjectsSerializer(serializers.ModelSerializer): interest_category = serializers.StringRelatedField() class Meta: model = Project fields = ( 'project_title', 'project_description', 'interest_category', 'created_by', 'created_at', 'updated_at', ) The data I am passing from Frontend project_title: this.project_title, project_description: this.project_description, interest_category: this.interest_category, I do have a token saved in localStorage, but I do not know how to get the ID of the currently logged in user id and pass to backend or set in backend. Any and all help is greatly appreciated! What is the best way of setting created_by the submitting/requesting user in the backend? -
Building a custom canonical url in python
I want to build a canonical url for my website: my.com here are the requirements: always include www subdomain always use https protocol remove default 80 and 443 ports remove trailing slash Example: http://my.com => https://www.my.com http://my.com/ => https://www.my.com https://my.com:80/ => https://www.my.com https://sub.my.com/ => https://sub.my.com https://sub.my.com?term=t1 => https://sub.my.com?term=t1 This is what I have tried: from urllib.parse import urlparse, urljoin def build_canonical_url(request): absolute = request.build_absolute_uri(request.path) parsed = urlparse(absolute) parsed.scheme == 'https' if parsed.hostname.startswith('my.com'): parsed.hostname == 'www.my.com' if parsed.port == 80 or parsed.port == 443: parsed.port == None # how to join this url components? # canonical = join parsed.scheme, parsed.hostname, parsed.port and parsed.query But I don't know how to join these url components? -
How to set user that submits on frontend to DRF API
So when a user submits a form via frontend (Vue.js), I want to be able to set the created_by attribute in the backend. What is the best way of achieving this? Views class ProjectView(generics.RetrieveAPIView): queryset = Project.objects.order_by('-created_at') def get(self, request): queryset = self.get_queryset() serializer = ProjectsSerializer(queryset, many=True) return Response(serializer.data) def post(self, request): if request.method == 'POST': serializer = ProjectsSerializer if serializer.is_valid(): serializer.save() return JsonResponse(serializer.data, status=201) return JsonResponse(serializer.errors, status=400) Serializer class ProjectsSerializer(serializers.ModelSerializer): interest_category = serializers.StringRelatedField() class Meta: model = Project fields = ( 'project_title', 'project_description', 'interest_category', 'created_by', 'created_at', 'updated_at', ) The data I am passing from Frontend project_title: this.project_title, project_description: this.project_description, interest_category: this.interest_category, What is the best way of setting created_by the submitting/requesting user in the backend? -
Password reset confirm page not loading
I am building the reset password page, the first page where the users enter his email work fine, he receive the reset password email with success. The problem it with the page where the user actually write his new password. When I click on the link / go to the page it give me this error: assert uidb64 is not None and token is not None # checked by URLconf I am following this docs here: https://docs.djangoproject.com/en/1.8/_modules/django/contrib/auth/views/ here is my views.py @sensitive_post_parameters() @never_cache def password_reset_confirm(request, uidb64=None, token=None, template_name='users/password_reset_confirm.html', token_generator=default_token_generator, set_password_form=SetPasswordForm, post_reset_redirect=None, current_app=None, extra_context=None): """ View that checks the hash in a password reset link and presents a form for entering a new password. """ UserModel = get_user_model() assert uidb64 is not None and token is not None # checked by URLconf if post_reset_redirect is None: post_reset_redirect = reverse('password_reset_complete') else: post_reset_redirect = resolve_url(post_reset_redirect) try: # urlsafe_base64_decode() decodes to bytestring on Python 3 uid = force_text(urlsafe_base64_decode(uidb64)) user = UserModel._default_manager.get(pk=uid) except (TypeError, ValueError, OverflowError, UserModel.DoesNotExist): user = None if user is not None and token_generator.check_token(user, token): validlink = True title = ('Enter new password') if request.method == 'POST': form = set_password_form(user, request.POST) if form.is_valid(): form.save() return HttpResponseRedirect(post_reset_redirect) else: form = set_password_form(user) else: validlink … -
Select2 on explicit through model in Django admin
Using autocomplete_fields/search_fields in Django's admin works well to cause a Select2 widget to be used for a ForeignKey field, but I'm getting an error when I set things up to have Select2 widgets rendered on a declared through model in a ManyToManyField relationship. My models are different than the following, but using the example from the Django docs where through models in the admin are discussed as a starting point, I have things set up something like this (the example in the docs has an implicit through model, but I have an explicitly declared through model): class Person(models.Model): first_name = models.CharField(max_length=128) last_name = models.CharField(max_length=128) class Group(models.Model): name = models.CharField(max_length=128) members = models.ManyToManyField(Person, through='Membership', related_name='groups') class Membership(models.Model): person = models.ForeignKey('Person', ...) group = models.ForeignKey('Group', ...) and in admin.py: class PersonAdmin(admin.ModelAdmin): inlines = [MembershipInline,] search_fields = ('first_name','last_name,) class MembershipInline(admin.TabularInline): model = Membership autocomplete_fields = ('person',) class GroupAdmin(admin.ModelAdmin): inlines = [MembershipInline,] When I go to the GroupAdmin and try to create a membership, the Select2 widget is rendered, but when I try to look up a person, I get this error: Forbidden (Permission denied): /admin/autocomplete/ Traceback (most recent call last): File "/virtualenvs/my_virtualenv/lib/python3.8/site-packages/django/utils/datastructures.py", line 84, in __getitem__ list_ = super().__getitem__(key) KeyError: 'app_label' During handling …