Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django 'str' object has no attribute 'read'
I am making the database call to bring a BLOB type image to the django view, but I get the error "'str' object has no attribute 'read'". views.py def listar_productos(): django_cursor = connection.cursor() cursor = django_cursor.connection.cursor() out_cur = django_cursor.connection.cursor() cursor.callproc('FASTFERIA.SP_LISTAR_PRODUCTOS', [out_cur]) lista = [] for fila in out_cur: data = { 'data': fila, 'imagen':str(base64.b64encode(fila[7].read()),'utf-8') } lista.append(data) return lista At first I got the error "'NoneType' object has no attribute 'read'", I fixed this by changing the row number where the image attribute is located. 'imagen':str(base64.b64encode(fila*[7]*.read()),'utf-8') If you could help me understand what the error is trying to say, I would appreciate it very much. -
Django choice field validation in admin
I have a model that has a choice field with choices loaded in the runtime. from some_utils import get_currency_options class Product(models.Model): name = models.CharField(max_length=20) currency = models.CharField(max_length=3, null=True, blank=True, default="USD", choices=[]) def clean(self): # getting the currency options at execution time, options may vary at different times currency_code_options = get_currency_options() if self.currency and self.currency not in currency_code_options: raise ValidationError({"currency": f"Invalid currency code {self.fb_check_currency}."}) super(Product, self).clean() Please ignore the bad design here, it was defined like this since we need to integrate with a legacy system. In the Django admin, I have a form like this from some_utils import get_currency_options class ProductAdminForm(ModelForm): currency_choices = get_currency_options() @staticmethod def _values_list_to_options(values_list): return [(val, val) for val in values_list] def __init__(self, *args, **kwargs): super(ProductAdminForm, self).__init__(*args, **kwargs) self.fields["currency"] = ChoiceField(choices=self._values_list_to_options(self.currency_choices)) class ProductAdmin(admin.ModelAdmin): form = ProductAdminForm Now the problem is, when I go to Django admin and want to update the currency option, it fails to save with an error saying currency is not a valid option. I understand this is due to the choice list being empty, I tried to override the clean and clean_all method but it didn't work. Which method does the admin update operation trigger? Is there a way I can use the … -
How can I do update method based on condition?
I'm working on a Django project and I want to proceed to update method based on condition - if value of requeststatusid = 0 only. I've tried adding errorhandling in my serializers, but no matter the value is, it throws the error. Appreciate any help! Here is my serializer with create and update method. See my if/else condition in update. class RequestCreateSerializer(serializers.ModelSerializer): parts=PartSerializer(many=True) class Meta: model = requestTable fields = ['rid','requestid', 'requeststatusid', 'requesterid', 'requestname', 'parts'] parts = serializers.SerializerMethodField() def create(self, validated_data): parts_data = validated_data.pop('parts') request = requestTable.objects.create(**validated_data) for part_data in parts_data: partsTable.objects.create(request=request, **part_data) return request def update(self, instance, validated_data): if instance.requeststatusid == '0': parts_data = validated_data.pop('parts') part = (instance.parts).all() part = list(part) instance.requeststatusid = validated_data.get('requeststatusid', instance.requeststatusid) instance.requestname = validated_data.get('requestname', instance.requestname) instance.save() for part_data in parts_data: partreq = part.pop() partreq.validatorid = part_data.get('validatorid', partreq.validatorid) partreq.partsstatusid = part_data.get('partsstatusid', partreq.partsstatusid) partreq.englishmaterialdescription = part_data.get('englishmaterialdescription', partreq.englishmaterialdescription) partreq.save() return instance else: raise ValidationError({"Error": 'Non-drafts are non-editable.'}) //views.py class RequestListCreateView(ListCreateAPIView): queryset = requestTable.objects.all() serializer_class = RequestCreateSerializer filterset_class = RequestFilter filter_backends = [DjangoFilterBackend, SearchFilter] filterset_fields=['rid', 'requeststatusid'] search_fields= ['requestname', 'requestid', 'businessunitid__businessunitname', 'plantid__plantname', 'parts__partsid'] def create(self, request, *args, **kwargs): write_serializer = RequestCreateSerializer(data=request.data) write_serializer.is_valid(raise_exception=True) instance = self.perform_create(write_serializer) headers = self.get_success_headers(write_serializer.data) return Response({"Request ID": … -
JS script code for enabling/disabling the button for all the users [closed]
JS script for whenever admin user disable a button for all the users , button should get disabled for all the users and similarly if admin user enable the button for all the users, buttons should get enabled for all the users this is my JS script code:- $(document).ready(function() { var button = $('#Button'); $(button).prop('disabled', true); $('.click').click(function() { if ($(button).prop('disabled')) $(button).prop('disabled', false); else $(button).prop('disabled', true); }); }); My HTML code:- <a href="{% url 'comp_update_form' %}"><input id="Button" type="button" value="Update Competency" class="btn btn-primary" disabled="disabled" /></a> <br/><br/> {% if user.username == '64119749' %} <div class="click"><button class="btn btn-primary" type="submit">Enable/Disable Competency</button></div> <div class="showup"> <!-- <a type="button" class="btn btn-primary" href="{% url 'comp_update_form' %}" id="Button">Update Competency</a>--> </div> {% endif %} How can I modify this for all the users?? -
Modelling custom form using django crispy form
I have this problem where I want to model the style of a field using django-crispy-forms from a template downloaded from the internet. The field looks like this: and the html for this section is (using bootstrap5 obviously): <div class="form-group mb-4"> <label for="id_username">Username</label> <div class="input-group"> <span class="input-group-text" id="basic-addon1"> <svg class="icon icon-xs text-gray-600" fill="currentColor" viewBox="0 0 20 20" xmlns="http://www.w3.org/2000/svg"> <g transform="translate(0.000000,20.000000) scale(0.100000,-0.100000)" fill-rule="evenodd" stroke="none"> <path d="M72 168 c-18 -18 -14 -56 7 -68 26 -14 50 -3 57 26 11 42 -34 72 -64 42z M48 59 c-34 -20 -17 -29 52 -29 39 0 70 4 70 10 0 26 -87 40 -122 19z"/></svg> </span> <input type="text" class="form-control" placeholder="admin" name="username" id="id_username" autofocus required> </div> </div> Using django-crispy-forms I try to model this with Layout() from crispy_forms.layout and using a form class in forms.py in django: from django import forms from django.utils.translation import gettext, gettext_lazy as _ from crispy_forms.helper import FormHelper from crispy_forms.layout import Layout, MultiField, Fieldset, Submit, Div, HTML, Field, Row class LoginForm(forms.Form): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.helper = FormHelper(self) self.helper.layout = Layout( Div( Div( HTML('<span class="input-group-text" id="basic-addon1">' '<svg class="icon icon-xs text-gray-600" fill="currentColor" viewBox="0 0 20 20" xmlns="http://www.w3.org/2000/svg">' '<g transform="translate(0.000000,20.000000) scale(0.100000,-0.100000)" fill-rule="evenodd" stroke="none">' '<path d="M72 168 c-18 -18 … -
Spotipy Token Caching with Django
I am trying to host an app which utilizes the Spotipy library to create and add songs to user's Spotify accounts. The app works fine on my local as the authorization token is stored in the root folder and when prompted on my terminal I am able to "Enter the URL you were redirected to:". I'm using Pythonanywhere to host the app and can see in the server log that the same question is asked but obviously Ito no answer. I've been reading about Django Sessions to try and cache user's tokens but am a bit lost and the only example in the documentation is for Flask. The code I am using is below - happy to share more from additional files if needed, any help is greatly appreciated! The function that creates a new playlist and adds songs to it is triggered when a form is submitted which contains the user's Spotify Username and the 'group' object which is later used to name the playlist... def AggregateTopsList(group, queryset, spotify_user_id, song_limit, start_date, end_date): 2. imports... import spotipy from spotipy.oauth2 import SpotifyOAuth from spotipy.oauth2 import SpotifyClientCredentials import pandas as pd 3. Spotify API Authentication - client credentials (redirect URI, client ID … -
How to display query result in django
I have an app called marketplace and in the app I have a model called Product that I want to be able to get data from to display it in my html file but it doesn't seem to be working. Here is the model: class Product(models.Model): product_id = models.AutoField(primary_key=True) inventory = models.ForeignKey(ProductInventory, on_delete=models.CASCADE) product_name = models.CharField(max_length=30) product_description = models.CharField(max_length=250) price = models.DecimalField(max_digits=10, decimal_places=2) subscription_length = models.IntegerField() Here is the code used in views.py def product_page(request): product_description = Product.objects.raw('SELECT product_description FROM marketplace_product WHERE product_name = "abcdef" ') context = {'product_description': product_description} return render(request, 'main/product-page.html', context) And here is the end result, as you can see it displays the query and not the result data. How can I make it display the result of the SQL query and not the query itself. Thanks -
Djanggo python - database
Ive been working on Web base Djanggo Pyhton project. So my problem is, the website somehow display error which is timeout error which means there something wrong in the code but i cant find where the error. Here is the code views fle # Create your views here. from datetime import datetime as dt, time #from dateutil.parser import parse, tz from django.http import JsonResponse, HttpResponse from django.conf import settings from django.contrib.auth.decorators import permission_required from django.core import serializers from django.core.serializers import serialize from django.core.serializers.json import DjangoJSONEncoder from django.forms.models import inlineformset_factory, modelformset_factory from django.forms import formset_factory, BaseModelFormSet from django.shortcuts import get_object_or_404, render, redirect from itertools import islice from django.db.models import F import collections import json import os from .forms import MitsubishiLiftForm from .models import MitsubishiLift from report.audit_log import log_addition, log_change, log_deletion, backup_log, restore_log from .settings import settings_write, settings_read from hardware.forms import ImportConfigurationForm @permission_required('setting.add_mconfig', raise_exception = True) def liftconfiguration_mconfig(request): title = "Enter Configuration" index_temp = "liconfiguration/index.html" form = MitsubishiLiftForm(request.POST or None) if form.is_valid(): new_obj = form.save() log_addition(request, form, new_obj) return redirect('setting:liconfiguration_index') context = { "title": title, "form": form, "index_temp": index_temp, } return render(request, "liconfiguration/indexr2.html", context) models file from django.db import models class MitsubishiLift(models.Model): id = models.AutoField(primary_key = True) ELSGW_ipaddress = models.CharField(max_length = 50) … -
Building an App that controls my math courses
I am a mathematician who has programming skills. I have a (Math) YouTube channel and give paid math courses. I want to build (or adjust a template of) a web application that allows me to control access to my classes (private playlists on the youtube platform). I will authorize the customers who have already paid to see the courses. Is there a known way to do that? I will be grateful for any suggestions and enlightenment. Thanks in advance. -
How to pass persistent volume to postgres docker
I want to run PostgreSql database with docker, I created a docker-compose like below: django: restart: always build: . ports: - "8000:8000" depends_on: - pgdb #environment: # - url=https://api.backend.example.com #command: "gunicorn config.wsgi:application --bind 0.0.0.0:8000" #networks: # - bridge pgdb: image: postgres container_name: pgdb environment: - POSTGRES_DB=hbys_filyos - POSTGRES_USER=healmedy - POSTGRES_PASSWORD=mhacare1 I want to run PostgreSql database with docker, I created a docker-compose like below: After building I run docker run -p 80:8000 surgery4:dev & as follows. I am getting the following error in terminal: django.db.utils.OperationalError: could not translate host name "pgdb" to address: Try again -
styles.css file is not working. how to solve the problem?
I made a website and got to the point where you need to connect styles.css, but after all the manipulations, my site has not changed and no design has been connected. I tried to rewrite css and html, tried different tips, but nothing helped me. any ideas? I would be grateful for any advice! 1part base.html <!DOCTYPE html> <html lang="en"> <head> <title>{{title}}</title> <link type="text/css" href="{% static 'women/css/styles.css' %}" rel="stylesheet" /> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <link rel="shortcut icon" href="{% static 'women/images/main.ico' %}" type="image/x-icon"/> <meta name="viewport" content="width=device-width, initial-scale=1.0"> </head> <body> <table class="table-page" border=0 cellpadding="0" cellspacing="0"> <tr><td valign=top> {% block mainmenu %} <div class="header"> <ul id="mainmenu" class="mainmenu"> <li class="logo"><a href="#"><div class="logo"></div></a></li> {% for m in menu %} {% if not forloop.last %} <li><a href="#">{{m.title}}</a></li> {% else %} <li class="last"><a href="#">{{m.title}}</a></li> {% endif %} {% endfor %} </ul> <div class="clear"></div> </div> {% endblock mainmenu %}``` I've added screenshots below if anyone needs them. [1][1] [2][2] [3][3] [4][4] - PS I have already tried these options, gives an error ```<link type="text/css" href="{% static 'women/css/styles.css' %}" rel="stylesheet" /> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <link rel="shortcut icon" href="{% static 'women/images/main.ico' %}" type="image/x-icon"/> <meta name="viewport" content="width=device-width, initial-scale=1.0">``` [1]: https://i.stack.imgur.com/3exw2.png [2]: https://i.stack.imgur.com/ye5k7.png [3]: https://i.stack.imgur.com/ZKSs6.png [4]: https://i.stack.imgur.com/eQRvd.png -
Ubuntu terminal opens as root user and forgot "code ." how to fix? picture included
Ubuntu crashed when I had the shell open for a django server. When it rebooted and everytime since, it opens me as the root user. How do I change it back to open me as user? Second, I can find my way back to the user via su username(I found this command via stack overflow). But it seems to have forgotten everything I set up. Like it no longer knows the command "code ." for VS code Any idea on how this happened and what I should do to fix it. See picture below -
Django copy object: func with self.id in html, urls and views
I try copy my object. I can receive copy from my "def checklist_copy" if i explicitly specify pk.(example) But, i try work with 'self.pk' and this is not work. I want to copy the object under which I click on the button i used different variations: (pk=pk) in function, checklist.id and checklist.pk in html template, tried passing "self" to function and doing self.pk doing pk=int(Checklist.object.get.id()) to then transfer this "pk" to (pk=pk) in object.id() try include func in class DetailView did not achieve a result Please help. I don't know where and what to look for Example: models.py from django.urls import reverse from django.db import models class Checklist(models.Model): title = models.CharField(max_length=250) def get_absolute_url(self): return reverse ('checklist:checklist', kwargs={'id': self.id, 'title': self.title}) def __str__(self): return self.title view.py from django.views.generic.list import ListView from django.views.generic.detail import DetailView from .models import Checklist from django.shortcuts import redirect from django.urls import reverse_lazy class CheckListView(ListView): model = Checklist context_object_name = 'checklists' class CheckListDetail(DetailView): model = Checklist context_object_name = 'checkList' template_name = 'base/checklist.html' def checklist_copy(request): dest = Checklist.objects.get(pk=2) #here i need to use self.id(pk), but can't include 'self' in args of func dest.pk = None dest.save() return redirect(reverse_lazy('checklists')) urls.py (my app) from django.urls import path from .views import CheckListView, … -
Django authentication when database is changed
I have created a Django application with authentication using django.contrib.auth. I was using a database with user admin and password xyz everything works fine. Then I changed the database which has user admin with password abc. The issue is my application is running fine after refresh (logged in as admin) even though I didn't know the password abc. which shouldn't be possible. After I logged out, everything is working fine as expected. -
Django upload file size limit and restriction
I have a form in my app where users can upload files so how can i set a limit to the uploaded file size and type ? **models.py** class Document(models.Model): emp = models.ForeignKey(Emp, null=True, on_delete=models.SET_NULL) Description = models.CharField(max_length=100, null=True) Fichier = models.FileField(upload_to='file/') data_created = models.DateTimeField(auto_now_add=True, null=True) **forms.py** class documentForm(ModelForm): class Meta: model = Document fields = '__all__' exclude = [] **view.py** def createDocument(request): forms = documentForm() if request.method == 'POST': forms = documentForm(request.POST, request.FILES) if forms.is_valid(): forms.save() return redirect('/') context = {'forms':forms} return render(request, 'accounts/document_form.html', context) -
Web socket disconnecting after stablishing a connection
I got a web socket connection that I perform with django channels, my app works perfectly fine in local, but when trying to run it on the vps, the web socket gets disconnected right after stablishing a connection with a 1005 code const socket = new WebSocket('wss://mydomain.com/ws/chat/testing/'); I was sending a message to the backend in socket.onopen() function, but that was not the problem since after commenting that line of code, the connection gets also closed The nginx configuration file looks like this: location /ws/ { proxy_set_header Host $http_host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Host $server_name; proxy_set_header X-Forwarded-Proto $scheme; proxy_set_header X-Url-Scheme $scheme; proxy_redirect off; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection $connection_upgrade; proxy_pass http://127.0.0.1:8115; } Django routing.py: application = ProtocolTypeRouter({ 'websocket':AllowedHostsOriginValidator( AuthMiddlewareStack( URLRouter([ path('chat/testing/', Chat().as_asgi()) ]) ) ) }) Setting.py: CHANNEL_LAYERS = { 'default': { 'BACKEND': 'channels_redis.core.RedisChannelLayer', 'CONFIG': { "hosts": [('127.0.0.1', 6379)], }, }, } I don't know if relevant but when using const socket = new WebSocket('wss://mydomain.com:8115/ws/chat/testing/'); I got a connection failed with code 1006 -
try block is working but except block is not handling error in python
While Handling Python dictionary key error except block is not working but try block is working. Below is my code def catch_empty_key(a): try: return 'aaaa' except : return 'bbbb' def zohoapicall(accesstoken): accesstoken = "" if accesstoken == "": parameters = { "refresh_token":"1000.06f10f49d6f00478887e3820634b928f.c045ff2a9dcb9c99057ec42645bf1e44", "client_id":"1000.UKZQIWVQ2A2THKSZ2126Y7E7CAA8CW", "client_secret":"91d25fbaeea0e81190a681708cd554a1030a9c4547", "redirect_uri":"https://www.google.com", "grant_type":"refresh_token", } response = requests.post("https://accounts.zoho.com/oauth/v2/token?", params=parameters) if response.status_code == 200: data = response.json() accesstoken = data['access_token'] headers = { 'Content-Type':'application/json', 'Authorization':'Zoho-oauthtoken ' + str(accesstoken) } response = requests.get("https://books.zoho.com/api/v3/invoices", headers=headers) if response.status_code == 200: data1 = response.json() data_2=[catch_empty_key(invoice['not_a_key']) for invoice in data1['invoices']] return HttpResponse(data_2, accesstoken) Here in the second last line data_2=[catch_empty_key(invoice['not_a_key']) for invoice in data1['invoices']] except block of catch_empty_key function is not working and it is throwing an error. On the Other hand if I replace second last line with something that is a key of invoice then try block is working and returning aaa as output. for example data_2=[catch_empty_key(invoice['is_a_key']) for invoice in data1['invoices']] I want to understand why this error is coming and how can we solve it? -
Authentication returns None in django rest frame work API
views.py @api_view(['POST']) def login(request): data = {} email = request.data.get('email') password = request.data.get('password') user = authenticate(email = email, password = password) U = User.objects.get(email=email) if user is not None: login(request, user) data['response'] = 'successfully logged in' elif Userprofile.objects.filter(email=email).exists() == False: data['response'] = 'user does not exist' elif U.is_active == False: data['response'] = 'Please verify your email' else: data['response'] = 'invalid password' return JsonResponse(data) otp=random.randint(11111,99999) @api_view(['POST']) def signup(request): serializer = UserprofileSerializer(data=request.data) data = {} if serializer.is_valid(): name = serializer.validated_data['name'] email = serializer.validated_data['email'] phone_number = serializer.validated_data['phone_number'] password = make_password(serializer.validated_data.get('password')) account = Userprofile.objects.create_user(name = name, email = email, phone_number = phone_number, password = password) data['response'] = 'successfully registered a new user' send_mail( 'Welcome to Trycompound', 'Your OTP is '+str(otp), EMAIL_HOST_USER, [email], ) user = User.objects.get(email=email) user.otp = otp user.save() else: data = serializer.errors return JsonResponse(data) I really can'f figure what's wrong because I have actually done these with the normal templates and when i tried it with the django rest framework, I am unable to login because authenticate is returning 'None'. and yes User is active, it says 1 in the database. -
issues with Docker on wsl (ubuntu 22.04)
An attempt to build a docker image fails on RUN pip install -r requirements.txt step with the following error: WARNING: Retrying (Retry(total=4, connect=None, read=None, redirect=None, status=None)) after connection broken by 'ReadTimeoutError("HTTPSConnectionPool(host='pypi.org', port=443): Read timed out. (read timeout=15)")': /simple/asgiref/ WARNING: Retrying (Retry(total=3, connect=None, read=None, redirect=None, status=None)) after connection broken by 'ReadTimeoutError("HTTPSConnectionPool(host='pypi.org', port=443): Read timed out. (read timeout=15)")': /simple/asgiref/ WARNING: Retrying (Retry(total=2, connect=None, read=None, redirect=None, status=None)) after connection broken by 'ReadTimeoutError("HTTPSConnectionPool(host='pypi.org', port=443): Read timed out. (read timeout=15)")': /simple/asgiref/ WARNING: Retrying (Retry(total=1, connect=None, read=None, redirect=None, status=None)) after connection broken by 'ReadTimeoutError("HTTPSConnectionPool(host='pypi.org', port=443): Read timed out. (read timeout=15)")': /simple/asgiref/ for some reason, asgiref==3.5.2 doesn't want to install. What could be the reason for this? System used: OS: Windows 11 WSL 2 with Ubuntu 22.04 on board Docker version 20.10.19, build d85ef84 Dockerfile contents: # Pull base image FROM python:3.10.6-slim-bullseye # Set enviroment variables ENV PIP_DISABLE_PIP_VERSION_CHECK 1 ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 # Set work directory WORKDIR /code # Install dependencies COPY ./requirements.txt . RUN pip install -r requirements.txt # Copy project COPY . . requirements.txt contents: asgiref==3.5.2 Django==4.1.2 sqlparse==0.4.3 -
how to get foreignkey names instead of sql reference number django view
Im trying to build a simple rest api in django. i have a transaction, account and stock table. Each transaction points to 1 account and 1 stock(on seperate tables using foreign keys). im trying to have my api gets the stock ticker for each transaction and not the sql reference number. does anyone know how to get simple views to return values instead of table keys? the serializers im using: class TransactionSerializer(serializers.ModelSerializer): class Meta: model = Transaction fields = "__all__" class StockSerializer(serializers.ModelSerializer): class Meta: model = Stock fields = "__all__" class AccountSerializer(serializers.ModelSerializer): class Meta: model = Account fields = "__all__" the models for transaction and stock: class Stock(models.Model): ticker = models.CharField(max_length=10, unique=True) name = models.CharField(max_length=200) price = models.FloatField() def __str__(self): return self.ticker class Transaction(models.Model): account = models.ForeignKey(Account, on_delete=models.CASCADE) stock = models.ForeignKey(Stock, on_delete=models.CASCADE) amount = models.IntegerField() price = models.FloatField() type = models.CharField(max_length=10) date = models.DateTimeField(auto_now_add=True) def __str__(self): return self.account im leaving out the account/user model but its a mess and half tied into the django base user model the view im using is a basic APIVIEW: class TransactionView(APIView): permission_classes = (IsAuthenticated,) authentication_classes = (JWTAuthentication,) def get(self, request, *args, **kwargs): account = Account.objects.get(email=request.user.email) transactions = Transaction.objects.filter(account=account) serializer = TransactionSerializer(transactions, many=True) return Response(serializer.data) … -
Relative links to admin.py
There is a class in admin.py: class NewsAdmin(TranslationAdmin): form = NewsForm list_display = ('title', 'date' 'show_url') def show_url(self, obj): return format_html("<a href='http://www.host.ru/news/{url}' target='_blank'>view</a>", url=obj.id) show_url.short_description = "View" Need a link http://www.host.ru replace with a relative one, something like this: protocol + domain name + news/{url} How can this be done? -
ModelChoiceFIeld Usage and what to include in queryset?
I cannot seem to figure out why my ModelChoiceField is not working, even after going through the django documentation about ModelForm which confused me despite having successfully relied on them throughout my learning. The error in my code is probably silly, and I apologize for that in advance. The error I get on my terminal when trying to makemigrations is: 'line 429, in getattr raise AttributeError(name) from None AttributeError: objects' forms.py from random import choices from django import forms from .models import Student from students.choices import * class StudentForm(forms.ModelForm): class Meta: model = Student fields = '__all__' #imports all of Student model's fields labels = { 'student_number': 'Student Number', #changes how the attribute names are presented to the user 'first_name': 'First Name', 'last_name': 'Last Name', 'email': 'Email', 'english': 'English', 'math': 'Math', 'language': 'Language', 'science': 'Science', 'ib_predicted': 'Predicted IB Score' } widgets = { 'student_number': forms.NumberInput(attrs={'class': 'form-control'}), 'first_name': forms.TextInput(attrs={'class': 'form-control'}), 'last_name': forms.TextInput(attrs={'class': 'form-control'}), 'email': forms.EmailInput(attrs={'class': 'form-control'}), 'english': forms.ModelChoiceField(queryset=English.choices), 'science': forms.ModelChoiceField(queryset=Science.objects.all()), 'language': forms.ModelChoiceField(queryset=Language.objects.all()), 'math': forms.ModelChoiceField(queryset=Math.objects.all()), 'ib_predicted': forms.NumberInput(attrs={'class': 'form-control'}) } choices.py from unittest.util import _MAX_LENGTH from django.db import models from django.utils.translation import gettext_lazy as _ class English(models.TextChoices): LANGLIT = 'LL', _('Language and literature') LIT = 'L', _('Literature') class Math(models.TextChoices): AA = 'AA', _('Analysis … -
Django Rest Framework Serializer PrimaryKeyRelatedField pass in uuid list
So, I am trying to make a social media application and users can tag other users in their post. class Post(models.Model): author = models.ForeignKey(User, related_name='posts', on_delete=models.CASCADE) caption = models.CharField(max_length=100, null=True, blank=True) id = models.UUIDField(default=uuid.uuid4, unique=True, primary_key=True, editable=False) date_created = models.DateTimeField(auto_now_add=True) date_edited = models.DateTimeField(auto_now=True) allow_comments = models.BooleanField(default=True) archived = models.BooleanField(default=False) media_file_url = models.FileField(upload_to='videos/', validators=[validate_file_extension]) tags = TaggableManager(blank=True, through=TaggedHashtag) mentioned_users = models.ManyToManyField(User, blank=True, through='MentionedUser') class MentionedUser(models.Model): id = models.UUIDField(default=uuid.uuid4, unique=True, primary_key=True, editable=False) date_created = models.DateTimeField(auto_now_add=True) post = models.ForeignKey(Post, on_delete=models.CASCADE) tagged_user = models.ForeignKey(User, on_delete=models.CASCADE) class Meta: unique_together = (('post', 'tagged_user')) ordering = ['date_created'] For serializing the uuids for the mentioned_users, I followed these instructions. Everything works fine, I can submit one uuid correctly like this: But when I try to submit more than one uuids, I get this error: Here is my serializer: class PostSerializer(TaggitSerializer, serializers.ModelSerializer): tags = TagListSerializerField() mentioned_users = serializers.PrimaryKeyRelatedField(many=True, allow_null=True, queryset=User.objects.all(), pk_field=serializers.UUIDField(format='hex')) id = serializers.CharField(read_only=True) class Meta: model = Post fields = [ 'caption', 'allow_comments', 'media_file_url', 'id', 'tags', 'mentioned_users', ] What am I doing wrong here? What is the correct way to submit list of uuids? Also, is the present method I am using efficient, any form of help would be appreciated. Thank You. Also, I tried adding double quotes … -
Django Formset not correctly populating form data
I am trying to set up a page where a Return can be made to an order, with as many ReturnItems as needed. The empty forms for additional ReturnItems are generated by JavaScript passing in the empty form HTML string created by the formset factory. When the forms are properly filled in, it works as expected. However, when I try to submit with multiple ReturnItems forms being empty, the validation of the forms do not work properly. What I don't understand is that even though the request.POST data is correct the 'reason' and 'opened' field are not populated for the forms which causes the forms to be empty and skipped, instead of raising a ValidationError for missing the product name/code. Any help or suggestions would be useful, thanks. Example of request.POST data <QueryDict: {'csrfmiddlewaretoken': ['token'], 'first_name': ['first'], 'last_name': ['last'], 'email': ['e@email.com'], 'telephone': ['12345'], 'order_id': ['123'], 'order_date': ['2022-10-05'], 'form-TOTAL_FORMS': ['2'], 'form-INITIAL_FORMS': ['0'], 'form-MIN_NUM_FORMS': ['1'], 'form-MAX_NUM_FORMS': ['15'], 'form-0-product_name': ['prod1'], 'form-0-product_code': ['code1'], 'form-0-quantity': ['2'], 'form-0-reason': ['1'], 'form-0-opened': ['False'], 'form-1-product_name': ['prod2'], 'form-1-product_code': ['code2'], 'form-1-quantity': ['3'], 'form-1-reason': ['1'], 'form-1-opened': ['False'], 'comment': ['comment']> Views.py def return_view(request): sitekey = settings.H_CAPTCHA_SITEKEY ReturnItemFormSet = formset_factory( ReturnItemForm, extra=0, min_num=1, max_num=15, validate_min=True, absolute_max=15, ) return_form = ReturnForm() return_item_formset = ReturnItemFormSet() empty_form … -
Django: How to use CreateView in one model and at the same time update a field in a second model. (Using a form in templates only)
I couldn't find a direct answer elsewhere. I created a Group Model and a GroupMember Model. My goal is that a user creates a Group via a form in templates, then automatically in the GroupMember model the fields should be filled. In particular the field is_admin should be 1, although its default value is set to 0. How to tell CreateGroupView to fill the GroupMember model? views.py class CreateGroupView(LoginRequiredMixin, CreateView): fields = ("name","description") model = Group class SingleGroupView(DetailView): model = Group class ListGroupView(ListView): model = Group models.py class Group(models.Model): name = models.CharField(max_length=255, unique=True) slug = models.SlugField(allow_unicode=True, unique=True) description = models.TextField(blank=True, default='') members = models.ManyToManyField(User,through="ProjectMember") def __str__(self): return self.name def save(self, *args, **kwargs): self.slug = slugify(self.name) super().save(*args, **kwargs) def get_absolute_url(self): return reverse("groups:single", kwargs={"slug": self.slug}) class GroupMember(models.Model): user = models.ForeignKey(User,related_name='user_groups',on_delete=models.CASCADE,) group = models.ForeignKey(Group, related_name="memberships",on_delete=models.CASCADE,) is_admin = models.BooleanField(default=False) def __str__(self): return self.user.username class Meta: unique_together = ("group", "user") my template to create a Group <form class="m-5" method="POST" action="{% url 'groups:create' %}" id="groupForm"> {% csrf_token %} <div class="form-group"> <label for="id_name">Name</label> <input type="text" name="name" maxlength="255" class="form-control" placeholder="Name" title="" required id="id_name"> </div> <div class="form-group"> <label for="id_description">Description</label> <textarea name="description" cols="40" rows="10" class="form-control" placeholder="Description" title="" id="id_description"></textarea> </div> <input type="submit" value="Create" class="btn btn-primary btn-large"> </form> the urls.py urlpatterns = …