Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Invalid password format or unknown hashing algorithm. Raw passwords are not stored. Django
I have a signup code views.py: def signup(req): if req.method == 'POST': form = SignupForm(req.POST) if form.is_valid(): form.save() return redirect('/') form = SignupForm() return render(req,'signup.html',{'form':form}) forms.py class SignupForm(forms.ModelForm): class Meta: model = User fields = ['username', 'email', 'password','first_name','last_name'] now whenever I try to login with this code the submission is successful but when I go to the admin panel and click on the user, on the password section it says Password: Invalid password format or unknown hashing algorithm. Raw passwords are not stored, so there is no way to see this user’s password, but you can change the password using http://localhost/admin/auth/user/3/password/. -
How do I make a serializer for many to many relationships in django if one model is a proxy model?
I have a project with multiple types of users: admins, drivers and commuters. I made proxy models for the drivers class User(AbstractBaseUser, PermissionsMixin): name = models.CharField(max_length=200) email = models.EmailField(unique=True, null=True) phone_number = models.CharField(max_length=15, unique=True) password = models.CharField(max_length=50) class Role(models.TextChoices): ADMIN = "ADMIN", 'Admin' COMMUTER = "COMMUTER", "Commuter" DRIVER = "DRIVER", 'Driver' base_role= Role.ADMIN role = models.CharField(max_length=50, choices=Role.choices) def save(self, *args, **kwargs): if not self.pk: self.role = self.base_role return super().save(*args, **kwargs) def __str__(self): return self.name I want to create a Vehicle model with a many to many relationship with only the drivers and also make serializers to allow me to link instances of drivers to vehicles and also list out all drivers and the vehicles they use. How do I go about this? -
error_css_class doesnt apply to django form
I have a form with one variable 'var1': class MyForm(forms.Form): error_css_class='error' var1=forms.IntegerField(label='var1',widget=forms.NumberInput(attrs={'id':'id_var1', 'name':'var1')) def clean_var1(self): var1=self.cleaned_data.get("var1") if var1 == 2: raise forms.ValidationError('cant be 2!') return var1 and styled the error message: <style> .errorlist { list-style-type: none; padding: 0; margin: 0; } .errorlist li { /* Style each error message */ color: red; } .error { /* the label of the field */ color:red; } .error input{ /* the text field */ border: 2px solid red; } </style> When i render the form using {{form.as_p}} everything works correctly, but when i render it manualy like this <form method="post"> {% csrf_token %} <div> <P>{{ form.var1.label_tag }} {{ form.var1 }} {{ form.var1.errors }}</P> </div> <button type="submit", name="calculate">Submit</button> </form> the class "error" isnt applied to the fields. I want to add stuff bewteen the field so using {{form.as_p}} isnt an option. thanks for the help -
Django annotate by first object from m2o or m2m field
I have 3 models: class Ban: name: models.CharField() person: models.ForeignKey(to="apps.Person") class Employee: name: models.Charfield() person: models.ForeignKey(to="apps.Person") class Person: name: models.Charfield() # here a have access to Ban and Employee as self.ban_set, self.employee_set I can get all Employee objects from Ban object as: ban_object.person.employee_set I need annotate Ban queryset by Employee first object from Ban "person.employee_set" field. I try do this by: employees = Employee.objects.filter(person_id=OuterRef("person_id")) qs = Ban.objects.annotate( employee=Subquery(employees[:1]) ) But I get error: "Cannot resolve expression type, unknown output_field" If I set output_field as models.ForeignKey() for Subquery or annotate, nothing working too -
Django concurrency bug handling
I have an API written in Django that provides user with the list of files that they have. There is also a delete API that can delete a File that the user has. However, there is a bug where a GET request after a deletion still shows the previously deleted object. The GET API uses a filter query on the Files object. While the DELETE API will delete a given file id from the list, by getting and calling .delete(). After googling around, it seems like I need to wrap the database queries into a transaction.atomic block and perform select_for_update() in both of the APIs. Will this solve the issue? By right, if the GET Request is done after receiving the DELETE response it should not ever have this concurrency bug right ? It is only if we sent the requests concurrently. But, select_for_update is locking the database row right? So, will the GET API be able to still read the currently being deleted row? Is this the correct way of handling, or do I need to somehow change the isolation level of the database. Currently the DB is Postgresql which defaults to "Repeatable Read". After reading around, this is … -
Django PostgreSQL - Indexes on JsonField vs. custom fields
I am working on a booking system on Django with the following context: Users can create Items for others to book They can further specify the 'available time' per weekday (mon-sun), i.e. opening_time & closing_time. We can also expect that: A. most users adopt the same 'default' values across 7 weekdays (i.e. override when necessary), and B. most users adopt the same default values, say 8am-10pm. A search on Items by its availability, e.g. "Monday 3-4pm", will be expected and of considerably high traffic, so query performance is a must. I have a few options in mind but cannot decide which is better: Option A: Default values + JsonField + index from django.db import models from django.contrib.postgres.fields import JSONField class Item(models.Model): opening_time = models.TimeField() closing_time = models.TimeField() override = JsonField() class Meta: indexes = [ models.Index(models.F("override__sun_open"), name="override__sun_open"), models.Index(models.F("override__sun_close"), name="override__sun_close"), ... ] The Json will 'override' if necessary - might look something like {'sun_open': 07:00, 'sun_close': 23:00}. The filter() will be more complicated but can save on storage (given most users will use the defaults). Option B: JsonField + index class Item(models.Model): available = JsonField() class Meta: indexes = [ models.Index(models.F("available__sun_open"), name="available__sun_open"), models.Index(models.F("available__sun_close"), name="available__sun_close"), ... ] The query will be easy … -
Django not able display the pdf file from Amazon S3, but able to upload to the amazon S3
i am trying to display my pdf list that had upload to the amazon S3, and i had make sure the connection between django and amazon S3 is correct, cause i am able to upload pdf file to S3 by using admin interface. Currently i am trying to display the list of file that had upload to S3 in a table. I had try to display the pdf file list from S3 and nothing show, but the print statement is able to show when i select the Link of "View PDF List", but no data is displaying at the table that should be display. Now the table is just empty and notthing will be display on the table. i had try looking out, did not find something i think it will help me. demo of the table. (https://i.stack.imgur.com/UVAbi.png) following is my code. views.py views.py def upload_pdf(request): if request.method == 'POST': form = PDFDocumentForm(request.POST, request.FILES) if form.is_valid(): pdf_doc = form.save(commit=False) # Upload the PDF file to S3 s3 = boto3.client('s3') pdf_file = request.FILES['pdf_file'] s3.upload_fileobj(pdf_file, settings.AWS_STORAGE_BUCKET_NAME, f'pdfs/{pdf_file.name}') # Set the S3 URL for the PDF file pdf_doc.pdf_file.name = f'pdfs/{pdf_file.name}' pdf_doc.save() return redirect('pdf_list') else: form = PDFDocumentForm() return render(request, 'customPage/uploadPage.html', {'form': form}) def … -
Django On Delete IntegrityError
I get an integrity Error on deleting a Company. See this code below class Company(models.Model): name = models.CharField(max_length=500, null=True, db_index=True) code = models.CharField(max_length=50, null=True, db_index=True) fmp_code = models.CharField(max_length=50, null=True) stock_exchange = models.ForeignKey(Exchange, on_delete=models.CASCADE) exchange = models.CharField(max_length=50, null=True) class CalculationYearlyGrowth(models.Model): company = models.ForeignKey(Company, on_delete=models.CASCADE) date = models.DateField() current = models.BooleanField(default=False, db_index=True) historical_data = models.ForeignKey(CalculatedHistoricalFundamental, on_delete=models.CASCADE) This is the error I got django.db.utils.IntegrityError: update or delete on table "company_company" violates foreign key constraint "company_calculationy_company_id_c31e6552_fk_company_c" on table "company_calculationyearlygrowth" DETAIL: Key (id)=(308248) is still referenced from table "company_calculationyearlygrowth". So every time I want to delete a company and wherever it has foreign relations, I first have to delete CalculationYearlyGrowth of that company manually and I can't delete the Company. I have seen some other questions related to this but None have worked for me and the error itself is confusing since I have a Cascade delete so I don't expect the error to come. Thanks -
Django many-to-many fields and ModelForms
I am now working on a system that is calculating the CO2 emissions of a building. The thresholds are calculated taking into consideration the building type and the area of it. One building can have more building types and each building type has its area which in the end compose the gross area of the building (total area). What I am trying to do is when the user adds a building for calculation they will add the building information and for each building type the area of the it, the total area of the building is not important for now, but I am thinking on calculating it from the sum of the areas of the building types. Here is the models.py file: class BuildingType(models.Model): type = models.CharField(max_length=255, blank=True, null=True) co2_factor = models.DecimalField(max_digits=15, decimal_places=7, blank=True, null=True) class Building(models.Model): bbl = models.CharField(max_length=10, blank=True, null=True, unique=True) area = models.DecimalField(max_digits=10, decimal_places=2, blank=True, null=True) electricity = models.DecimalField(max_digits=10, decimal_places=2, blank=True, null=True) natural_gas = models.DecimalField(max_digits=10, decimal_places=2, blank=True, null=True) building_type = models.ManyToManyField(BuildingType, through='BuildingTypeSize', blank=True, null=True) class BuildingTypeSize(models.Model): building = models.ForeignKey(Building, on_delete=models.CASCADE) building_type = models.ForeignKey(BuildingType, on_delete=models.CASCADE) area = models.DecimalField(max_digits=10, decimal_places=2, blank=True, null=True) I am fairly new to Python and Django, i tried following some tutorials and also the documentation. … -
Django: How to convert "1 day, 1:00:09" in "HH:MM:SS" format
I have time in seconds. To convert it into the "HH:MM: SS" format used hour = forDuration.strftime('%H:%M:%S', forDuration.gmtime(seconds)) but I got this value: 1 day, 1:00:09. Are there any other options to get an hour in this format "HH:MM: SS" -
Expense Sharing api using DRF
I am creating an API which user can add expense in group. Imagine that we have 3 user in a group. User 1 add two expense with amount 90 and 210, and user 3 add an expense with amount 30. So basically when i see the group as User 1 i only should see Who do I owe and who owes me. it means i should see ( User2 owes you 100 and User3 owes you 90 ). first problem is i dont know how to calculate the 90 because user 3 had expense with amount 30 it means user3 owes user 1 100 but with the expense he paid, it will reduce his part from his balance. my main problem is in calculate settlements between 2 users amoung group. class GroupRetrieveView(generics.RetrieveAPIView): queryset = Group.objects.all() serializer_class = GroupSerializer permission_classes = [permissions.IsAuthenticated] def calculate_balance(self, pk): try: group = Group.objects.get(pk = pk) except group.DoesNotExists: return Response({'Error':'Group not found !'}, status=status.HTTP_404_NOT_FOUND) expenses = Expense.objects.filter(group = group) summary = defaultdict(Decimal) for expense in expenses: payer = expense.paid_by.username participants = expense.group.members.all() amount = Decimal(expense.amount) len_participants = participants.count() if len_participants > 0: # payment = amount - share share = amount / len_participants for participant in … -
ArrayField is empty even after serializer.save() (Django and Postgres)
I'm trying to save an existing Python list to an ArrayField in Postgres, but when saved it ends up empty. When I print data['questions'] and data['sources'], they both print a populated list (ex. [question1, question2, question3]), but when I print serializer.data, it shows as: 'sources': [] and 'questions': [] data['conversation']['bot'] works correctly. Hence, the problem might be in the model setup, but I'm unable to figure out what's wrong. I have run py manage.py runserver to migrate changes already but the lists are still empty. Here's the excerpt from views.py: def histories(request): if(request.method == 'POST'): data = JSONParser().parse(request) serializer = HistorySerializer(data=data) if(serializer.is_valid()): result = some_python_dictionary data['conversation']['bot'] = result['answer'] data['sources'] = result['sources'] data['questions'] = result['questions'] serializer.save() return JsonResponse(serializer.data, status=201) models.py from django.db import models import json from django.contrib.postgres.fields import ArrayField # Create your models here. class History(models.Model): conversation = models.JSONField() sources = ArrayField(models.CharField(max_length=256), default=list) questions = ArrayField(models.CharField(max_length=256),size=3, default=list) created_at = models.DateTimeField(auto_now_add=True) def __str__(self): return json.dumps(self.conversation) class Meta: verbose_name_plural = "Histories" serializers.py from rest_framework import routers, serializers, viewsets from .models import History class HistorySerializer(serializers.HyperlinkedModelSerializer): class Meta: model = History fields = ['conversation', 'sources', 'questions', 'created_at'] -
Google Places API returns diferent street number which was given in auto complete
Something wierd starts to happens with Google Places API. I am working on a Python Django app but Google Places API is returning diferent street number in it queries. I search a street name and number "Rua Augusta, 300": But after selecting it the response cames with other number options instead of the choosen one. Does anyone knows what could be happening? It does happens with other addresses even where I live in. :-) Thank you very much! -
pipenv install ERROR: Couldn't install package: {}
I am trying to run a pipenv install command on my ubuntu 22.04 wsl and keep getting this error. I have looked up online and didn't find anything useful. Does anyone knows how to solve it? First, I run pip3 install pipenv succesfully. After running pipenv install I get the following: Installing dependencies from Pipfile.lock (ccbde9)... [pipenv.exceptions.InstallError]: Collecting mysqlclient==2.2.0 (from -r /tmp/pipenv-nctfx03x-requirements/pipenv-zco7ngoc-hashed-reqs.txt (line 1)) [pipenv.exceptions.InstallError]: Using cached mysqlclient-2.2.0.tar.gz (89 kB) [pipenv.exceptions.InstallError]: Installing build dependencies: started [pipenv.exceptions.InstallError]: Installing build dependencies: finished with status 'done' [pipenv.exceptions.InstallError]: Getting requirements to build wheel: started [pipenv.exceptions.InstallError]: Getting requirements to build wheel: finished with status 'error' [pipenv.exceptions.InstallError]: error: subprocess-exited-with-error [pipenv.exceptions.InstallError]: [pipenv.exceptions.InstallError]: × Getting requirements to build wheel did not run successfully. [pipenv.exceptions.InstallError]: │ exit code: 1 [pipenv.exceptions.InstallError]: ╰─> [24 lines of output] [pipenv.exceptions.InstallError]: /bin/sh: 1: pkg-config: not found [pipenv.exceptions.InstallError]: /bin/sh: 1: pkg-config: not found [pipenv.exceptions.InstallError]: Trying pkg-config --exists mysqlclient [pipenv.exceptions.InstallError]: Command 'pkg-config --exists mysqlclient' returned non-zero exit status 127. [pipenv.exceptions.InstallError]: Trying pkg-config --exists mariadb [pipenv.exceptions.InstallError]: Command 'pkg-config --exists mariadb' returned non-zero exit status 127. [pipenv.exceptions.InstallError]: Traceback (most recent call last): [pipenv.exceptions.InstallError]: File "/home/naluh/.local/share/virtualenvs/Otimizador_de_Calendario-e6nrz_ZD/lib/python3.10/site-packages/pipenv/patched/pip/_vendor/pyproject_hooks/_in_process/_in_process.py", line 353, in <module> [pipenv.exceptions.InstallError]: main() [pipenv.exceptions.InstallError]: File "/home/naluh/.local/share/virtualenvs/Otimizador_de_Calendario-e6nrz_ZD/lib/python3.10/site-packages/pipenv/patched/pip/_vendor/pyproject_hooks/_in_process/_in_process.py", line 335, in main [pipenv.exceptions.InstallError]: json_out['return_val'] = hook(**hook_input['kwargs']) [pipenv.exceptions.InstallError]: File "/home/naluh/.local/share/virtualenvs/Otimizador_de_Calendario-e6nrz_ZD/lib/python3.10/site-packages/pipenv/patched/pip/_vendor/pyproject_hooks/_in_process/_in_process.py", line 118, in … -
Row size too large error in django after changing charfields to textfields
I have change my database from postgresql to mysql and i got this error : django.db.utils.OperationalError: (1118, 'Row size too large. The maximum row size for the used table type, not counting BLOBs, is 65535. This includes storage overhead, check the manual. You have to change some columns to TEXT or BLOBs') Before that i had to change all charfields to textfields because of another error ! And now I have this error! i am using RichTextField from ckeditor , do you think this may be the problem? -
django-filter compose filtered url
I'm using django-filter and I would like to link to the view with a pre-set filter. At this time, I'm doing like this: <a href='{{ url "order_list" }}/?year=2023'> or urlnext = ( reverse('order_list') + "?year=2023" ) return HttpResponseRedirect(urlnext) I would like to know if exists a more elegant approach. Thanks -
Create an exe file from a Django project with pyinstaller
I have a problem with generating an .exe file from a Django project using PyInstaller. My goal is to start the Django development server and open the web browser to the homepage by running the file. For this purpose, I have created a file (start.py) that is supposed to start the server: import os import time import webbrowser from django.core.management import execute_from_command_line os.environ.setdefault("DJANGO_SETTINGS_MODULE", "django_test.settings") def run_server(): execute_from_command_line(["manage.py", "runserver"]) if __name__ == "__main__": run_server() I create the exe file using PyInstaller: pyinstaller start.py --onefile When I run the exe file (./dist/start), I get the following error: Traceback (most recent call last): File "start.py", line 19, in <module> run_server() File "start.py", line 16, in run_server execute_from_command_line(["manage.py", "runserver"]) File "django/core/management/__init__.py", line 442, in execute_from_command_line File "django/core/management/__init__.py", line 436, in execute File "django/core/management/base.py", line 412, in run_from_argv File "django/core/management/commands/runserver.py", line 74, in execute File "django/core/management/base.py", line 458, in execute File "django/core/management/commands/runserver.py", line 111, in handle File "django/core/management/commands/runserver.py", line 118, in run File "django/utils/autoreload.py", line 673, in run_with_reloader File "PyInstaller/hooks/rthooks/pyi_rth_django.py", line 24, in _restart_with_reloader File "django/utils/autoreload.py", line 272, in restart_with_reloader File "django/utils/autoreload.py", line 229, in get_child_arguments IndexError: list index out of range When I run the start.py file, the server can be started without any … -
Integrating my Django REST API based extension into OpenedX container
I made a django extension according to these details:"Stand up an instance of Open edX using either the Dockerized Tutor release or our https://gallery.ecr.aws/ibleducation/ibl-edx-ce (architected using Tutor). Develop an extension that exposes a REST API endpoint and saves a greeting from the user (secure this endpoint with OAuth2 in the same way that Open edX secures its other API endpoints). This endpoint should do the following things with the user-submitted greeting: Log it (it should be visible in the platform’s LMS logs). Save it in the database (the greeting should be visible from the Django Admin). If the greeting is “hello”, then the view of this API endpoint should call the original greeting endpoint again with “goodbye” as the parameter. This is to make sure that you can write an Open edX view that can make an OAuth2-secured API call with a client ID, a client secret and an access token. Of course, if your code calls this endpoint with “hello” again then it’ll be recursive and things will crash." And now the steps where OpenedX is involed are left only please someone guide me through it. I created a docker container using the image link provided above now I … -
django passing variable to javascript in html template
I was trying to pass a variable to my html template in my django project and I can't seem to find a solution to why it doesn't work. The input of username_list: ['name1', 'name2'] back end: username_list = [user.username for user in User.objects.all()] return render(response, "main/main-page.html", {"list": username_list}) template: <script> let availableKeywords = {{ list }}; console.log(availableKeywords); </script> The javascript won't run and I don't understand if there is another correct way of doing it that I am not aware of. Can't figure it out. Thanks for the help! -
How to schedule tasks with Celery in Django based on a model field and update them dynamically?
I've encountered a challenge while developing an application with Django and using Celery to schedule tasks based on a model field. I'd like to share my solution and seek advice on potential improvements. As a relatively inexperienced developer, I welcome any guidance. I'm working on a Django application for managing training courses, and I need to schedule tasks when a registration deadline is reached. I've implemented Celery for task scheduling and store task IDs in a model field to allow for revocation if necessary.My challenge is ensuring that when the registration deadline is changed, the scheduled task is also updated or executed if the deadline has passed. from datetime import datetime from celery.result import AsyncResult from django.db import transaction from django.db.models.signals import post_save, pre_delete, pre_save from django.dispatch import receiver from django.shortcuts import get_object_or_404 from django.utils import timezone from .models import Training from .tasks import post_registration_deadline def delay_and_assign_registration_deadline_task(training_id): """ The post_registration_deadline notifies the members of the training manager group if the minimum number of candidates is not reached. If there is still some registrations to review, they are canceled with the reason "REGISTRATION_DEADLINE_PASSED". """ training = get_object_or_404(Training, id=training_id) task_id = post_registration_deadline.delay(training.id).task_id training.registration_deadline_task = task_id training.save() @receiver(pre_save, sender=Training) def pre_save_training(sender, instance, **kwargs): … -
how can redirect to another page when if statement is true in django template?
I have a HTML page that displays some information retrieved from database, in this template i have if statement when it is return True, it must be redirect to another page, here is my HTML Page: Communications.html: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> {% load bootstrap5 %} {% bootstrap_css %} <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.5.0/css/all.css" integrity="sha384-B4dIYHKNBt8Bc12p+WXckhzcICo0wtJAoU8YZTY5qE0Id1GSseTk6S+L3BlXeVIU" crossorigin="anonymous"> <style> label{ font-size: 18px; } </style> </head> <body> <table id="tblToExcl" class="table table-striped table-bordered table-sm"> <thead class="thead-dark"> <tr> <th>Day</th> <th>From</th> <th>To</th> <th>Name Lecturer</th> <th>Lesson</th> <th>Lab</th> </tr> </thead> <tbody> {% for table in tables %} <tr> <td>{{ table.day }}</td> <td>{{ table.strt_lec }}</td> <td>{{ table.end_lec }}</td> <td>{{ table.name_lecurer }}</td> <td>{{ table.name_lesson }}</td> <td>{{ table.lab }}</td> {% if table.comm_time_compare%} <p>time is equal</p> {% else %} <p> time is not equal</p> {% endif %} </tr> {% endfor %} </tbody> </table> </body> </html> models.py: class Communications(models.Model): day = models.CharField(max_length=20) strt_lec = models.CharField(max_length=20) end_lec = models.CharField(max_length=20) name_lecurer = models.CharField(max_length=40, choices=LECTURER_NAME_Comm) name_lesson = models.CharField(max_length=70, choices=LESSONS_Comm) lab = models.CharField(max_length=20, choices=LAB_NAMES_Comm) @property def comm_time_compare(self): current_time = time.strftime("%I:%M") if current_time == self.strt_lec: return True else: return False urls.py: from django.urls import path from . import views from django.views.generic import TemplateView urlpatterns = [ path('members/', views.members, name='members'), path('', views.index, name='index'), path('Communications', … -
Gateway timeout(504) in django application
I've built a website in django and hosted it on vercel. However if the website stay inactive for 5-10 mins I get a 504 error. I'm not sure why it is happening. Any suggestions on how to fix this issue will be really helpful? -
"I'm having trouble with my Django 'delete' function in customer registration. It doesn't delete as expected. Can you review and advise? Thanks!"
"I'm working on a Django project for customer registration, and I'm encountering an issue with the 'delete' function. When I try to delete a customer's information, it doesn't work as expected. Can someone please review my 'delete' function and suggest any corrections or improvements? Thank you!" This my view.py code block. from . models import Customer from django.contrib import messages def cutomer_registration (request): message = '' data = '' number = 0 if 'ok' in request.POST: name = request.POST['name'], surname = request.POST['surname'], email = request.POST['email'], phone = request.POST['phone'] if name and surname and email and phone: if Customer.objects.filter(email=request.POST['email']).exists(): message = "This email already exists." elif Customer.objects.filter(phone=request.POST['phone']).exists(): message = "This phone already exists" else: save_data = Customer( name = request.POST['name'], surname = request.POST['surname'], email = request.POST['email'], phone = request.POST['phone '], note = request.POST['note'] ) save_data.save() message = "Customer registration was successful." else: message = "Fill in the appropriate boxes" data = Customer.objects.all().order_by('-id') number = Customer.objects.count return render(request, 'registration_m.html', {'message' : message, 'data' : data, 'number' : number}) def del(request, id): if 'delete' in request.POST: customer = Customer.objects.get(id=id) if 'yes' in request.POST: customer.delete() else: return redirect('registration') return render(request, 'registration_m.html', {'customer' : customer}) This my html code block. <h2>Customer Registration</h2> <form method="post"> {% … -
How to generate one json into two json?
I have the following fixture from a Django project: [ { "model": "music", "pk": 1, "fields": { "attributed_to": false, "creator": null, "name": "Piano Trio No. 1", "name_en": "Piano Trio No. 1", "name_de": "Trios für Pianoforte, Violine und Violoncello, Nr. 1", "dedicated_to": "Prince Karl Lichnowsky", "piece_type": "Trio", "category": "Chamber Music", "date_start": "1792-01-01", "date_completed": "1794-01-01", "key": "e-flat major" }, { "model": "music", "pk": 2, "fields": { "attributed_to": false, "creator": null, "name": "Piano Trio No. 2", "name_en": "Piano Trio No. 2", "name_de": "Trios für Pianoforte, Violine und Violoncello, Nr. 2", "dedicated_to": "Prince Karl Lichnowsky", "piece_type": "Trio", "category": "Chamber Music", "date_start": "1792-01-01", "date_completed": "1794-01-01", "key": "G major" }, { "model": "music", "pk": 3, "fields": { "attributed_to": false, "creator": null, "name": "Piano Trio No. 3", "name_en": "Piano Trio No. 3", "name_de": "Trios für Pianoforte, Violine und Violoncello, Nr. 3", "dedicated_to": "Prince Karl Lichnowsky", "piece_type": "Trio", "category": "Chamber Music", "date_start": "1792-01-01", "date_completed": "1794-01-01", "key": "c minor" } ] Due to a restructure of the app, I need to spilt/sort various columns of this fixture/json into two separate fixture/jsons. The two new fixture/json files should look like this: Fixture #1 [ { "model": "music", "pk": 1, "fields": { "creator": null, "name": "Piano Trio No. 1", "name_en": "Piano … -
Can`t get the value of input Django
So i need to get the quantity of product and then add it to cart. I made an input field with quantity value and when i click 'add to cart' i want to send it to django view, but i get None type for some reason. Im using htmx for dynamic requests. views.py product = Product.objects.get(slug=slug) quantity = request.POST.get('quantity') print(quantity) productId = product.pid customer = request.user.customer product = Product.objects.get(pid=productId) order, created = Order.objects.get_or_create(customer=customer, complete=False) orderItem, created = OrderItem.objects.get_or_create(order=order, product=product) orderItem.quantity = quantity orderItem.save() if orderItem.quantity <= 0: orderItem.delete() html code <form method="post">{% csrf_token %} <div class="body-product__actions"> <div data-quantity class="body-product__quantity quantity"> <button data-quantity-minus type="button" class="quantity__button quantity__button_minus"></button> <div class="quantity__input"> <input data-quantity-value='True' autocomplete="off" type="text" name="quantity" value="1"> <!-- here is the input im trying to get --> </div> <button data-quantity-plus type="button" class="quantity__button quantity__button_plus"></button> </div> <button data-ripple type="submit" hx-get="{% url 'Add product page' product.slug %}" hx-trigger="click" class="body-product__add-to-cart button button_cart"><span class="_icon-cart-plus">Add to cart</span></button> <!-- This is the button that sends the htmx request --> <a href="#" class="body-product__cicil border-button border-button_cicil"> <img src="{% static 'mstore/img/icons/cicil.svg' %}" alt="cicil"> </a> </div> </form> I tried to get the value with post, get requests but the result is similar, i have similar code in my other project and it works perfect.