Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Is there a less bloated alternative to GDAL and GeoDjango?
I am writing an API in Django and need to filter posts by a search radius and later on will need live tracking like on Uber. I am wondering if there is an easier way to query for posts and filter them based on a search radius defined by the user and their location. Wondering how a program like AutoTrader would do this. Dealing with the installation process for GDAL is a complete pain for Windows and my docker image. I know there are ways to install a pre-built wheel and blah blah blah but I'm looking for a streamlined approach that is as simple as throwing it into my requirements and won't be a nuisance after each release. -
How to create different sizetables for each type of clothing?
Im making shop on django and cant realize how to solve the problem: I got class Product(class for clothes) and i need to create another class for Sizes of different categories of clothes, for example: Shoes will got - 9US, 10US, 11US... Shirts will got - XS, S, M, L... etc. How can i create that type of class?? My Product class: class Product(models.Model): class ModerationStatuses(models.TextChoices): DRAFT = 'DR', _('черновик') ON_MODERATION = 'MD', _('На модерации') APPROVED = 'AP', _('Одобрено') REJECTED = 'RJ', _('Отклонено') class ConditionStatuses(models.TextChoices): NEW = 'NEW', _('New') USED = 'USD', _('Used') VERY_WORN = 'VW', _('Very worn') NOT_SPECIFIED = 'NS', _('Not specified') title = models.CharField(max_length=100) price = models.DecimalField(max_digits=6, decimal_places=2) quantity = models.IntegerField() city = ... style = models.ForeignKey(Style, related_name='category_products', on_delete=models.CASCADE, null=True, blank=True) category = models.ForeignKey(Category, related_name='style_products', on_delete=models.CASCADE, null=True, blank=True) address = models.CharField(max_length=250) description = models.TextField() brand = models.CharField(max_length=150) published = models.BooleanField(default=False, null=False) modification = models.OneToOneField('self', on_delete=models.CASCADE, null=True, blank=True, help_text='When editing an approved item a modification is created. This ' 'modification is sent for moderation and, after approval, replaces ' 'the original position.') is_modification = models.BooleanField(default=False) moderation_status = models.CharField(choices=ModerationStatuses.choices, default=ModerationStatuses.DRAFT, null=False, max_length= 2) condition = models.CharField(choices=ConditionStatuses.choices, default=ConditionStatuses.NEW, null=False, max_length=3) posted_at = models.DateTimeField(auto_now_add=True) def __str__(self): return self.title I literally cant find … -
Custom MultiInput Model Field in Django
I'm trying to create a custom field for volume made up of 4 parts (length, width, height and units). I'm thinking that extending the models.JSONField class makes the most sense. Here is what I have so far. inventory/models.py from django.db import models from tpt.fields import VolumeField class Measurement(models.Model): volumne = VolumeField() tpt/fields.py from django.db import models from tpt import forms class VolumeField(models.JSONField): description = 'Package volume field in 3 dimensions' def __init__(self, length=None, width=None, height=None, units=None, *args, **kwargs): self.widget_args = { "length": length, "width": width, "height": height, "unit_choices": units, } super(VolumeField, self).__init__(*args, **kwargs) def formfield(self, **kwargs): defaults = {"form_class": forms.VolumeWidgetField} defaults.update(kwargs) defaults.update(self.widget_args) return super(VolumeField, self).formfield(**defaults) tpt/forms.py import json from django import forms class VolumeWidget(forms.widgets.MultiWidget): def __init__(self, attrs=None): widgets = [forms.NumberInput(), forms.NumberInput(), forms.NumberInput(), forms.TextInput()] super(VolumeWidget, self).__init__(widgets, attrs) def decompress(self, value): if value: return json.loads(value) else: return [0, 0, 0, ''] class VolumeWidgetField(forms.fields.MultiValueField): widget = VolumeWidget def __init__(self, *args, **kwargs): list_fields = [forms.fields.CharField(max_length=8), forms.fields.CharField(max_length=8), forms.fields.CharField(max_length=8), forms.fields.CharField(max_length=4)] super(VolumeWidgetField, self).__init__(list_fields, *args, **kwargs) def compress(self, values): return json.dumps(values) I'm able to run the server but when I try and add a new entry to the Measurement Model in Admin I get this error: [13/May/2024 11:57:59] "GET /admin/inventory/measurement/ HTTP/1.1" 200 12250 Internal Server Error: /admin/inventory/measurement/add/ Traceback … -
End of year project using Django, React and MySQL (beginner)
I'm a first year programming student so I apologize for sounding a bit ignorant on this topic, I'm still learning, but I need help. I'm working on making a web app for my end of year project. I'm gonna be using Django for backend, MySQL for storing data, React, html and css for frontend. I have 2 months to make this project so I'm currently speed running learning react and django rn. I am watching tutorials on how to link all these technologies together and it's quite confusing, can someone help and give me a simple explanation or some good resources that I can use please? Also the most important part of my question is where do I start? do I start with frontend or backend? I thought about making the frontend first, creating templates and all, and then linking it to Django and MySQL. I need professional advice though, any help would be much appreciated :) I just got started so I haven't done much. I just made a mockup template for starters, that's it, but I'm gonna start coding after I grasp the conceps I mentioned. I'm familiar with html and css and python(this will mostly help me … -
TestDriven.io: Docker Not Installing Pytest Requirements For Django API course project
I'm on the Django REST Framework portion of the course. Aside from the entrypoint, everything else is working. so I am leaving it as commented out for now. Here is the structure: Here is the Dockerfile: # pull official base image FROM python:3.11.2-slim-buster # set working directory WORKDIR /usr/src/TestDrivenIO # set environment variables ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 # updated # install system dependencies RUN apt-get update \ && apt-get -y install netcat gcc postgresql \ && apt-get clean # install dependencies RUN pip install --upgrade pip COPY requirements.txt . RUN pip install -r requirements.txt # # new # # copy entrypoint.sh # COPY ./entrypoint.sh /usr/src/TestDrivenIO/entrypoint.sh # RUN chmod +x /usr/src/TestDrivenIO/entrypoint.sh # # add app # COPY . . # # new # # run entrypoint.sh # ENTRYPOINT ["/usr/src/TestDrivenIO/entrypoint.sh"] Entrypoint file: #!/bin/sh # continues until "Connection to movies-db port 5432 [tcp/postgresql] succeeded!" returned if [ "$DATABASE" = "postgres" ] then echo "Waiting for postgres..." while ! nc -z $SQL_HOST $SQL_PORT; do sleep 0.1 done echo "PostgreSQL started" fi python manage.py flush --no-input python manage.py migrate exec "$@" Requirements file in the TDD-Django/TestDrivenIO/requirements.txt file: Django==4.1.7 djangorestframework==3.14.0 psycopg2-binary==2.9.5 pytest-django==4.5.2 pytest==7.2.2 Requirements file in the TDD-Django/requirements.txt file (copied from other in case … -
how to get info from image before uploading it to db using django
i have a view that uploads image to db i need to get face_encoding tbefore uploading it to db any ideas how to do that this is my view def index(request): if request.method=='POST': form = ImageForm(request.POST,request.FILES) if form.is_valid(): form.save() return HttpResponse(type(ImageForm)) else: return HttpResponse("error") context={'form':ImageForm()} template=loader.get_template("core/index.html") return HttpResponse(template.render(context,request)) i want to use face_recognition library -
Django: Facing Issues in accessing DB and Instantiating object on app load
I want to load data from db and store it in an object and access that object from anywhere in the Django project. Preferably using the conventional settings.GlobalSettings where settings are the django.conf. I have a function that should run while the app starts. How can I achieve that and is it possible? I have been trying different implementations and getting errors like AttributeError: 'Settings' object has no attribute 'GlobalSettings' django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. I was trying to call that function as a post_migrate signal in the apps.py. also, I was calling the settings class using from django.conf import settings and added my GlobalSettings in it and tried to load but nothing worked. I am fairly new to this, any help would be appreciated. -
Getting error 500 while accepting image from client to server
I have html code that takes image from user as an input and i am trying to send it to server side when i click button process for processing in Django but i am hetting error 500 in console. On server side i want to read that image and allign it and apply ocr on it Code for html is: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Image Processing</title> </head> <body> <h1>Image Processing</h1> <form id="image-upload-form" method="post" enctype="multipart/form-data"> {% csrf_token%} <input type="file" id="image-upload" name="image" accept="image/*"> <button type="submit">Upload Image</button> </form> <div id="result"></div> </body> </html> Code for server side python: # views.py from django.http import JsonResponse from django.views.decorators.csrf import csrf_exempt import numpy as np import cv2 import imutils import pytesseract import base64 pytesseract.pytesseract.tesseract_cmd = r'C:\Program Files\Tesseract-OCR\tesseract.exe' def order_points(pts): rect = np.zeros((4, 2), dtype="float32") s = pts.sum(axis=1) rect[0] = pts[np.argmin(s)] rect[2] = pts[np.argmax(s)] diff = np.diff(pts, axis=1) rect[1] = pts[np.argmin(diff)] rect[3] = pts[np.argmax(diff)] return rect def four_point_transform(image, pts): rect = order_points(pts) (tl, tr, br, bl) = rect maxWidth = max(int(np.sqrt(((br[0] - bl[0]) * 2) + ((br[1] - bl[1]) * 2))), int(np.sqrt(((tr[0] - tl[0]) * 2) + ((tr[1] - tl[1]) * 2)))) maxHeight = max(int(np.sqrt(((tr[0] - br[0]) * 2) + ((tr[1] - br[1]) * 2))), … -
How do I add a new entry to my many to many related table in Django?
I have two models Course and Educators. Course has 3 fields course_name, course_educators and course_past_educators which link Educators to Courses by many to many. I want to write a function so that whenever a new entry is added to course_educators that entry will be copied over to course_past_educators. #models.py #code for Educators model class Educators(models.Model): educator_name=models.CharField(max_length=20,default=None) educator_img = models.ImageField(upload_to='educators_img',default=None) #code for Courses model class Course(models.Model): course_name = models.CharField(max_length=100) course_educators=models.ManyToManyField(Educators, related_name='current_educators', default=None, blank=True) course_past_educators=models.ManyToManyField(Educators, related_name='past_educators', default=None, blank=True) #views.py #This is the function I wrote so that entries into course_past_educators are automatically added when course_educators is added with another entry. @receiver(m2m_changed, sender=Course.course_educators.through) def create_past_educator_on_add(sender, instance, action, reverse, model, pk_set, **kwargs): if action == 'post_add' and reverse is False: currentEducators=instance.course_educators.all() for currentEducator in currentEducators: instance.course_past_educators.add(currentEducator) I use Django admin panel to add the educators yet, educators are not being added to course_past_educators. How do I fix this issue? -
Validation Error Placement for a list editable field
I have enabled list editable on one of my django admin to allow user update the min and max value. I have set a validation in place to make sure that min is not greater than max. The validation works as expected. However, I am not really happy with the way the message is displayed. So currently as seeing in the screenshot, the error message appears right above the field which messes up the alignment of the table. The column with error becomes wider than the others and it's not even highlighted with red. What I am trying to achieve instead is to show the error on the top of the page like Please correct the errors below. Min value cannot be greater than max value .... and simply have the errored field highlighted with red border. what is the best way to achieve this? I tried overriding the is_valid function in my CustomModelForm but I can't add the messages there since I don't have access to the request object. Anything I tried to pass the request object was in vain. class CustomModelForm(forms.ModelForm): class Meta: model = MyModel fields = '__all__' def is_valid(self): if 'min_quantity' in self._errors: # messages.error(self.request, self._errors["min_quantity"]) … -
colorpicker and field validation
I am using TabularInlines to gather some information, one of which is a colorfield: class UnitForm(forms.ModelForm): class Meta: model = Unit fields = ["date", "name", "label", "color"] widgets = {"color": TextInput(attrs={'type': 'color'}),} class UnitTabularInline(admin.TabularInline): form = UnitForm model = Unit extra = 0 ##workaround class StockAdmin(admin.ModelAdmin): list_display = [] inlines = [UnitTabularInline] My problem is, without the extra = 0 switch, I always see 3 "empty" fields (which I actually want to see). But I cannot save my form, if I do not fill out all the fields, because the colorpicker has a preselected value. It seems that when input has type="color" there is always a color defined, and there's no way to set that string to empty. Can I somehow skip form validation for fields, that only have color in self.chagned_data or something like this? I would like the other edits to be saved. The model: class Unit(models.Model): name = models.CharField("name", max_length=128, blank=True, null=True) date = models.DateField() stock = models.ForeignKey(Stock, on_delete=models.CASCADE) label = models.CharField("extra label", max_length=32, null=True, blank=True) color = models.CharField(max_length=7, null=True, blank=True) -
UnicodeEncodeError at api
enter image description here I cannot insert data into this api and because of this 'ascii' codec can't encode characters in position 231-232: ordinal not in range(128) enter image description here I want a solution to fix this issue. I'm using django framework. The same database is working on localhost of my local computer but at server I can't insert data. I've cloned the server database too but it work at local computer but send error at server database. -
What should I do if data is not saved in Django?
I'm new to Django. And I'm faced with the problem of saving data from the form to the database. I was writing code in PyCharm. The main problem is that the data is not saved in the database. There are no errors, no warnings, NOTHING. Everything works except saving. I will be very grateful for your help! Here is the code: views.py: `from django.shortcuts import render, redirect from .models import Articles from .forms import ArticlesForm def news_home(request): news = Articles.objects.order_by('title') return render(request, 'news/news_home.html', {'news': news}) def create(request): error = '' if request.method == 'POST': form = ArticlesForm(request.POST) if form.is_valid(): article = form.save() return redirect('news_home') else: error = 'Unfortunately, the form was not filled out correctly.' form = ArticlesForm() data = { 'form': form, 'error': error } return render(request, 'news/create.html', data)` models.py: `from django.db import models class Articles(models.Model): title = models.CharField('name', max_length=50) anons = models.CharField('anons', max_length=250) full_text = models.TextField('article') date = models.DateTimeField('Date of publication') def __str__(self): return self.title class Meta: verbose_name = 'news' verbose_name_plural = 'news'` forms.py: `from .models import Articles from django.forms import ModelForm, TextInput, DateTimeInput, Textarea class ArticlesForm(ModelForm): class Meta: model = Articles fields = ['title', 'anons', 'full_text', 'date'] widgets = { "title": TextInput(attrs={ 'class': 'form-control', 'placeholder': 'the name … -
How to save the child set instance in the parent object in Django's Many to One (Foreign Key) relationship?
I am working on a social media project where users can follow each other. Here are the models that are relevant to this problem django.contrib.auth.models.User class UsersProfiles(ddm.Model): user = ddm.OneToOneField( dcam.User, on_delete=ddm.CASCADE, related_name="profile", ) followers_count = ddm.IntegerField(default=0) followings_count = ddm.IntegerField(default=0) class UsersFollows(ddm.Model): follower = ddm.ForeignKey( dcam.User, on_delete=ddm.CASCADE, related_name="followers", ) following = ddm.ForeignKey( dcam.User, on_delete=ddm.CASCADE, related_name="followings", ) I am creating data redundancy for scalability by storing the followers and followings counts instead of calculating it by using UsersFollows model. So I am using Django's transaction to add a follower for atomicity. with ddt.atomic(): umuf.UsersFollows.objects.create( follower=user, following=followed_user, ) followed_user.profile.followers_count += 1 user.profile.followings_count += 1 followed_user.profile.save() user.profile.save() But during the testing, the user to its followers and followings set is appearing empty. def test_valid(self): response = self.client.post( c.urls.USERS_1_FOLLOWINGS, {"user": 2}, headers=h.generate_headers(self.login_response), ) h.assertEqualResponses(response, c.responses.SUCCESS) user1 = dcam.User.objects.get(pk=1) user2 = dcam.User.objects.get(pk=2) self.assertEqual(user1.profile.followings_count, 1) self.assertEqual(user2.profile.followers_count, 1) follow = umuf.UsersFollows.objects.filter( follower=user1, following=user2, ) self.assertEqual(len(follow), 1) # Below 2 assertions are failing self.assertIn(user1, user2.followers.all()) self.assertIn(user2, user1.followings.all()) I tried saving both the User instances. I also tried saving the UserFollow instance just in case the create function did not save it automatically. umuf.UsersFollows.objects.create( follower=user, following=followed_user, ).save() user.save() followed_user.save() I don't get what am I missing here. -
issue is sending data from backend to frontend in django cannels AsyncWebsocketConsumer
so, th eproblem is simple there is a mistake in receive method which i am unable to find , the problem is that i am successfully getting data from frontend but unable to send data back from server to frontend/client, i just want to send data from backend to frintend -
django model.py file remain unchanged
my django project tree image models.py source file sqlite3 db table image sorry about unskilled writing I want django migration to update sqlite3 db tables, so I make models.py with that codes (second image) but If I type python manage.py makemigrations, it prints "No change detected" and If I type python manage.py migrate, my models.py codes doesn't work like third image(tables doesn't change) p.s django installed in venv move models.py file to sub directory -> doesn't work either -
Manual Django form not saving no matter what I do to Postgres database
I have a problem with saving a form to the database. Everything I've tried doesn't work and I really don't know what else to do. I have a manual form created in Django, I get absolutely no errors on save, everything works fine without any errors, I even get redirected to the success page, and yet I have absolutely nothing in the database. # models.py class Lead(Model): lead_status = CharField(choices=STATUS, default='Activă', verbose_name='Status cerere') property_type = CharField(choices=TIP_PROPRIETATE, default='Apartament', verbose_name='Tip cerere') transaction_type = CharField(choices=TIP_TRANZACTIE, verbose_name='Tip tranzacție') contact = ForeignKey(Contact, on_delete=SET_NULL, null=True, verbose_name='Contact asociat') county = CharField(choices=JUDETE, verbose_name='Județ') city = CharField(max_length=30, verbose_name='Localitate') zone = CharField(max_length=30, null=True, blank=True, verbose_name='Zonă') street = CharField(max_length=40, null=True, blank=True, verbose_name='Stradă') budget = IntegerField(null=True, blank=True, verbose_name='Buget alocat') payment_method = CharField(choices=MODALITATE_PLATA, null=True, blank=True, verbose_name='Modalitate plată', ) urgency = CharField(choices=URGENTA, default='Normal', verbose_name='Urgență') other_details = TextField(max_length=2000, null=True, blank=True, verbose_name='Alte detalii') labels = CharField(choices=ETICHETA, null=True, blank=True, verbose_name='Etichete') notes = TextField(max_length=2000, null=True, blank=True, verbose_name='Notițe proprii') created_at = DateTimeField(auto_now_add=True, verbose_name='Data introducerii') updated_at = DateTimeField(auto_now=True, verbose_name='Data ultimei actualizări') deadline_date = DateField(null=True, blank=True, verbose_name='Data limită') deadline_time = TimeField(null=True, blank=True, verbose_name='Ora limită') class Meta: abstract = True def __str__(self): return f'{self.contact}' class ApartmentLead(Lead): apartment_type = CharField(choices=TIP_APARTAMENT, verbose_name='Tip apartament') destination = CharField(choices=DESTINATIE_AP, verbose_name='Destinație') rooms_number = IntegerField(null=True, blank=True, verbose_name='Număr camere') nr_bedrooms … -
How can I get my crispy form to work in Django in the login process?
I would like to customize my login page using crispy by using placeholders in the text fields instead of labels. I can't log in with the crispy form tag and the design is also different to what I want but with the crispy filter I can log in but I don't know how to design the template according to my wishes. That's my code so far: views.py: from django.http import HttpResponse from django.shortcuts import render, redirect from django.contrib.auth.models import User from django.contrib.auth.decorators import login_required from django.contrib import messages from .forms import UserRegisterForm, UserIndexForm #The webpage where you can login. def login(request): return render(request, 'loginprofile/login.html') forms.py: from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import AuthenticationForm from crispy_forms.helper import FormHelper from crispy_forms.layout import Layout, Fieldset, Submit, HTML, Field # UserIndexForm class UserIndexForm(AuthenticationForm): def __init__(self, *args, **kwargs): super(UserIndexForm, self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_show_labels = False self.helper.form_show_errors = True self.helper.error_text_inline = False self.helper.help_text_inline = True self.helper.form_tag = False self.helper.form_method = 'POST' self.helper.form_action = 'submit_survey' self.fields['username'].help_text = None self.fields['password'].help_text = None self.helper.layout = Layout( Field('username', placeholder='Username'), Field('password', placeholder='Password'), ) self.helper.add_input(Submit('submit', 'Sign In', css_class='container btn-success justify-content-center')) class Meta: model = User fields = ['username', 'password'] widgets = { 'username': forms.TextInput(attrs={'class': 'form-control mb-0', … -
how can i show the terminal output and matplotlib graphic on django web
I got no clue how to do it. this is my py code # Gerekli kütüphanelerin yüklenmesi import numpy as np import pandas as pd import matplotlib.pyplot as plt from sklearn.datasets import load_iris from sklearn.model_selection import train_test_split from sklearn.preprocessing import StandardScaler from sklearn.tree import DecisionTreeClassifier from sklearn.ensemble import RandomForestClassifier, GradientBoostingClassifier, AdaBoostClassifier from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score # Iris veri setini yükleme iris = load_iris() X = iris.data y = iris.target # Veri setini görselleştirme plt.figure(figsize=(10, 6)) plt.scatter(X[:, 0], X[:, 1], c=y, cmap='viridis') plt.xlabel('Sepal Length') plt.ylabel('Sepal Width') plt.title('Iris Veri Seti') plt.colorbar(label='Class') plt.show() # Veri setini eğitim ve test setlerine ayırma X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42) this is the matplotlib output this is the output of the terminal -
django.core.exceptions.ImproperlyConfigured: AUTH_USER_MODEL refers to model 'tools.User' that has not been installed
I want to replace the original User of django with my own User, but the following error occurred there is my settings.py,I mainly addedAUTH_USER_MODEL = 'tools.User' from datetime import timedelta from pathlib import Path import django DEBUG = True ALLOWED_HOSTS = [] INSTALLED_APPS = [ 'channels', "daphne", 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework_simplejwt', 'corsheaders', 'campus_services', 'edu_admin', 'interaction', 'tools', ] AUTH_USER_MODEL = 'tools.User' # Application definition MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'backend.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [BASE_DIR / 'templates'] , '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 = 'backend.wsgi.application' DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': '', 'USER': '', 'PASSWORD': '', 'HOST': '', } } # Password validation # https://docs.djangoproject.com/en/4.2/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.2/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/4.2/howto/static-files/ STATIC_URL = 'static/' # Default primary key field type # https://docs.djangoproject.com/en/4.2/ref/settings/#default-auto-field DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework_simplejwt.authentication.JWTAuthentication', ) } SIMPLE_JWT = { … -
Django DRF_Spectacular and dynamic serializer problem
i have a 2 serializers when i get the list of ItemCategory i want have all fields so ItemCategorySerializer is enough but when i call ItemCategorySerializer from ItemSerializer i want print only id and name but when i generate the swagger schema inside my schema list i find ItemCategory with only 'id', 'name' class ItemCategorySerializer(coreSerializers.DynamicModelSerializer): class Meta: model = ItemCategory fields = "__all__" class ItemSerializer(coreSerializers.DynamicModelSerializer,): class Meta: model = Item fields = "__all__" category_obj = ItemCategorySerializer(source='category', many=False, read_only=True, required=False, allow_null=True, partial=True, fields=['id', 'name', ]) so, i have this inside swagger this schema but i want that i think that happen because before it generate ItemCategory full then ItemSerializer call ItemCategorySerializer and replace ItemCategory full with minimized: how i can force to use in schema model ItemCategory full ? -
Model Message at migration in django
My Model is like below. from django.db import models from django.contrib.auth.models import AbstractUser # Create your models here. class User(AbstractUser): GENDER_CHOICES = ( ('M', 'Male'), ('F', 'Female'), ('O', 'Other'), ) USER_TYPE = ( ('S', 'Super Admin'), ('A', 'Admin'), ('P', 'Patient'), ('D', 'Doctor'), ('U', 'User'), ) first_name = models.CharField(max_length=255) last_name = models.CharField(max_length=255) date_of_birth = models.DateField() gender = models.CharField(max_length=1, choices=GENDER_CHOICES) user_type = models.CharField(max_length=1, choices=USER_TYPE) email = models.EmailField(unique=True) phone = models.CharField(max_length=15, blank=True, null=True) address = models.TextField(blank=True, null=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) active = models.BooleanField(default=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] def __str__(self): return f"{self.first_name} {self.last_name}" I am getting message like below. It is impossible to add a non-nullable field 'password' to user without specifying a default. This is because the database needs something to populate existing rows. Please select a fix: 1) Provide a one-off default now (will be set on all existing rows with a null value for this column) 2) Quit and manually define a default value in models.py. -
ViewSet method create never validates nested model
I'm learning WebSockets [django channels] to use along with DRF. I have created simple HTML form to create Comment. The form contains some User data so everyone can post a comment and the data entered is being used to create a new User (posting comment not requiring any authentication at all). Everything works fine when sending POST request from DRF Browsable API. However doesn't work when sending data from HTML form : returns error "user": ["This field is required."] Models: class Comment(MPTTModel): """ The base model represents comment object in db. """ user = models.ForeignKey(CustomUser, related_name="comments", on_delete=models.CASCADE) date_created = models.DateTimeField( verbose_name="Created at", auto_now_add=True, blank=True, null=True ) text = models.TextField(max_length=500) class CustomUser(AbstractBaseUser, PermissionsMixin): """Custom User model extends a pre-defined django AbstractUser model.""" uuid = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) email = models.EmailField(verbose_name="email address", max_length=255, unique=True) username = models.CharField(max_length=64, unique=True) avatar = ResizedImageField( force_format="WEBP", crop=["middle", "center"], upload_to=profile_avatar_path, blank=True, null=True, max_length=500, storage=OverwriteStorage() ) homepage = models.URLField(max_length=255, null=True, blank=True) enter code here ViewSet: class CommentViewSet(ModelViewSet): """ Comment Viewset to handle base model operations. """ queryset = Comment.objects.filter(level=0) serializer_class = CommentSerializer def create(self, request, *args, **kwargs): user_data = {} for field, value in request.data.items(): if field.startswith("user"): user_data.update({field.split("-")[1]: value}) request.data._mutable = True request.data["user"] = user_data request.data._mutable = False … -
How to use variable to iterate in django template?
I'm using python and django and I would like to use a variable I entered in a previous input, to iterate over creating multiple other input fields. This is the part in the Django template where I ask the number I would like to use in the iteration: <form method="GET"> <label for="grondstoffen_count" style="font-family: Oswald, sans-serif;">Give how many products were delivered:</label> <input type="number" name="grondstoffen_count" id="grondstoffen_count" min="0" required> <button type="submit" name="submit_count">Bevestig</button> </form> This is the part my views.py where I generate a string of the sequence up to the input number. When I have the string I return it to the Django template: elif 'submit_count' in self.request.GET: grondstoffen_count = int(self.request.GET.get('grondstoffen_count', 0)) volgordelijst = "" for i in range(1, grondstoffen_count + 1): volgordelijst += str(i) print(type(volgordelijst)) # string print(volgordelijst) # when grondstoffen_count is 5 then this gives "12345" return render(self.request, 'Ano_app/BehandelNieuweVoorraad.html', {'volgordelijst': volgordelijst}) In the template I receive the 'volgordelijst' (so I don't think it's a problem with giving the variable from the view to the template because the name is automatically suggested) and I would like to use that variable for the loop. I would like to have as many input fields as the number in the original input but when I … -
add and view cart with django session
def add_cart(request, pk): produit = Produit.objects.get(id=pk) quantity = int(request.POST.get('quantity', 1)) # Get the quantity from the form cart = request.session.get('cart', []) if quantity > produit.quantitéP: messages.error(request, "La quantité dépasse le stock!!") return redirect(reverse('details-produit', args=[produit.id])) # Append the product and its quantity to the cart as a dictionary cart.append({'produit_id': produit.id, 'quantity': quantity}) request.session['cart'] = cart messages.success(request, "Produit ajouté au panier avec succès ") return redirect('cart') def view_cart(request): cart = request.session.get('cart', []) produits_in_cart = [] for item in cart: produit_id = item.get('produit_id') quantity = item.get('quantity') try: produit = Produit.objects.get(id=produit_id) produits_in_cart.append((produit, quantity)) except Produit.DoesNotExist: pass return render(request, 'app1/cart.html', {'produits_in_cart': produits_in_cart}) I'm trying to add a product and his quantity into a cart after that i wanted tho show all the products with their quantity in a cart template but i'm getting and (AttributeError at /cart 'int' object has no attribute 'get') Error here's my views :