Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django serialize custom user model
I have CustomUser model which inherits from AbstractUser clas. I have a serializer which throw me following errors: When I use from django.contrib.auth.models import User, the error is "AttributeError: 'NoneType' object has no attribute '_meta'". When I use from users.models import User, the error is "'QuerySet' object has no attribute 'email'", but the email field exists within the model. Here is what my serializer looks like: from rest_framework import serializers from users.models import User # from django.contrib.auth.models import User class DepartmentSerializer(serializers.ModelSerializer): class Meta: model = Department fields = ['id', 'title', 'is_active'] class CustomUserSerializer(serializers.ModelSerializer): department = DepartmentSerializer() class Meta: model = User fields = ['id', 'email', 'ad_login', 'sap', 'user_type', 'language', 'first_name', 'last_name', 'department'] In my settings I have also defined "AUTH_USER_MODEL = 'users.User'". Hoping this is enough information, what may be the cause of these errors? -
How to Insert in SQL using django app but getting COUNT field incorrect or syntax error
I want to insert data from django to sql but getting error : ('07002', '[07002] [Microsoft][ODBC SQL Server Driver]COUNT field incorrect or syntax error (0) (SQLExecDirectW)') My code is below: for connection: def connsql(): server = '' database = '' username = '' password = '' conn = pyodbc.connect('DRIVER={SQL Server};SERVER='+server+';DATABASE='+database+';UID='+username+';PWD='+ password) return conn for storing data in db: connectionString=self.connsql() saveDetails=ModelClass() todayDate=date.today() saveDetails.Date=todayDate.strftime('%m/%d/%Y') saveDetails.Questions=question saveDetails.Result=str(result) cursor=connectionString.cursor() cursor.execute("insert into [dbo].[testtable] (Date,Questions,Result) values ("+saveDetails.Date+"','"+saveDetails.Questions+"','"+saveDetails.Result+");") cursor.commit() As I'm new to this any help will be thankfull. -
How Make each app use diffrent database(postgresql)?
My project have 3 apps(accounts:sqlite, books:postgresql, publishers:postgresql), And I want each app use its own db but I don't know how :( I installed pgAdmin and created table and databases but I can't connect it correctly to django! This is my setting Databse part: DATABASES = { 'default': {}, 'accounts': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'users.sqlite3', }, 'books_db': { 'NAME': 'book_data', 'ENGINE': 'django.db.backends.postgresql', 'USER': 'postgres', 'PASSWORD': 'root', 'HOST': '127.0.0.1', 'PORT': '5432', }, 'publishers_db': { 'NAME': 'publisher_data', 'ENGINE': 'django.db.backends.postgresql', 'USER': 'postgres', 'PASSWORD': 'root', 'HOST': '127.0.0.1', 'PORT': '5432', } } -
Django remove source files and how to running pyc files?
In Django project, I don't share the views.py to client. like to remove views.py source files from Django, only pyc files there. But when i remove source file, it gives me ImportError, it should refer pyc file, but it is not refering them. How to solve this problem? -
How to display latest created multiple records created twice in a same day in django
Here when the user clicks the schedule button multiple times in a day it is creating same set of records multiple times in the database But i want to display to only the lastest created records for example when the user clicks the schedule button first time it creates records from id 1 to 5 and again when the user clicks the schedule button for the second time its is creating the same records i.e id from 6 to 10 with updated time different Now in my front end i want to display only the records from 6 to 10 (because id 1 to 5 and 6 to 10 are same records irrespective of updated_on field) id o_num_id p_id s_date time_req i_line_id updated_on 1 1312 22 2023-03-14 225 2426 2023-03-10 06:19:52.174517 2 1312 22 2023-03-13 120 2426 2023-03-10 06:19:52.174517 3 1312 21 2023-03-12 430 2426 2023-03-10 06:19:52.174517 4 1312 20 2023-03-11 350 2426 2023-03-10 06:19:52.174517 5 1312 20 2023-03-10 720 2426 2023-03-10 06:19:52.174517 6 1312 22 2023-03-14 225 2426 2023-03-10 06:23:52.174517 7 1312 22 2023-03-13 120 2426 2023-03-10 06:23:52.174517 8 1312 21 2023-03-12 430 2426 2023-03-10 06:23:52.174517 9 1312 20 2023-03-11 350 2426 2023-03-10 06:23:52.174517 10 1312 20 2023-03-10 720 … -
The authenticate function return always none Django Project
I am working on a vehicle project management system, and using a custom table for storing the signup details in MySQL. When the user logins the authenticate function returns none always, I am using email and password fields for login checked the values are retrieving from database correctly or not The backend authentication ' def userLogin(request): if request.method == 'POST': email = request.POST.get('email') password = request.POST.get('password') print('from loginhtml page',email,password) try: user_profile = UserProfiles.objects.get(email=email) user = authenticate(request, username=email, password=password) print("from database ",user_profile.email,user_profile.password) print(user) if user is not None: login(request, user) messages.success(request, 'You have been logged in successfully.') return redirect('/DashboardPage.html') else: error_message='Invalid email or password. Please try again.' messages.error(request, error_message) except UserProfiles.DoesNotExist: error_message='Invalid email or password. Please try again.' messages.error(request, error_message) return render(request, 'userLogin.html') from django.contrib.auth.backends import BaseBackend from django.contrib.auth import get_user_model from django.shortcuts import redirect from .models import UserProfiles class UserProfileBackend(BaseBackend): def authenticate(self, request, email=None, password=None): try: user = UserProfiles.objects.get(email=email) if user.check_password(password): return user except UserProfiles.DoesNotExist: return None {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <title>Vehicle Parking Management System - User Login</title> <link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet"> <link href="https://fonts.googleapis.com/css?family=Montserrat:400,700&display=swap" rel="stylesheet"> <link rel="stylesheet" href="{% static 'styles/loginstyle.css' %} "> </head> <body> <nav class="navbar navbar-expand-lg navbar-light bg-light"> … -
Should I create an endpoint per HTTP method in my Django backend application?
I am developing a Django backend application with Django Rest Framework. Apart from having to write a lot of code, is it good practice to have a separate endpoint for each CRUD operation? Say I have an Organization model that I would like to create CRUD endpoints for. My usual approach is to create an endpoint ListCreateOrganization(generics.ListCreateAPIView) and map that to the path /organization/. Then create another endpoint /organization/<int:pk>/ for a RetrieveUpdateDeleteOrganization(generics.RetrieveUpdateDestroyAPIView) (assuming all CRUD operations apply). What are the scalability and performance concerns of this approach? What about creating five endpoints and mapping that to each operation: Create - /organization/create List (get multiple instances) - /organization/list/ Get a single instance - /organization/<int:pk>/retrieve/ Update a single instance - /organization/<int:pk>/update/ Delete a single instance - /organization/<int:pk>/delete/ -
Image not working django (TRYING TO ADD PLACEHOLDER IMAGE)
Iam doing a food ordering website using django. Iam trying to keep the place holder image but it is not working. Below I have attached models.py,0001_initials.py,index.html. I tried but it is not working models.py: from django.db import models # Create your models here. class Item(models.Model): name=models.CharField(max_length=200) desc=models.CharField(max_length=200) price=models.CharField(max_length=200) image=models.CharField(max_length=400,default='https://upload.wikimedia.org/wikipedia/commons/e/e0/PlaceholderLC.png') def __str__(self) : return self.name 0001_initials.py: # Generated by Django 4.1.7 on 2023-03-07 13:10 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Item', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=200)), ('desc', models.CharField(max_length=200)), ('price', models.CharField(max_length=200)), ('image', models.CharField(default='https://upload.wikimedia.org/wikipedia/commons/e/e0/PlaceholderLC.png', max_length=400)), ], ), ] index.html: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> {% for item in item %} <div class="row"> <div class="col-md-3 offset-md-3"> <img src='{{item.image}}' class="card" height="150px"> </div> </div> {% endfor %} </body> </html> These are the files. Output: enter image description here -
Difference between calling user.save() and create_user when using UserCreationForm (or subclass of) and register view in Django
I am making a web app using Django 4.1. I am trying to implement a simple registration page. For the moment, I am using the UserCreationForm provided by Django. I do intend to implement a custom Here is my code from views.py: def register(request): if request.method == "POST": form = UserCreationForm(request.POST) if form.is_valid(): user = form.save(commit=False) user.clean() username = form.cleaned_data.get("username") raw_password = form.cleaned_data.get("password1") response_text = ( f"Received username: {username}\nReceived password: {raw_password}" ) user.save() return HttpResponse("<p>" + response_text + "</p>") else: form = UserCreationForm() return render(request, "register.html", {"form": form}) I need some help on knowing when create_user is used. I looked at this, but it doesn't address the issue of when to use create_user in the context of a registration form. How would one use create_user() in a user registration view? Should it even be used? What are the best practices? -
How to I make a Django model field with choices of all IANA timezones?
I would like to have a dropdown in the django admin console for valid iana timezone choices. How can I achieve something like this: from django.db import models class Building(models.Model): name = models.CharField(max_length=100) iana_timezone = models.CharField(max_length=100, choices=iana_timezone_choices) -
How to make a loop in views.py file through my Django Session Cart Data
This data i added to Django session.I want to calclute single data: (qty and price ) and i want to claclute my (total amount) dict_items([('1', {'name': 'Talon Lott', 'image': '/media/images/products/1.png', 'reg_price': '958.0', 'dis_price': '844.0', 'qty': 1}),('2', {'name': 'Lionel Owens', 'image': '/media/images/products/2.png', 'reg_price': '684.0', 'dis_price': '221.0', 'qty': '1'}),('3', {'name': 'Brenna Chan', 'image': '/media/images/products/3.png', 'reg_price': '728.0', 'dis_price': '177.0', 'qty': 1}),('4', {'name': 'Amos Osborne', 'image': '/media/images/products/4.png', 'reg_price': '453.0', 'dis_price': '547.0', 'qty': '1'})]) But In views.py file when i loop this data i only get id:1 data. {'name': 'Talon Lott', 'image': '/media/images/products/1.png', 'reg_price': '958.0', 'dis_price': '844.0', 'qty': 1} So how may i make a loop for my session data Here is my views.py file I used Jquey ajax on Add_to_cart button to add my product Add To Cart # Add To Cart def add_to_cart(request): card_product = {} card_product[str(request.GET['id'])] ={ 'name': request.GET['name'], 'image': request.GET['image'], 'reg_price': request.GET['reg_price'], 'dis_price': request.GET['dis_price'], 'qty': request.GET['qty'] } # print(card_product) # print(id, name, image, reg_price, dis_price, qty) if 'cartdata' in request.session: if str(request.GET['id']) in request.session['cartdata']: card_data = request.session['cartdata'] card_data[str(request.GET['id'])]['qty'] = int(card_product[str(request.GET['id'])]['qty']) card_data.update(card_data) request.session['cartdata'] = card_data else: card_data = request.session['cartdata'] card_data.update(card_product) request.session['cartdata']= card_data else: request.session['cartdata'] = card_product return JsonResponse({ 'data':request.session['cartdata'], 'totalitems':len(request.session['cartdata']) }) # Cart Page View class CartListView(IndexView): template_name = 'cart/cart.html' def get_context_data(self, … -
django.template.exceptions.TemplateSyntaxError: Could not parse the remainder: '{' from '{'
I'm trying to display a photo on a page. My code: # views.py def productHTML(request, uuid): product = Product.objects.get(id = uuid) path = product.category.path_to_foto slovar = {"product": product, "category": path} return render(request, "product.html", slovar) productHTML.html: {% extends 'products.html' %} {% load static%} {% block title %}Продукт{% endblock %} {% block page_content %} {% if product %} <p>Путь до фото: {{path}} </p> <img src="{% static {{ path }} %}" alt="product picture" width="540" height="300"> <p><b>Категоия: </b>{{ product.category }} </p> <p><b>Название: </b>{{ product.name }}</p> <p><b>Марка: </b>{{ product.marka }}</p> <p><b>Привод: </b>{{ product.privod }}</p> <p><b>Лошадиные силы: </b>{{ product.loshad_sila }}</p> <p><b>Коробка передач: </b>{{ product.box_peredach }}</p> <p><b>Объём двигателя: </b>{{ product.volume_dvigatel }} <p><b>Цена: Бесплатно</p> <button>КУПИТЬ</button> {% endif %} {% endblock %} Through Product.objects.get(id = uuid) I get a specific product. Through product.category.path_to_foto I get the path to the photo of this product. After that I'm trying to put this path into a variable and display it on the html page, but I get an error: django.template.exceptions.TemplateSyntaxError: Could not parse the remainder: '{{' from '{{' All product photos are stored in static/media If you need any details, I am ready to provide them. I tried to change the path to the photo. For example, I tried to replace media/<file> … -
Save multiple forms in one view
I have the following relational models: class Anuncio(models.Model): anunciante = models.ForeignKey(User, verbose_name=_("anunciante"), on_delete=models.CASCADE, null=True) titulo = models.CharField(_("titulo del anuncio"), max_length=50) class Producto(models.Model): nombre = models.CharField(_("nombre del producto"), max_length=50) anuncio = models.ForeignKey(Anuncio, on_delete=models.CASCADE, related_name='products', blank=True, null=True) class Imagen(models.Model): producto = models.ForeignKey(Producto, on_delete=models.CASCADE, related_name='imagen', blank=True, null=True) imagen = models.ImageField(upload_to='marketplace/') I have a form, that allows adding an instance of all of three models with the proper relations. This works okay, but I'm trying to add a feature that adds additional Producto and Imagen instances to the same Anuncio. I'm rendering the additional forms with JavaScript and I get the render OK, but I can't get the data of the additional forms saved. This is the main Anuncio create view: def anunciocreateview(request): if request.method == "POST": anuncio_form = AnuncioForm(request.POST or None) producto_form = ProductoForm(request.POST or None) imagen_form = ImagenForm(request.POST, request.FILES) if all([anuncio_form.is_valid(), producto_form.is_valid(), imagen_form.is_valid()]): anuncio = anuncio_form.save(commit=False) anuncio.anunciante = request.user anuncio.save() producto = producto_form.save(commit=False) producto.anuncio = anuncio producto.save() imagen = request.FILES.get('imagen') if imagen: Imagen.objects.create(producto=producto, imagen=imagen) return HttpResponse(status=204, headers={'HX-Trigger' : 'eventsListChanged'}) else: print(anuncio_form.errors) print(producto_form.errors) print(imagen_form.errors) else: anuncio_form = AnuncioForm() producto_form = ProductoForm() imagen_form = ImagenForm() context = { 'anuncio_form' : anuncio_form, 'producto_form' : producto_form, 'imagen_form' : imagen_form } return render(request, 'buyandsell/formulario.html', context) And this … -
Django: password is being saved plain text in MySQL Database
I'm trying to register user. When i'm creating superuser, password is being saved correctly, however when i'm registering the user through the api, it's being saved as plain text. My RegisterSerializer: from django.contrib.auth.models import User from rest_framework import serializers, validators class RegisterSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('username', 'password', 'email', 'first_name', 'last_name') extra_kwargs = { "password": {"write_only": True}, "email": { "required": True, "allow_blank": False, "validators": [ validators.UniqueValidator( User.objects.all(), "A user with that Email already exists" ) ] }, 'first_name': {"required": True}, 'last_name': {"required": True} } def create(self, validated_data): user = User( email=validated_data.get('email'), username=validated_data.get('username'), first_name=validated_data.get('first_name'), last_name=validated_data.get('last_name'), ) user.set_password(validated_data.get('password')) user.save() return user views.py register request: @api_view(['POST']) def register_api(request): serializer = RegisterSerializer(data=request.data) serializer.is_valid(raise_exception=True) user = serializer.save() _, token = AuthToken.objects.create(user) return Response({ 'user_info': { 'id': user.id, 'username': user.username, 'email': user.email, 'first_name': user.first_name, 'last_name': user.last_name, }, 'token': token }) -
React JS, Python Django Tutorial - infinite loop componentDidUpdate
I'm following an online video tutorial on creating a CRUD full-stack app with React/Django/Sqlite, but I am running into an infinite loop when fetching any table data. The problem seems to be caused by componentDidUpdate, which is necessary for reloading the table after updating/deleting an entry. Here's a sample code snippet below (links below): refreshList(){ fetch(process.env.REACT_APP_API+'employee') .then(response=>response.json()) .then(data=>{ this.setState({emps:data}); //<=? }); } componentDidMount(){ this.refreshList(); } componentDidUpdate(){ //<= this.refreshList(); } Learn React JS, Python Django by Creating a Full-Stack Web App from Scratch GitHub Source Code Problem Code Snippet -
Brand new to Django. from django.urls import include, path not working
Cannot import include into urls.py It was working a few hours ago, and I broke something, badly. Please be nice. Newbie Haven't touched UNIX or a program in 30 years. Thanks I tried, in urls.py from django.urls import include, path VS Code won't even light up the "include" Django Version 4.0.3 -
MobSF (Mobile-Security-Framework-MobSF) installation problems
I spent last days striving with MobSF (Mobile-Security-Framework-MobSF) installation, which finally fails without reaching the target. My work laptop is Windows 10 with i5-8250U and 16G memory. I tried it using git clone https://github.com/MobSF/Mobile-Security-Framework-MobSF.git then running setup.bat Meanwhile installing Python (Python 3.11.2), OpesnSSL (64 bit) and Visual studio. The BAT file runs slowly ... unfortunately fails [ERROR] Installation Failed! throwing errors: *ERROR: Could not find a version that satisfies the requirement yara-python-dex>=1.0.1 (from apkid==2.1.4->-r requirements.txt (line 24)) (from versions: none) ERROR: No matching distribution found for yara-python-dex>=1.0.1 (from apkid==2.1.4->-r requirements.txt (line 24)) * and Traceback (most recent call last): File "c:\Users\ij\tools\Mobile-Security-Framework-MobSF\manage.py", line 12, in from django.core.management import execute_from_command_line ModuleNotFoundError: No module named 'django' Trying to kludge it around: pip install -r requirements.txt python -m pip install django But it still does not work. Another attempt was installation using docker build -t mobsf . But it finishes: ERROR [ 5/15] RUN ./install_java_wkhtmltopdf.sh [ 5/15] RUN ./install_java_wkhtmltopdf.sh: #9 0.782 /bin/sh: 1: ./install_java_wkhtmltopdf.sh: not found executor failed running [/bin/sh -c ./install_java_wkhtmltopdf.sh]: exit code: 127 Google hardly shows anything about it. **I will appreciate any hint to solve. May be there is another qwat to install MobSF ** -
Chatbot Backend API
For a full stack project, I've been working with ChatterBot and Django and It's been really tricky for me to fully grasp. The concept of the project is pretty simple. I web scraped some recipes and now I' using a chatbot to filter the recipes. For instance, if the user sends a message like: "What can I make with eggs?" The chatbot should filter through the recipes and return those with egg as an ingredient. I have a FilterView that works great: class RecipeFilter(APIView): def post(self, request): ingredients = request.data.get('ingredients', []) if ingredients: recipes = Recipe.objects.all() for ingredient in ingredients: recipes = recipes.filter(ingredients__ingredient__ingredient__iexact=ingredient) serializer = RecipeSerializer(recipes, many=True) return Response(serializer.data) else: return Response({'message': 'Please provide a list of ingredients.'}) I've been trying to use ChatterBot for the same effect but with more casual user input. Here's what I've got: class ChatBot(APIView): def post(self, request): message = request.data['message'] bot = ChatBot('Bot') trainer = ListTrainer(bot) if not bot.storage.count(): recipes = Recipe.objects.all() for recipe in recipes: trainer.train([recipe.recipe] + [ri.ingredient.ingredient for ri in recipe.ingredients.all()]) response = bot.get_response(message) recipe = Recipe.objects.filter(recipe=response.text).first() if recipe: serializer = RecipeSerializer(recipe) return Response({'message': serializer.data['description']}) else: return Response({'message': "I'm sorry, there are currently no recipes available with those ingredients."}) This implementation is … -
This error message in Django means "TypeError: Object of type type is not JSON serializable"
This error message in Django means "TypeError: Object of type type is not JSON serializable". This doesn't make sense! This is my serializers: class MatriculaSerializer(serializers.ModelSerializer): class Meta: model = models.MATRICULA fields = ( 'ID_MATRICULA', 'ID_USUARIO', 'ID_TIPO_MATRICULA', 'VALIDADE', 'EXPEDICAO', 'ISATIVO' ) this is my models class MATRICULA(BASE): ID_MATRICULA = models.AutoField(primary_key=True) ID_USUARIO = models.ForeignKey(USUARIO, related_name='MATRICULA_ID_USUARIO',on_delete=models.DO_NOTHING, null=False) ID_TIPO_MATRICULA = models.ForeignKey(TIPO_MATRICULA, related_name='MATRICULA_TIPO_MATRICULA',on_delete=models.DO_NOTHING, null=False) VALIDADE = models.DateField EXPEDICAO = models.DateField(null=False) def __str__(self): str = (f"{self.ID_MATRICULA}") return str this is my views class MatriculaAPIView(generics.ListCreateAPIView): queryset = models.MATRICULA.objects.all() serializer_class = serializers.MatriculaSerializer And this is my urls path('matricula/', views.MatriculaAPIView.as_view(), name='matricula') This error only happens with this model "Matricula" I have several others that work well, and they have the same type of coding. -
Django, How to serialize multiple model object in Nested Relationships?
I am creating an API using Django Restframework which needs data from multiple models. I followed the API guide of django rest framework - Nested relationships, but it doesn't work. I have 4 tables, Gallery, Picture, Tag, PictureTag, and my models as follows class Gallery(models.Model): title = models.CharField(null=True, blank=True, default=None) created = models.DateTimeField(default=timezone.now) class Picture(models.Model): gallery = models.ForeignKey(Gallery, on_delete=models.CASCADE, related_name='pictures') name = models.CharField(null=True, blank=True, default=None) posted = models.DateTimeField(default=timezone.now) tags = models.ManyToManyField(Tag, through='GalleryTag') class Tag(models.Model): tag_name = models.CharField(max_length=25) class PictureTag(models.Model): gallery = models.ForeignKey(Gallery, on_delete=models.CASCADE) tag = models.ForeignKey(Tag, on_delete=models.CASCADE) vote = models.IntegerField() I wrote the following code according to the API guide of django rest framework Here's my serializer class PictureListSerializer(serializers.ModelSerializer): class Meta: model = Picture fields = ['name', 'posted'] class GalleryDetailSerializer(serializers.ModelSerializer): pictures = PictureListSerializer(many=True, read_only=True) class Meta: model = Gallery fields = ['id', 'title', 'created', 'pictures'] and my view class GalleryDetail(generics.RetrieveUpdateDestroyAPIView): queryset = Gallery.objects.prefetch_related('pictures') serializer_class = GalleryDetailSerializer I want to get the detail of a gallery with gallery_id, for example: http://127.0.0.1:8000/api/gallery/2/ { "id": 2, "title": "Gallery Example", "created": "2023-3-9", "pictures": [ { "name": "name1" "posted": "posted1" }, { "name": "name2" "posted": "posted2" }, { "name": "name3" "posted": "posted3" }, ... ], } But I actually only get id, title and created, … -
Django - How can I add a user to an auth_group?
I have and django application that I am trying to apply user group permissions. Here is how my members model is setup. Class Member(AbstractUser) Class Meta: permissions = ((Perm1_codename, Perm1_desc),...) pass address = models.CharField(max_length=30) When I migrate this, the permissions are saved in the auth_group_permissions table instead of the members_app_member_user_permissions table. I don't see a way to associate a user to the auth_group table because there is no user column in these tables. I setup my roles in auth_group and defined the permission of each role in auth_group_permissions, how can I associate a user to these groups? Alternatively, how can I add these user permissions to my members_app_member_user_permissions? -
I whant advise witch Django version use with graphql
I want to get advice. When I started working with graphql with django 4, the packages were causing problems. Changing the django version to 3 I solved the problem. Do you think I should continue with django 3 version or what? First I tried to fix the settings, but I didn't fix it completely. Has anyone ever encountered such a situation? -
DRF - AttributeError when using ModelSerializer to save manyToMany relation with 'though' table
I am building a Django Rest Framework project and I'm encountering an attribute error that I cannot seem to resolve. Specifically, I'm getting the following error when I try to serialize a Sale object: Got AttributeError when attempting to get a value for field `product` on serializer `SaleItemSerializer`. The serializer field might be named incorrectly and not match any attribute or key on the `Product` instance. Original exception text was: 'Product' object has no attribute 'product'. I've defined my models and serializers as follows: # Models class Product(models.Model): name = models.CharField(max_length=100) price = models.DecimalField(max_digits=10, decimal_places=2) cost = models.DecimalField(max_digits=10, decimal_places=2) description = models.TextField() image = models.ImageField(upload_to='images/') category = models.ForeignKey(Category, on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class Sale(models.Model): products = models.ManyToManyField(Product, related_name='sales', through='SaleItem') created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class SaleItem(models.Model): sale = models.ForeignKey(Sale, on_delete=models.CASCADE) product = models.ForeignKey(Product, on_delete=models.CASCADE) quantity = models.IntegerField() price = models.DecimalField(max_digits=10, decimal_places=2) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) # Serializers class SaleItemSerializer(serializers.ModelSerializer): class Meta: model = SaleItem fields = ['product', 'quantity', 'value'] class SaleSerializer(serializers.ModelSerializer): products = SaleItemSerializer(many=True) class Meta: model = Sale fields = '__all__' def create(self, validated_data): sale_items_data = validated_data.pop('products') sale = Sale.objects.create(**validated_data) for sale_item in sale_items_data: SaleItem.objects.create(sale=sale, **sale_item) # The erro return sale The code … -
How to prevent hx-push-url when form does not validate
I am building a multi-step form-wizard. When posting each step of the form, I want the url to change. For example 1st step has a url like /update/1/, and when I click Continue, the 2nd step will be at /update/2/ and so on. This is useful so that in case the user does a hard refresh, I can still "stay" in the same step. I deal with this in my view when request.method=="GET" I have a form for which hx-post is triggered by elements outside it like so: <div id="form-wrap"> <form id="my-form"> <input hx-validate="true" some-input.../> {# all inputs have hx-validate="true" #} </form> </d> <button hx-post="{% url 'my_app:company-update' prev %}" hx-include="#my-form *" hx-target="#form-wrap" hx-vals='{ "posting_step": {{current_step}}}' hx-push-url="true">Back</button> <button hx-post="{% url 'my_app:company-update' next %}" hx-include="#my-form *" hx-target="#form-wrap" hx-vals='{ "posting_step": {{current_step}}}' hx-push-url="true" >Continue</button> When the form is valid, everything works fine. However, when any of the fields has validation errors, hx-push-url still pushes the url resulting in seeing the same step of the form with errors, but the url does not correspond to that step, but the next one... Perhaps this is related to this. Is there anyway to go around this? The part of my view dealing with this: # views.py # … -
Django settings.py S3 bucket
My Django app runs in AWS. Is there a way to restart a Django app and pick up new "config" without having to "push" the settings.py (or other) file? My app uses settings.py and what I would like to do is find a way to change config without having to promote my code (and the settings.py file) through my dev, stage and prod environments. I'm wondering if, for example, there is a way to tell Django (or in some other way) pick up the settings.py file from an S3 bucket on a restart? It doesn't have to be the settings.py file, it's just what I'm thinking of since all the config is in there for now. I'm aware that I could use AWS Secrets, but in my situation that would require updating 3 separate secrets (dev, stage, and prod) and so I was hoping for a "one place" solution. Thanks.