Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
authorize user using JWT and axios
settings.py from datetime import timedelta from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/4.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'django-insecure-siq5r5k3*sg#858b4w8$i*6c-ubf*zkpjj1wb&chn4v$%t!ve+' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'corsheaders', 'rest_framework', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'dlt.urls' REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework_simplejwt.authentication.JWTAuthentication', ], } SIMPLE_JWT = { 'ACCESS_TOKEN_LIFETIME': timedelta(minutes=10), 'REFRESH_TOKEN_LIFETIME': timedelta(days=1), 'ROTATE_REFRESH_TOKENS': True, 'BLACKLIST_AFTER_ROTATION': True } CORS_ALLOW_ALL_ORIGINS = True CORS_ORIGIN_WHITELIST = [ 'http://localhost:3000', ] TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'dlt.wsgi.application' # Database # https://docs.djangoproject.com/en/4.1/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', } } # Password validation # https://docs.djangoproject.com/en/4.1/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/4.1/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' … -
Filtering object if it is referenced in another object with many to many relation in Serializer
I am trying to pull a list of all Rooms here where Tenant is equal to the Tenant that is pulled from context data and where the Roomss is a part of the Unit. This is a manytomanyrelationship. Then it should serialize and output the fields for all. This then goes down to Bed as well. The filter for tenant is working but the other filter is not. MODELS.PY class Bed(models.Model): bed_id = models.AutoField(primary_key=True) bed_name = models.CharField(max_length=200) description = models.CharField(max_length=200) tenant = models.ForeignKey(Tenant, on_delete=models.CASCADE,null=True,related_name='bedtenant',blank=False) def __str__(self): return self.bed_name class Room(models.Model): room_id = models.AutoField(primary_key=True) room_name = models.CharField(max_length=200) description = models.CharField(max_length=200) beds = models.ManyToManyField(Bed,blank=True,null=True) tenant = models.ForeignKey(Tenant, on_delete=models.CASCADE,null=True,related_name='roomtenant',blank=False) def __str__(self): return self.room_name class Unit(models.Model): unit_id = models.AutoField(primary_key=True) unit_name = models.CharField(max_length=200) description = models.CharField(max_length=200) rooms = models.ManyToManyField(Room,blank = True,null=True) tenant = models.ForeignKey(Tenant, on_delete=models.CASCADE,null=True,related_name='unittenant',blank=False) def __str__(self): return self.unit_name Serializers.py class RoomSerializer(serializers.ModelSerializer): beds = serializers.SerializerMethodField('get_beds') def get_beds(self, obj): serializer_context = {'request': self.context.get('request') } user_tenant = self.context.get('request').user.tenant bed_instances = Bed.objects.filter(room__isnull=False,tenant=user_tenant) serializer = BedSerializer(bed_instances, many=True,context=serializer_context) return serializer.data class Meta: model = Room fields = ['room_id','room_name','description','beds'] class BedSerializer(serializers.ModelSerializer): class Meta: model = Bed fields = ['bed_id','bed_name','description'] class UnitSerializer(serializers.ModelSerializer): rooms = serializers.SerializerMethodField('get_rooms') def get_rooms(self, obj): serializer_context = {'request': self.context.get('request') } user_tenant = self.context.get('request').user.tenant room_instances = Room.objects.filter(unit__isnull=False,tenant=user_tenant) serializer = RoomSerializer(room_instances, … -
cannot access my Django application from /api
I have deployed my django Api on kubernetes on my localmachine, windows laptop. I did setup kubernetes deployment, LoadBalancer service and ingress file also. But When i try to access the api using path http://localhost/api/my-api-endpoint it does not work and throws an error server not found. While i can successfully connect using just https://locahost/my-api-endpoint Below is my Service file and Docker file: # START Service apiVersion: v1 kind: Service metadata: name: peopledb-api-service labels: app: peopledb-api-service spec: type: LoadBalancer ports: - port: 80 #port that the service exposes targetPort: 8000 #port that the app is receiving requests from via the pod selector: name: peopledb-api-deployment # END SERVICE --- apiVersion: networking.k8s.io/v1 kind: Ingress metadata: name: django-api-ingress annotations: nginx.ingress.kubernetes.io/rewrite-target: / spec: ingressClassName: nginx rules: - host: localhost - http: paths: - path: /api pathType: Prefix backend: service: name: peopledb-api-service port: number: 80 Docker File: FROM python:3.9.7-slim ENV PYTHONUNBUFFERED=1 WORKDIR /api COPY requirements.txt /api/ RUN pip install -r requirements.txt COPY . /api/ EXPOSE 8000 CMD ["python", "manage.py", "runserver", "0.0.0.0:8000"] please note that I have not included any custom nginx config files or I also did not specify any base URL in my Django app settings. what am I doing wrong? do I need to … -
Arduino + Django REST API + Cloud Run = HTTP 302 + No response
I am exploring the wonderful world of IOT, just started. I wanted to start simple: Arduino Rev2 Wifi, combined with couple of sensors (humidity, temp etc) Django REST API, to push mentioned data, deployed on Cloud Run (MySQL is somewhere else) Some kinda of BI e.g. Looker on gcp etc. I assume that this may not be the go-to architecture but i tried nevertheless :) Django works fine This is the view.py from django.http import HttpResponse from django.views.decorators.csrf import csrf_exempt from server.models import Reading, Sensor @csrf_exempt def index(request): if request.method == 'GET': return HttpResponse(False) elif request.method == 'POST': print(request) temperature = request.POST.get("temperature") humidity = request.POST.get("humidity") heatIndex = request.POST.get("heatIndex") sensorId = request.POST.get("sensorId") print(sensorId, temperature, humidity, heatIndex) currentSensor = Sensor.objects.get(pk=sensorId) new_reading = Reading.objects.create( temperature=temperature, humidity=humidity, heatIndex=heatIndex, sensor=currentSensor ) return HttpResponse(True) else: return HttpResponse(False) I can easly push data via Postman and check either via admin panel or MySql workbench that those data were correctly saved. With Arduino is not that simple. #include "DHT.h" #include "WiFiNINA.h" #include "arduino_secrets.h" #include "SPI.h" #define DHTTYPE DHT11 #define DHTPIN 12 DHT dht(DHTPIN, DHTTYPE); float val; int redPin = 2; int greenPin = 7; char ssid[] = SECRET_WIFINAME; char pass[] = SECRET_WIFIPASS; char serv[] = SECRET_SERVER; int status … -
Django filtered queryset doesn't update
Following this tutorial, I'm trying to implement a facet filter based navigation: (starting at 7'05). The facet shows up with the expected materiau__nom and count, but the queryset doesn't update when I click on the filter categories. Is there any visible error in the code? models.py class ObjetArchi(models.Model): id = models.AutoField( primary_key=True, ) materiau = models.ForeignKey( 'Materiau', on_delete=models.SET_NULL, related_name='objets_archi', blank=True, null=True ) class Materiau(models.Model); id = models.AutoField( primary_key=True ) nom = models.CharField( max_length=125, blank=True, null=True ) views.py class NoticesListView(ListView): model = ObjetArchi template_name = 'notices/index.html' context_object_name = 'liste_notices' paginate_by = 20 def get_queryset(self): qs = super().get_queryset() materiau = self.request.GET.get('materiau__nom') if materiau: qs = qs.filter(type=materiau) return qs def get_context_data(self, **kws): context = super().get_context_data(**kws) context['materiaux'] = ( self.get_queryset() .values('materiau__nom') .annotate(count=Count('id')) ) return context urls.py urlpatterns = [ path('', views.NoticesListView.as_view(), name='notices_list'), ] notices/index.html {% for materiau in materiaux %} <ul> <a href="?materiau={{ materiau.materiau__nom }}"> {{ materiau.materiau__nom }} ({{ materiau.count }}) </ul> {% endfor %} {% if liste_notices %} <ul> {% for notice in liste_notices %} <li><a href="{% url 'notices:detail' notice.id %}">{{ notice.titre }}</a></li> {% endfor %} </ul> {% else %} <p>Aucune notice n'est accessible.</p> {% endif %} -
django formset with initial data is not showing the Files
So im using a django formset to show multiple instances of a model and i have a file field in this model. the problem is when i add a file and save it, it's not being shown in frontend part. this is the form: class ProductForm(forms.ModelForm): class Meta: model = Product fields = ( "name", "description", "related_file" ) widgets = { 'description': forms.Textarea(attrs={'rows':4, 'cols':10}), } the formset: ProductFormSet = formset_factory(ProductForm) and view: class ProductView(LoginRequiredMixin, TemplateView): template_name = 'pages/account/products.html' success_url = reverse_lazy('account:products') page_name = 'products' page_title = _('Products') crumb = _('Products') def render_to_response(self, context: Dict[str, Any], **response_kwargs: Any): formset = ProductFormSet( initial=self.request.user.company.products.all().values()) context['formset'] = formset return super().render_to_response(context, **response_kwargs) to test i used these tags in my html file: {{formset.0.initial}} {{formset}} and this is the result: as you can see the initial data is there, and also filled other inputs correctly, but it did not fill the filefield data. -
How to move items between lists in Django
Beginner and fairly new to Django here, I have two Django models and I would like to move an item(s) from one to the other. I am using lists to store the items, but for some reason I can't quite figure out why when I try to remove the item from one and move it into the other it is remaining in the previous list. Here is my code: views.py def profile(request): playinglist = Playinglist.objects.filter(user=request.user.username) playinglist_items = [] playing = 0 present_in_playinglist = False if playinglist: for item in playinglist: try: game = Game.objects.get(id=item.game_id) playinglist_items.append(game) present_in_playinglist = True playing += 1 print(playinglist_items) except: present_in_playinglist = False playedlist = Playedlist.objects.filter(user=request.user.username) playedlist_items = [] finished = 0 present_in_playedlist = False if playedlist: for item in playedlist: try: game = Game.objects.get(id=item.game_id) playedlist_items.append(game) present_in_playedlist = True finished += 1 playing -= 1 playinglist_items.remove(game) except: present_in_playedlist = False models.py class Game(models.Model): title = models.CharField(max_length=200) description = models.TextField(blank=True, null=True, max_length=500) image = models.URLField(blank=True, null=True, max_length=500) genre = models.CharField(blank=True, null=True, max_length=200) platform = models.CharField(blank=True, null=True, max_length=200) developer = models.CharField(blank=True, null=True, max_length=200) publisher = models.CharField(blank=True, null=True, max_length=200) added_by = models.CharField(max_length=64) def __str__(self): return f"ID# { self.id }: { self.title }" class Playinglist(models.Model): title = models.CharField(max_length=200) user = models.CharField(max_length=64) … -
Slug Error / No Reverse URL for manually uploaded data
I have a slug defined in my model as follows: slug = models.SlugField(blank=True, null=True) def save(self, *args, **kwargs): if self.slug is None: self.slug = slugify(self.name + "-" + self.city + "-" + self.state) super().save(*args, **kwargs)``` The issue I'm having is when I bulk upload to the database via CSV I have to manually go in and re-save each business for the slug to save/populate. I would like to be able to simply upload the csv with the slug pre-populated (slug field with formatting is already in the csv). Can I format the slug manually or does this need to be done via the save method in the models.py file? -
Wagtall - template class for blocks StreamField
I have a Strucktblock: # blocks.py class GameBlock(StructBlock): logo = ImageChooserBlock(required=True) image = ImageChooserBlock(required=True) heading = CharBlock(required=True, max_length=50) description = CharBlock(required=True, max_length=100) url_button = URLBlock(required=True) class Meta: icon = "form" template = "blocks/game_card.html" How can I wrap one or more blocks in a template into its own class? For example: <div class="row-grid"> <div class="card">Card1</div> <div class="card">Card2</div> </div> I tried a template: {% for block in page.body %} {% if block.block_type == 'game' %} <div class="row-grid">{% include_block block %}</div> {% else %} {% include_block block %} {% endfor %} And I did: <div class="row-grid"><div class="card">Card1</div></div> <div class="row-grid"><div class="card">Card2</div></div> -
How can I solve django.db.utils.OperationalError when I try to migrate data when I run my docker compose up command?
I am currently working on a project to deploy a django app using docker compose but I keep getting a django.db.utils.OperationalError when I try to migrate data when I run the docker compose up command. This is the full error I am getting; => ERROR [6/7] RUN python3 manage.py makemigrate --settings=core.settings.production 4.5s ------ > [6/7] RUN python3 manage.py makemigrate --settings=core.settings.production: #0 3.964 /usr/local/lib/python3.10/site-packages/django/core/management/commands/makemigrations.py:158: RuntimeWarning: Got an error checking a consistent migration history performed for database connection 'default': could not translate host name "postgres" to address: Name or service not known #0 3.964 #0 3.964 warnings.warn( #0 3.985 No changes detected in app 'tags' #0 4.016 No changes detected in app 'users' #0 4.050 No changes detected in app 'content' #0 4.081 No changes detected in app 'actions' #0 4.102 Traceback (most recent call last): #0 4.102 File "/usr/local/lib/python3.10/site-packages/django/db/backends/base/base.py", line 289, in ensure_connection #0 4.104 self.connect() #0 4.104 File "/usr/local/lib/python3.10/site-packages/django/utils/asyncio.py", line 26, in inner #0 4.105 return func(*args, **kwargs) #0 4.105 File "/usr/local/lib/python3.10/site-packages/django/db/backends/base/base.py", line 270, in connect #0 4.106 self.connection = self.get_new_connection(conn_params) #0 4.106 File "/usr/local/lib/python3.10/site-packages/django/utils/asyncio.py", line 26, in inner #0 4.107 return func(*args, **kwargs) #0 4.107 File "/usr/local/lib/python3.10/site-packages/django/db/backends/postgresql/base.py", line 269, in get_new_connection #0 4.108 connection = self.Database.connect(**conn_params) #0 4.108 File … -
Django. Detail.html page returns all posts from list.html on a single page
I'm trying to create a blog with a title and description form and a photo created inline in the admin admin StackedInline. So far, everything has worked, including the list.html page with the list of posts, but the detail.html page returns all posts on a single page. How to solve it? the page includes comment, I didn't find anything similar on the internet. Models.py from django.db import models from django.contrib.auth.models import User from django.urls import reverse from django.utils import timezone from taggit.managers import TaggableManager from django.utils.html import mark_safe class PublishedManager(models.Manager): def get_queryset(self): return super().get_queryset().filter(status='published') class Post(models.Model): STATUS = ( (0,"Draft"), (1,"Publish") ) user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='blog_posts') title = models.CharField(max_length=200) slug = models.SlugField(max_length=250, unique_for_date='publish') publish = models.DateTimeField(default=timezone.now) description = models.TextField() image = models.ImageField(upload_to ='uploads/') status = models.IntegerField(choices=STATUS, default=0) objects = models.Manager() # The default manager. published = PublishedManager() # Our custom manager. #tags = TaggableManager(blank=True) def img_preview(self): #new return mark_safe(f'<img src = "{self.image.url}" width = "300"/>') def __str__(self): return self.title class Travel(models.Model): travel = models.ForeignKey(Post, on_delete=models.CASCADE, verbose_name="travel-post") title = models.CharField(max_length=200) description = models.TextField() image = models.ImageField(upload_to ='uploads/') created = models.DateTimeField(auto_now_add=True) objects = models.Manager() # The default manager. class Comment(models.Model): STATUS = ( ('Lido', 'Lido'), ('Não Lido', 'Não Lido'), ) post … -
Axios authorization is not working correctly
settings.py """ Django settings for dlt project. Generated by 'django-admin startproject' using Django 4.1.5. For more information on this file, see https://docs.djangoproject.com/en/4.1/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/4.1/ref/settings/ """ from datetime import timedelta from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/4.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'django-insecure-siq5r5k3*sg#858b4w8$i*6c-ubf*zkpjj1wb&chn4v$%t!ve+' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'corsheaders', 'rest_framework', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'dlt.urls' REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework_simplejwt.authentication.JWTAuthentication', ], } SIMPLE_JWT = { 'ACCESS_TOKEN_LIFETIME': timedelta(minutes=10), 'REFRESH_TOKEN_LIFETIME': timedelta(days=1), 'ROTATE_REFRESH_TOKENS': True, 'BLACKLIST_AFTER_ROTATION': True } CORS_ALLOW_ALL_ORIGINS = True CORS_ORIGIN_WHITELIST = [ 'http://localhost:3000', ] TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'dlt.wsgi.application' # Database # https://docs.djangoproject.com/en/4.1/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', } } # Password … -
CheckBoxSelectMultiple values not saving to Django database
I have a django form with a CheckBoxSelectMultiple field, linked to the 'opening_days' field in my BookingManagement model. This renders in my template, and the form submits after checking some of the checkbox options, for example: However, when I check the model instance in the database, the 'opening_days' field is "NULL" for this model instance, rather than a string of the days I selected. Have researched lots but cannot find where I am going wrong. My models.py (I've excluded fields not relevant to this problem from this snippet): class DaysOfWeek(models.Model): day = models.CharField(max_length=13) def __str__(self): return str(self.day) class BookingManagement(models.Model): listing = models.ForeignKey(Listing, verbose_name="Listing", on_delete=models.CASCADE) opening_time = models.TimeField(verbose_name="Opening Time", blank=False) closing_time = models.TimeField(verbose_name="Closing Time", blank=False) opening_days = models.ManyToManyField(DaysOfWeek, null=True, blank=True, verbose_name="Opening Days") My forms.py: class BookingManagementForm(forms.ModelForm): """ A form to complete all information in relation to booking management. """ opening_days = forms.ModelMultipleChoiceField(queryset=DaysOfWeek.objects.all(), to_field_name="day", widget=forms.CheckboxSelectMultiple(attrs={'name': 'opening_days', 'id': 'opening_days'})) class Meta: model = BookingManagement fields = ['opening_time', 'closing_time', 'opening_days', 'booking_slots_per_day', 'max_bookings_per_time_slot', 'standard_booking_duration', 'min_booking_duration', 'max_booking_duration', 'booking_duration_increment', 'min_people_per_booking', 'max_people_per_booking', 'turnaround_time', 'time_slot_frequency', 'max_people_per_time_slot', 'max_people_per_day', 'min_adults_per_booking', 'max_children_per_adult', 'min_age', 'max_age', 'child_max_age'] My views.py: class BookingManagementView(NextUrlMixin, View): form_class = BookingManagementForm template_name = 'listings/createlistingbookingmanagement.html' default_next = '/' def get(self, request, *args, **kwargs): form = self.form_class() context = { 'form': form … -
Testing Django Allauth Locally with NGINX
Is it possible to test django allauth locally with nginx? My local environment 'requires' nginx + gunicorn since I am doing more than the local dev server can handle. Practically what this means is that nginx is listening on localhost:8080 and django-gunicorn on localhost:8000. nginx proxy_passes up to 8000. This creates a 'funny' situation from Google's perspective as I try to login with google, specifically with the redirect_uri. I initiate a request as a user from localhost:8080 but my application server makes the request from localhost:8000. Google requires that the callback uri come from the same host as the request. I am unable to set a redirect uri of localhost:8080, which is what i want. gunicorn doesn't load static assets, which is what nginx is doing. if i cannot redirect to 8080 instead of 8000 i get my site with zero css. I am able to login in via google if i make the request from localhost:8000 but it's a bad experience since no static content loads. this makes it hard to really test what the experience will be like. That 'works' sort of - but begs the larger question: Is gunicorn + nginx fundamentally incompatible with django-allauth for local … -
Django: Cannot get distinct objects when using order_by method after distinct
I want to order objects in queryset after I check if there exists foreign relation. After I tried to select disctinct values and then order them, number of items does not match initial distinct values. Here is the functional view import datetime from business.models import Business from deals.models import Deal from directory.forms import FilterDirectoryForm from django.db.models import Q from django.shortcuts import render def directory_filter(request): directories = Business.objects.all().order_by("company_name") deals = Deal.objects.all() if request.method == "POST": form = FilterDirectoryForm(request.POST) if form.is_valid(): keywords = form.cleaned_data.get("keywords", "") keywords = keywords.split(",") categories = form.cleaned_data.get("categories", "") membership_age = form.cleaned_data.get("membership_age", "") has_deal = form.cleaned_data.get("has_deal", "") sort_by = form.cleaned_data.get("sort_by", "") order_by = form.cleaned_data.get("order_by", None) directories_q_object = Q(company_name__icontains=keywords[0]) | Q( about__icontains=keywords[0] ) if len(keywords) > 1: for item in keywords[1:]: directories_q_object.add( (Q(company_name__icontains=item) | Q(about__icontains=item)), directories_q_object.connector, ) directories = directories.filter(directories_q_object) if categories: directories_categories_q_object = ( Q(business_category__primary_category=categories[0]) | Q(business_category__additinal_category_1=categories[0]) | Q(business_category__additinal_category_2=categories[0]) | Q(business_category__additinal_category_3=categories[0]) ) if len(categories) > 1: for item in keywords[1:]: directories_categories_q_object.add( ( Q(business_category__primary_category=item) | Q(business_category__additinal_category_1=item) | Q(business_category__additinal_category_2=item) | Q(business_category__additinal_category_3=item) ), directories_categories_q_object.connector, ) directories = directories.filter(directories_categories_q_object) if membership_age != "all": if membership_age == "new_members": directories = directories.filter( created_at__gt=datetime.datetime.today() - datetime.timedelta(days=30) ) else: directories = directories.filter( created_at__lt=datetime.datetime.today() - datetime.timedelta(days=30) ) if has_deal != "all": if has_deal == "yes": directories = directories.filter( … -
Django: write something to the database in a catch block, when using an atomic transaction
I have a Django REST Framework serializer which uses select_for_update in combination with atomic transitions, like this: https://docs.djangoproject.com/en/4.2/ref/models/querysets/#select-for-update/. That works fine, except that I want to write something to the database when an error is thrown... and these insert statements are getting rolled back, never making it to the database. The code is something like this: class MySerializer(Serializer): # Some serializer fields here.. @transaction.atomic def save(self): foo = Foo.objects.all().select_for_update() try: SomeExternalSDK.doStuff() except SomeExternalSDK.SomeException as e: log = Log(message="Uh oh") log.save() raise ValidationError("Something went wrong") The problem I am facing is that when the external SDK triggers an error and I'm trying to write something to the database, that this never ends up in the database, the transaction is just rolled back. How can I make sure that I can still write something to the database when using atomic transactions, in the except block? -
Pass the username of logged user into django avatar tags
I have to build a column of datatable dynamically. In this column i want to put the user's avatar. So i used createdCell function to do this: { 'targets': [4], 'createdCell': function (td, cellData, rowData, row, col) { var username = rowData['username'] $(td).html( '<div class="d-flex">' + '<div class=" text-secondary bradius me-3">' + '{% avatar "'+username+'" class="avatar profile-user brround cover-image" %}' + '</div>' + '<div class="">' + '<h6 class="mb-1 fw-semibold">' + username + '</h6>' + '<p class="fw-normal fs-12"><span class="text-muted">' + rowData['data_ultimo_aggiornamento'] + '</span></p>' + '</div>' + '</div>'); }, }, My problem is that I can't pass the javascript variable "username" into django avatar tags because it returns me always "/static/avatar/img/default.jpg" (default image url) even if the user has a personal avatar. I tried also with a replace like that: '{% avatar 1234 class="avatar profile-user brround cover-image" %}'.replace('1234',username), but the error is that the username paramater mustnt' be a digit. With a string instead '1234' it returns me the default image. -
Call parent model field m2m relationship field from child
I am trying to call the list of M2M object referenced in ModelB from ModelC. I normally use it the other way around (start with parent model and filter down to child), but this time I cant see a way around it. I feel there might be something to do with the related name, but the behaviour seems different than with normal FK. Any ideas? models.py class ModelA(models.Model): title = models.CharField(verbose_name="title",max_length=100, null=True, blank=True) class ModelB(models.Model): ModelB_Field1= models.ManyToManyField(ModelA, blank=True) class ModelC(models.Model): ModelC_Field1= models.ForeignKey(ModelB,null=True, blank=True, on_delete=models.SET_NULL, related_name='modelc_field1') views.py def function(request, modelc_id): q = ModelC.objects.filter(pk=modelc_id) -
How to correctly filter a QuerySet based on a form MultipleChoice field?
This is how I have defined my form: class TaskFilterForm(forms.Form): status = forms.MultipleChoiceField( required=False, widget=forms.CheckboxSelectMultiple, choices=PLAN_STATUS, ) And I'm trying to get my QuerySet filtered like this: class MyTasksView(generic.ListView): template_name = 'my-tasks.html' context_object_name = 'tasks' object_list = Task.objects.all() def get_context_data(self, **kwargs): # Call the base implementation first to get a context context = super().get_context_data(**kwargs) # Add in a QuerySet of all the books context['filter_form'] = TaskFilterForm(self.request.GET) return context def get_queryset(self, **kwargs): print(self.request.GET) qs = Task.objects.filter(assignee=self.request.user) status = self.request.GET.get('status') if status: qs = qs.filter(status__in=status) return qs def post(self, request, *args, **kwargs): context = super().get_context_data(**kwargs) context['filter_form'] = TaskFilterForm(self.request.POST) print('MyTaskView.request.POST', self.request.POST) return render(request, self.template_name, context) It is correctly filtering just for an item, but I'd like it to filter, say, including status 0 and 1, when both are selected. How should I correct this? -
call a function in export django
i have this in my models.py of Requests @property def calculate_pd_days(self): from reports.models import PdReport pd_report = ( PdReport.objects.filter( request=self, maturity_date__lte=datetime.date.today() ) .exclude(status=PdReport.Status.SUCCESS) .last() ) if pd_report: pd_days = (datetime.date.today() - pd_report.maturity_date).days self.pd_days = pd_days return pd_days return 0 here is the export which I have in my views.py of reports def export_report_csv(request): print("Downloading reports") query_kwargs = {} reports = DataReportExcel.objects.annotate( full_name=Concat( "request__customer__first_name", Value(" "), "request__customer__last_name" ), broker_full_name=Concat( "request__broker__first_name", Value(" "), "request__broker__last_name" ), team_leader_full_name=Concat( "request__team_leader__first_name", Value(" "), "request__team_leader__last_name", ), ).filter(**query_kwargs) if request.user.role == "Team Leader": reporting_brokers = InternalUser.objects.filter( reporting_to=request.user.internaluser.pk ) reports = reports.filter( Q(request__broker__in=reporting_brokers) | Q(request__broker=request.user) | Q(request__successior_broker=request.user.internaluser) ) response = HttpResponse(content_type="text/csv") response["Content-Disposition"] = 'attachment; filename="DataReport.csv"' writer = csv.writer(response) writer.writerow( [ "Pd Days", ] ) datas = reports.values_list( "request__pd_days", ) for i in datas: report_list = list(i) report_list[6] = report_list[6] + "'" if report_list[6] is not None else "" writer.writerow(report_list) return response Now on export, I do not need to call this anymore request_pd_days, but I need to call the value that comes from the function calculate_pd_days in models.py of Requestz How can I achieve that (tried with request__calculate_pd_days) but it says that cannot resolve keyword 'calculate_pd_days' into field. -
Problem login after hosting Django in a domain
please I have a problem authenticate after hosting my app Django in Cpanel When I'm use the correct login the url make this chaine "https://www.example.com/manageStock/login/?next=/manageStock/home/" after redirection in the same page. Can I help me please to resolve this issue. I'm using Python 3.7.16 and Django 3.2.18. Setting.py: """ Django settings for eCommerce_website_python project. Generated by 'django-admin startproject' using Django 4.0.4. For more information on this file, see https://docs.djangoproject.com/en/4.0/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/4.0/ref/settings/ """ import os from pathlib import Path CSRF_TRUSTED_ORIGINS = [ 'https://example.com:8000' ] # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/4.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'django-insecure-ww(0ivm)v$msei=k$^mh16^&85le=g%ij^mz96pk)m-+o2dob3' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ['example.com','www.example.com'] # Application definition INSTALLED_APPS = [ 'manageStock.apps.ManagestockConfig', # 'livereload', # 'django_browser_reload', 'widget_tweaks', 'mathfilters', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', # "django_browser_reload.middleware.BrowserReloadMiddleware", # "livereload.middleware.LiveReloadScript", 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', # 'manageStock.middleware.AuthMiddleware', ] SESSION_ENGINE = 'django.contrib.sessions.backends.cache' SESSION_EXPIRE_AT_BROWSER_CLOSE = True TEMPLATE_DIR = os.path.join(BASE_DIR, 'templates') ROOT_URLCONF = 'eCommerce_website_python.urls' TEMPLATES = … -
How to override createsuperuser command in django
I'm trying to customize the createsuperuser command. The purpose of this is: I've a table called administrator, and its have OneToOne relationship with auth_user table class Administrator(models.Model): user = models.OneToOneField(get_user_model(), on_delete=models.CASCADE, related_name="admin") And whenever I create new super user by using command createsuperuser, i'd like to create a record in table administrator as well. But I'm not sure how to do this yet. Please help, thanks. Here's my repo: https://github.com/ncson1/regov-pop-quiz-backend-s-v1/blob/main/auth_custom/commands/createsuperuser.py -
Django Admin all users's permissions
Groups: Users: In django admin I can only see user's permissions, but I want to see all user permissions, including group permissions. So in the right column it would display all permission of selected user. I can get list of all permissions via user.get_all_pemissions, but I can not display it there. Only thing that i succeded with is to display them like this: I understand that i can not remove group permission from user, but at least I want to display them more prettier. -
Nested Serializer for prefect_related in Django Rest Framework
I'm trying to make a nested serializer with prefect_related but it doesn't work, here's my code: models.py from django.db import models class Student(models.Model): phone = models.IntegerField(null=True) birth_date = models.DateField(null=True) user = models.OneToOneField(get_user_model(), on_delete=models.CASCADE, related_name="student") class Course(models.Model): title = models.CharField(max_length=100, blank=True, default='') class CourseEnroll(models.Model): course = models.ForeignKey(Course, on_delete=models.PROTECT, related_name='course_enroll') student = models.ForeignKey(Student, on_delete=models.PROTECT, related_name='student_enroll') views.py from rest_framework import mixins from rest_framework.viewsets import GenericViewSet from quiz.models import Course from quiz.serializers import CourseSerializer class CourseViewSet(mixins.CreateModelMixin, mixins.ListModelMixin, mixins.RetrieveModelMixin, GenericViewSet): def get_queryset(self): queryset = Course.objects.prefetch_related("course_enroll").all() return queryset serializer_class = CourseSerializer serializers.py from rest_framework import serializers from quiz.models import Course, CourseEnroll class CourseEnrollSerializer(serializers.ModelSerializer): class Meta: model = CourseEnroll fields = ['id'] class CourseSerializer(serializers.ModelSerializer): student_enrolled = CourseEnrollSerializer(many=True, read_only=True) class Meta: model = Course fields = ['id', 'title', 'student_enrolled'] Here's my repo: https://github.com/ncson1/regov-pop-quiz-backend-s-v1/tree/main/quiz Did I do something wrong here? Please help, thanks. -
Can I host a Django CMS everywhere?
Somehow I cannot find the one simple answer if I can host Django CMS at "common" hosting providers. As Django is python I assume this is not possible and I need specific python hosting. Am I correct?