Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Reverse for 'password_reset_confirm' not found. 'password_reset_confirm' is not a valid view function or pattern name. Django-rest-auth
I'm doing the Django password reset but this error always happens and I don't know why Here are the urls: from django.urls import path from . import views from django.contrib.auth import views as auth_views app_name = 'accounts' urlpatterns = [ path('login/', views.login, name="login"), path('registrar/', views.registrar, name="registrar"), path('logout/', views.logout, name="logout"), path('reset/password_reset_confirm/<uidb64>/<token>/', auth_views.PasswordResetConfirmView.as_view(), name='password_reset_confirm'), path('reset/password_reset/', auth_views.PasswordResetView.as_view(), name='password_reset'), path('reset/password_reset_done/', auth_views.PasswordResetDoneView.as_view(), name='password_reset_done'), path('reset/password_reset_complete/', auth_views.PasswordResetCompleteView.as_view(), name='password_reset_complete'), ] Here are my custom pages: my custom pages: And these are the project urls: from django.contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('accounts/', include('accounts.urls')), path('admin/', admin.site.urls), path('', include('home.urls')), path('turmas/', include('turmas.urls')), path('calendario/', include('calendario.urls')), ] if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) -
I it possible to integrate python with CSS, Javascript, and HTML?
I have a frontend web application built with JavaScript, HTML, and CSS. I would like to incorporate the output of a Python script into my frontend without using a server or a full backend solution. The Python script is a simple neural network, and I want to display its output in the frontend, such as showing the result as a header or plotting a graph generated by the script. I have already tried printing the output to the console from the Python script, but I need assistance with transferring that output to the frontend. Is it possible to achieve this without a server? I am open to suggestions and starting with a simpler solution, like plotting a graph generated by the Python script in the frontend. I appreciate any guidance or code examples on how to accomplish this. Thank you! I have looked into Django but I feel as if that seems too complex and more server focused for the simple task I require. -
Why does the matching query does not exist error occur?
There is a model: class ProductRating(models.Model): class Meta: indexes = [ UniqueIndex(fields=['user', 'product']), ] user = models.ForeignKey(User, on_delete=models.CASCADE) product = models.ForeignKey(Product, on_delete=models.CASCADE) grade = models.BooleanField() created_time = models.DateTimeField(auto_now_add=True, verbose_name='created_time') I want to create a row in the database with a post request class PostRatingFromUser(generics.CreateAPIView): queryset = ProductRating.objects.all() permission_classes = [IsAdminOrAuthenticatedUser, ] serializer_class = ProductRatingSerializer def post(self, request, *args, **kwargs): rating_from_db = ProductRating.objects.get(product_id=kwargs['pk'], user=request.user) if rating_from_db: rating_from_db.grade = kwargs['grade'] rating_from_db.save() else: ProductRating.objects.create(product_id=kwargs['pk'], grade=kwargs['grade']).save() return Response(status=200) But before adding, I check if there is such a database, if there is, then I just change the value of 'grade' but it gives me an error: product.models.ProductRating.DoesNotExist: ProductRating matching query does not exist. -
In Django, how can I select an object from the database and pass the parameters not to the url, but in some other better way?
I'm new to Django, in a page i have a combobox which is populated by fields from a database (simply city names). I select an object from the database with parameters which I pass to the url. I know this isn't the cleanest approach and that there is a better way. Is there a better way to populate the combobox without passing database parameters to the url? Then passing the parameters in a different and better way. How could my code take a different approach? models.py from django.db import models class City(models.Model): name = models.CharField(max_length=30) def __str__(self): return self.name forms.py from .models import City class SelectCityForm(forms.Form): city = forms.ModelChoiceField(queryset=City.objects.all()) class Meta: model = City fields = ('name') views.py def city_detail(request): form = CitySelectForm() object = None if request.method == "POST": form = CitySelectForm(request.POST) if form.is_valid(): city_id = form.cleaned_data['city'] object = City.objects.get(id=city_id) context = {'form': form, 'object': object} return render(request, 'app1/home.html', context) home.html <form action="/url-to-city_detail-view/" method="post"> {% csrf_token %} {{ form }} <input type="submit" value="Submit"> </form> urls.py from django.urls import path, include from . import views from app1.views import index from app1 import views urlpatterns = [ path('', index, name='index'), #Aggiunto per combobox path('login/', views.sign_in, name='login'), path('logout/', views.sign_out, name='logout'), path('home/', views.home, … -
Django Error: Question matching query does not exist() Updating Questions and Choices to Primary Keys
I am currently attempting the official Django tutorial polls app. It has asked me to create questions for a poll app and than after that create answer choices. I made a mistake creating the questions and somehow made an empty query set which I believe set the primary key to 1 and 2 respectively for the blank questions. I went on to create questions 3, 4, and 5. I realized the blanks were there an I attempted to delete the two questions. After running the delete() command I removed them. I figured that the primary keys would be removed and everything would slide back into place. My question who invented python remained at pk=3. Now I am wondering what to do. Should I create answer choices off of primary key id 3 and run with it? Or should I find a way to reassign the answer choices. Well, I have asked the Django forums website and someone recommended to me that I run the command `[(q.id, q.question_text) for q in Question.objects.all()]' this command output: >>> [(q.id, q.question_text) for q in Question.objects.all()] [(3, 'Who invented python?'), (4, 'This question was changed by dot notation on the object.'), (5, 'Who invented Django?')] … -
django aggregate a list of dictionaries
I have this situation that I have a queryset with complex relation and i need this kind of data: filters: [{ colors: [{ 'black': '#000000' }, { 'white': '#111111' } ] }, { categories: [{ "Digital": [{ "mobile": [{ 'Apple': ['first_phone', 'second_phone'] }, {'Android': ['first_phone', 'second_phone']} ], }] }] } ] basically for categories its a 3 level children-parent situation. and the reason is i don't want to call my queryset multiple times since its a pretty heavy one. overall this is what i have in mind: queryset.aggregate( colors=ArrayAgg( {F('packs__colors__title'): F("packs__colors__hex_code")}, distinct=True, ), categories=ArrayAgg( { F('categories__title'): { F("categories__parent__title"): { F("categories__parent__parent__title") } } }, distinct=True,) ) for first level its working fine. but how can i make this kind of aggregations? -
Host the GOOGLE_CREDENTIALS on google cloud storage not working
What is the best way of accessing the GOOGLE_CREDENTIALS json file ? I tried hosting it on Google cloud storage and the link is public, but can't work in Django . I am using redner.com as my server. -
Error while signing up with Django (Backend) and Angular (Frontend)
I am encountering an error when trying to create a user from my Angular frontend using my Django backend. I have set up CORS in my backend to allow all origins (allow origin all), but I continue to receive the following errors When I send a POST request to the URL 'http://127.0.0.1:8000/api/users/', I get a "400 (Bad Request)" response in the console. If I remove the '/' from the URL and send the request to 'http://127.0.0.1:8000/api/users', I receive the following error: "Access to XMLHttpRequest at 'http://127.0.0.1:8000/api/users' from origin 'http://localhost:4200/' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: Redirect is not allowed for a preflight request." I have already installed and configured the CORS package in my Django backend to allow access from all origins. Despite this, the error persists. Here are some additional details: Django version: v4.1.7 Angular version: v15 CORS configuration in my Django backend (code snippet): enter image description here I am stuck and unsure how to resolve this issue. Any help would be greatly appreciated. Thank you very much! -
Python & MimeTypes: Parsing Email Body & Data in a multipart email
I am working on a python script (with BeautifulSoup) that reads emails through a Gmail service account. I can successfully read through the mailparts for an email sent from Gmail and identify the "data" part to read through and find a keyword in the text or HTML. However, I am having issues reading through any email sent from an apple device. I assume I will encounter other email clients issues too. I'm wondering how apple mail clients structure their email parts. Ultimately, I must find the "data" part in the body of the email. Here is the portion fo the script causing my issue: def parse_parts(self, part): mimeType = part['mimeType'] body = "" if mimeType == "text/plain" or mimeType == "text/html": data = part['body']["data"] data = data.replace("-","+").replace("_","/") decoded_data = base64.b64decode(data) soup = BeautifulSoup(decoded_data , "lxml") body = soup.get_text() return body -
Why is my console shows the coding of my html file?
I was able to use the quantity increment but i accidentally undo my work and it turns out like this someone help me please >:( the console print out my base.html coding and does not increase the quantity (base.html) <!DOCTYPE html> <html lang="en"> {% load static %} <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.1/dist/css/bootstrap.min.css"> <script src="https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js"></script> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-9ndCyUaIbzAi2FUVXJi0CjmCapSmO7SnpJef0486qhLnuZ2cdeRhO02iuK6FUUVM" crossorigin="anonymous"> <script type="module" src="https://unpkg.com/ionicons@5.5.2/dist/ionicons/ionicons.esm.js"></script> <script nomodule src="https://unpkg.com/ionicons@5.5.2/dist/ionicons/ionicons.js"></script> <title>Python World</title> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css"> <style> nav{ background-color: white; } .one-edge-shadow { box-shadow: 0 8px 2px -5px rgb(246, 245, 245); } .display-8{ font-weight: 200; font-size: 30px; } .badge { padding-left: 9px; padding-right: 9px; -webkit-border-radius: 9px; -moz-border-radius: 9px; border-radius: 9px; } .label-warning[href], .badge-warning[href] { background-color: #c67605; } #lblCartCount { font-size: 15px; background: #ff0000; color: #fff; padding: 0 5px; vertical-align: top; margin-left: -17px; } .btn-circle.btn-sm { width: 25px; height: 25px; padding: 7px; border-radius: 14px; font-size: 12px; text-align: center; font-weight: bold; } </style> <script> function cartpage() { window.location.href="{% url 'cartpage' %}" } </script> </head> <body> <!-- navbar --> <nav class="one-edge-shadow sticky-top navbar navbar-expand-lg navbar navbar-dark bg-primary"> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarSupportedContent"> <ul … -
How to best model a tree of generic content types in Django?
I have a Django API for managing a bunch of content related to D&D campaigns: characters, locations, factions, quests, etc. Until now the frontend has always displayed these types of content in their own tabs, so a list of characters, another list of locations, and within a tab content can be nested: locations can have sub-locations, but they are all in their own "silo". class Location(models.Model): name = models.CharField(max_length=255) subtitle = models.CharField(max_length=255, blank=True) text = models.TextField(blank=True) icon = models.CharField(max_length=255, default="map-location-dot") parent = models.ForeignKey("self", on_delete=models.SET_NULL, blank=True, null=True) campaign = models.ForeignKey(Campaign, on_delete=models.CASCADE, editable=False) I am thinking about turning the frontend into one nested tree of all content types: so a location could have nested factions, which could have nested characters, and so on, totally free-form. I'm not really sure how to best model this in the database. One idea I have is to create a brand new model that contains the tree, with generic relations to content items via the contenttypes framework from Django. class Tree(models.Model): content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.PositiveIntegerField() content_object = GenericForeignKey("content_type", "object_id") parent_content_type = models.ForeignKey(ContentType, null=True, on_delete=models.CASCADE) parent_object_id = models.PositiveIntegerField(null=True) parent_content_object = GenericForeignKey("content_type", "object_id") order = models.PositiveIntegerField() campaign = models.ForeignKey(Campaign, on_delete=models.CASCADE, editable=False) That would work (although I … -
Cannot add <Image> instance is on database "default", value is on database "None"
I'm developing and app in Django, and I'm getting this error when my form y submitted, the problem is given when it try to add images on the relationship ManyToMany. Internal Server Error: /publish_offer/ Traceback (most recent call last): File "C:\Users\G-FIVE\Desktop\Projects\revenue\venv\Lib\site-packages\django\core\handlers\exception.py", line 55, in inner response = get_response(request) ^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\G-FIVE\Desktop\Projects\revenue\venv\Lib\site-packages\django\core\handlers\base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\G-FIVE\Desktop\Projects\revenue\venv\Lib\site-packages\django\contrib\auth\decorators.py", line 23, in _wrapper_view return view_func(request, *args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "D:\Projects\revenue\management\views.py", line 49, in publish_offer oferta.imagenes.add(*imgs) File "C:\Users\G-FIVE\Desktop\Projects\revenue\venv\Lib\site-packages\django\db\models\fields\related_descriptors.py", line 1137, in add self._add_items( File "C:\Users\G-FIVE\Desktop\Projects\revenue\venv\Lib\site-packages\django\db\models\fields\related_descriptors.py", line 1397, in _add_items target_ids = self._get_target_ids(target_field_name, objs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\G-FIVE\Desktop\Projects\revenue\venv\Lib\site-packages\django\db\models\fields\related_descriptors.py", line 1313, in _get_target_ids raise ValueError( ValueError: Cannot add "<ImagenesOferta: ImagenesOferta object (None)>": instance is on database "default", value is on database "None" [29/Jun/2023 16:10:20] "POST /publish_offer/ HTTP/1.1" 500 87580 This is my models: class ImagenesOferta(models.Model): imagen = models.ImageField(verbose_name='Imagen Oferta', blank=False, null=False, upload_to='img_ofertas/') class Meta: verbose_name = 'Imagen de Oferta' verbose_name_plural = 'Imagenes de Ofertas' ordering = ['-id'] class Oferta(models.Model): titulo = models.CharField(verbose_name='Título', max_length=100, null=False, blank=False) descripcion = models.TextField(verbose_name='Descripción', null=True, blank=True) cantidad = models.PositiveSmallIntegerField(verbose_name='Cantidad', null=False, blank=False, default=1) valor = models.DecimalField(verbose_name='Valor', max_digits=4, decimal_places=2, null=False, blank=False) material = models.CharField(verbose_name='Material', max_length=20, null=False, blank=False, choices=MATERIAL_CHOICES) imagenes = models.ManyToManyField(ImagenesOferta, verbose_name='Imagenes de la Oferta', blank=True) usuario = … -
How to access WSGIRequest multiple times?
I have an APIView that calls another APIView for check purpose, But after hours of searching I know now that it's not easy to access HttpRequest after turn into stream object and will cause the below error: django.http.request.RawPostDataException: You cannot access body after reading from request's data stream some are suggest to use request.data not request.body but I can't do it in such case: B.views.py from rest_framework import views from rest_framework.response import Response from A.views import A class B(views.APIView): def post(self, request, *args, **kwargs): http_response = A.as_view()(request._request) # So far so good, but if I want to access request.data after calling A.as_view() will raise # the exception. return Response(http_response.data) How to deal with this issue? source: issue2774 -
create constance django from model list
I need to implement functionality when only one user of users Model can has 'editor-role' I will use this constant in my drf api. So I need to create some django constant with one user id, and dropdown menu of all users in my django admin panel. How can I do it? I choose django-constant, but faced with the problem that list of model data couldn't init in settings py: CONSTANCE_BACKEND = 'constance.backends.database.DatabaseBackend' CONSTANCE_ADDITIONAL_FIELDS = { 'users_select': ['django.forms.fields.ChoiceField', { 'widget': 'django.forms.Select', 'choices': ( (None, "-----"), User.objects.all().split(",")) ) }], } CONSTANCE_CONFIG = { 'DEFAULT_USER': ('', 'default user', 'users_select'), } Any another ideas how to implement this functionality? -
Django hide media files link for certain people
I programmed a function where you can download a file from the media folder with the media files depending on the link. The problem is that if you change the path in the link you have access to all the media files and not just the ones you are supposed to download. Can I somehow ban the other links (with a permission or something) or is there a clever way to solve the whole thing? -
Is `pytz` deprecated now or in the future in Python?
pytz is used in the Django version: <=3.2 doc Selecting the current time zone as shown below: import pytz # Here from django.utils import timezone class TimezoneMiddleware: def __init__(self, get_response): self.get_response = get_response def __call__(self, request): tzname = request.session.get('django_timezone') if tzname: timezone.activate(pytz.timezone(tzname)) else: timezone.deactivate() return self.get_response(request) But, zoneinfo is used instead of pytz in the Django version: 4.0<= doc Selecting the current time zone as shown below: import zoneinfo # Here from django.utils import timezone class TimezoneMiddleware: def __init__(self, get_response): self.get_response = get_response def __call__(self, request): tzname = request.session.get('django_timezone') if tzname: timezone.activate(zoneinfo.ZoneInfo(tzname)) else: timezone.deactivate() return self.get_response(request) My questions: Is pytz deprecated now or in the future in Python? Why isn't pytz used in the Django version: 4.0<= doc Selecting the current time zone? -
Django form saves only the last row, times the number of records in the form
I have a form which saves data. The problem is, only the last row of the form gets saved, multiplied by the number of records that appear in the form. I have a feeling that only the last data row is being passed, and it is being looped through. However, for the life of me, I just cannot figure this out. Thanks in advance for help. Here is the relevant code: Model: class MonthlySheet(models.Model): employeename = models.ForeignKey(Employees, on_delete=models.CASCADE, related_name='monthlysheets') uan = models.CharField(max_length=12) ip = models.CharField(max_length=15) epfowages = models.IntegerField() esicwages = models.IntegerField() twelve_percent = models.IntegerField() eight_three_three_percent = models.IntegerField() difference = models.IntegerField() working_days = models.IntegerField() ncp = models.IntegerField() zero_point_seven_five_percent = models.IntegerField() Form: class MonthlySheetForm(forms.Form): print("Starting monthlysheetform class validation") employeename_id = forms.IntegerField(required=True) establishmentid = forms.IntegerField(required=True) uan=forms.CharField(required=True) ip=forms.CharField(required=True) epfowages = forms.IntegerField(required=True) esicwages = forms.IntegerField(required=True) twelve_percent = forms.IntegerField(required=True) eight_three_three_percent = forms.IntegerField(required=True) difference = forms.IntegerField(required=True) working_days = forms.IntegerField(required=True) ncp = forms.IntegerField(required=True) zero_point_seven_five_percent = forms.IntegerField(required=True) def clean(self): print("Cleanse starting in MonthlySheetForm") cleaned_data = super().clean() epfowages = cleaned_data.get('epfowages') esicwages = cleaned_data.get('esicwages') establishmentid = cleaned_data.get('establishmentid') employeename_id = cleaned_data.get('employeename_id') return cleaned_data View: def add_monthlysheet(request): assert isinstance(request, HttpRequest) establishments = Establishment.objects.all() employees = [] establishmentname = request.session.get('establishmentname', '') establishment_id = '' # Set initial value for establishment_id monthlysheet = MonthlySheet.objects.all() if … -
What is the best way to save comma separated keywords posted from client side into database table using Django?
I have a text area input on a simple HTML page, where I am posting comma-separated keywords to save into my database table. For example, Keywords input is like: keyword1,keyword2,keyword3, ... I am using Django 3.2 and Tastypie as a API framework. Here is my Django model: class Keywords(models.Model): keyword = models.CharField(max_length=200, unique=True) class Meta: db_table = 'keywords' And Tastypie resource: class KeywordResource(ModelResource): class Meta(CommonMeta): queryset = Keywords.objects.all() resource_name = 'keyword-resource' filtering = {'id': ALL, 'keyword': ALL} allowed_methods = ['get', 'post', 'put', 'patch'] I want to save the comma-separated keyword in one post request from the client side. How can I post comma-separated keywords and insert them one by one into the table Keywords? Also, what would be the best way to use save() method from model or hydrate() method from tastypie resource to prepare the data to save? -
Django don't manually change the URL and go to the index.html page
I am new to Django. Let's assume my project name is mysite, and I have one app called Polls. I have 2 html in the templates file: "index.html", "df.html" Now, when I runserver, I have to manually change the URL, add "polls" after "http://127.0.0.1:8000/" to show the index.html, but I want when I click the link in the terminal, it can direct me to the index.html. I don't need to manually change the URL Thank you and any help if really appreciated! views.py def index(request): xxxx return render (request,"index.html") polls\urls.py from django.urls import path from . import views urlpatterns = [ path('', views.index, name='index'), ] mysite\urls.py from django.contrib import admin from django.urls import include, path from polls import views urlpatterns = [ path('polls/', include('polls.urls')), path('df/', views.df_show) ] -
Simple html form in Django
Could you please help me, I don't understand why html+css don't work as expected in Django. I use a simple form to upload two files, but it looks really ugly. index.html without id="upload_container" <div class="page_thirdblock thirdblock"> <div class="thirdblock__container _container"> <form method="POST" enctype="multipart/form-data" class="upload1"> {% csrf_token %} <input type="file" name="upload_file"> <input type="hidden" name="form_type" value="form_1"> <button type="submit">Upload File 1</button> </form> <form method="POST" enctype="multipart/form-data" class="upload2"> {% csrf_token %} <input type="file" name="upload_file"> <input type="hidden" name="form_type" value="form_2"> <button type="submit">Upload File 2</button> </form> </div> </div> index.html with id="upload_container" <div class="page_thirdblock thirdblock"> <div class="thirdblock__container _container"> <form method="POST" enctype="multipart/form-data" class="upload1" id="upload_container"> {% csrf_token %} <input type="file" name="upload_file"> <input type="hidden" name="form_type" value="form_1"> <button type="submit">Upload File 1</button> </form> <form method="POST" enctype="multipart/form-data" class="upload2" id="upload_container"> {% csrf_token %} <input type="file" name="upload_file"> <input type="hidden" name="form_type" value="form_2"> <button type="submit">Upload File 2</button> </form> </div> </div> How I can fix it? I mean get Browse... button, but with css style. -
Django Channels AsyncHTTPConsumer example
Title says it all. For the love of god, is there an example where there are routes both for 'http' and 'websocket' protocols? I'm simply trying to have (along with classic django channels websockets) an async download, and setup my asgi configuration for it, but I can't find any examples on the internet, let alone the documentation, how to have them both. It shouldn't be much of an ask, but it seems that it is. -
Forbidden (403) CSRF verification failed. Request aborted. with Gunicorn
I've created a form that includes the {% csrf_token %} but every time I submit the form it refuses it due to my domain not coming from a trusted origin. I set CSRF_TRUSTED_ORIGIN = "https://proj.com" and I even tried using @csrf_exempt to see if that would get rid of the problem but it still didn't work, the form still isn't submitting. I am using gunicorn with my django project and PostgreSQL for my database. -
django: update html dynamically when model is updated
There is a Status model with instances saved in the database. There is a view generating the html code that displays these instances to the client. Another process updates the values of the fields of these instances ('updates': read the instance from the database, change the values of some of the fields, and save the instances back to the database). I would like the html report currently displayed to the client to be updated 'live' everytime the database has been updated. I searched, but I am failing to determine the canonical way of doing this. It feels like I should use things like channels, data binding, WebsocketBinding. But the documentation (https://channels.readthedocs.io/en/1.x/binding.html) is quite difficult to follow for a beginner and I could not find any example that would help me start. It would be great, and possibly useful to many, to have a minimal example of this (not necessarily using WebsocketBinding if there are better ways of doing this) -
How can I change form field population *after* successful POST request for Class-Based-Views
I want to change the forms initial field population. Here is the catch: I want to change it for the POST request and not for the GET request. Let's say my app offers a calculation based on a body weight input. If the user inputs a body weight calculation happens with that weight, if not a default of 50 is used. So it is allowed to let the field empty. But after the calculation ran, I want to display that the value used for calculation was 50. That's why I want to populate the field with 50 after the form was initially submitted with an empty value. # forms.py class CalculatorForm(forms.Form): body_weight = forms.FloatField(required=False) def clean(self): cleaned_data = super().clean() if cleaned_data['body_weight'] is None: cleaned_data['body_weight'] = 50.0 # ideally I want to put the logic here # self.data[bpka] = 50.0 --> AttributeError: This QueryDict instance is immutable # self.fields['body_weight'] = 50.0 --> does not work # self.initial.update({'body_weight': 50.0}) --> does not work return cleaned_data I feel like the problem is that I can not reach the bound fields from the clean() method. If it is not possible within the form the logic has to go to the view I guess. Feel … -
no such table: api_user
I used from django.contrib.auth.models import User before, but now I need to switch to AbstractUser. How can I transfer the data from the previous auth_user table to AbstractUser? I followed the code from here. models.py from django.db import models from django.contrib.auth.models import AbstractUser class User(AbstractUser): username = models.CharField(max_length=50, unique=True) email = models.CharField(max_length=100) password = models.CharField(max_length=100) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] serializers.py from .models import User from rest_framework import serializers class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ['username', 'email', 'password'] extra_kwargs = { 'password': {'write_only': True} # Don't return password } def create(self, validated_data): # Hash password password = validated_data.pop('password', None) instance = self.Meta.model(**validated_data) if password is not None: instance.set_password(password) instance.save() return instance When I login to admin pages I get : no such talbe: api_user I want to use AbstractUser instead without deleting the auth_user table.