Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: 0001_initial.py is not on current status after complementing models.py
I am new to Django/ python and I am facing a problem with my models.py I added some attributes, saved it -> py manage.py makemigrations -> py manage.py migrate but the current attributes are not shown in the 0001_initial.py and also when I am opening the database in my DB Browser for SQLite I still get the old status. Can anyone of you help me out with this? Thanks in advance, Laura Here's my code: models.py ` from django.db import models # from django.contrib.auth.models import User # Create your models here. category_choice = ( ('Allgemein', 'Allgemein'), ('Erkältung', 'Erkältung'), ('Salben & Verbände', 'Salben & Verbände'), ) class medicament(models.Model): PZN = models.CharField(max_length=5, primary_key=True) # Maxlaenge auf 5 aendern name = models.CharField('Medikament Name', max_length=100) description = models.CharField('Medikament Beschreibung', max_length=500) category = models.CharField(max_length=100, blank=True, null=True, choices=category_choice) instructionsForUse = models.CharField('Medikament Einnehmhinweise', max_length=400) productimage = models.ImageField(null=True, blank=True, upload_to="images/") stock = models.PositiveIntegerField(default='0') reorder_level = models.IntegerField(default='0', blank=True, null=True) price= models.DecimalField(default='0.0', max_digits=10, decimal_places=2) sold_amount = models.IntegerField(default='0', blank=True, null=True) sales_volume = models.DecimalField(default='0.0', max_digits=10, decimal_places=2) def __str__(self): return self.name And the 0001_initial.py `# Generated by Django 3.2.16 on 2023-01-05 14:33 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='medicament', fields=[ ('PZN', … -
how to use static in django project
Is this not the correct way of making use of Django's static directories in code? The folder is static/assets/css/style.css settings.py STATIC_URL = 'static/' STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATICFILES_DIRS = (os.path.join(BASE_DIR, 'static'),) urls.py from django.conf.urls.static import static from django.conf import settings urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) base.html {% load static %} <!DOCTYPE html> <head> <link rel="stylesheet" href="{% static 'assets/css/style.css' %}"> </head> <body> <a href="">Go somewhere</a> </body> </html> style.css a{ text-decoration: none; } -
How can I save the data from my Django crispy form
This is how my form looks like: When I press submit and go to the page where the post should be rendered, then I cannot see the post I just have created. This is the page where I have my form: 'anzeige_new.html' {% load crispy_forms_tags %} {% block content %} <div class="content-section"> <form method="POST"> {% csrf_token %} <fieldset class="form-group"> <legend class="border-bottom mb-4">Inserat erstellen</legend> {{ form|crispy }} </fieldset> <div class="form-group"> <button class="btn btn-outline-info" type="submit">Post</button> </div> </form> </div> {% endblock content %} This is where it should be rendered: "angebote.html" {% block content %} {% for post in posts %} <p>Inside for loop</p> <a class="mr-2" href="#">{{ Post.objects.all }}</a> <article class="media content-section"> <img class="rounded-circle article-img" src="{{ post.author.profile.image.url"> <div class="media-body"> <div class="article-metadata"> <a class="mr-2" href="#">{{ post.author }}</a> <small class="text-muted">{{ post.date_posted|date:"F d, Y" }}</small> </div> <h2><a class="article-title">{{ post.title }}</a></h2> <p class="article-content">{{ post.content }}</p> </div> </article> {% endfor %} {% endblock content %} forms.py class PostForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(PostForm, self).__init__(*args, **kwargs) # If you pass FormHelper constructor a form instance # It builds a default layout with all its fields self.helper = FormHelper(self) # You can dynamically adjust your layout self.helper.layout.append(Submit('save', 'save')) class Meta: model = Post fields = ('title', 'category', 'weekday') models.py class … -
Run Celery tasks on Railway
I deployed a Django project in Railway, and it uses Celery and Redis to perform an scheduled task. The project is successfully online, but the Celery tasks are not performed. If I execute the Celery worker from my computer's terminal using the Railway CLI, the tasks are performed as expected, and the results are saved in the Railway's PostgreSQL, and thus those results are displayed in the on-line site. Also, the redis server used is also the one from Railway. However, Celery is operating in 'local'. This is the log on my local terminal showing the Celery is running local, and the Redis server is the one up in Railway: -------------- celery@MacBook-Pro-de-Corey.local v5.2.7 (dawn-chorus) --- ***** ----- -- ******* ---- macOS-13.1-arm64-arm-64bit 2023-01-11 23:08:34 - *** --- * --- - ** ---------- [config] - ** ---------- .> app: suii:0x1027e86a0 - ** ---------- .> transport: redis://default:**@containers-us-west-28.railway.app:7078// - ** ---------- .> results: - *** --- * --- .> concurrency: 10 (prefork) -- ******* ---- .> task events: OFF (enable -E to monitor tasks in this worker) --- ***** ----- -------------- [queues] .> celery exchange=celery(direct) key=celery [tasks] . kansoku.tasks.suii_kakunin I included this line of code in the Procfile regarding to the worker (as I … -
Comparação de tabelas em python
Olá, gostaria de saber como que eu comparo duas tabelas em python e crio uma nova apenas com as linhas que são diferentes entre elas. Eu pensei na função merge() mas não sei como remover as linhas diferentes. -
vscode testing with pytest for dockerized Django project
i want to debug my tests in vscode for my Django project witch is set up in a docker container but the problem is it always says pytest discovery error, sometimes it seems to not be able to import modules(for example models) inside the test file and after some configuration it seems to not find the test file itself. all the folders of my project have an init.py file so everything is treated as a package, by the way there is no problem importing modules in my Django project. the odd thing is when I run pytest inside of my docker container it works fine but I want to debug the tests. i am fairly new to this so any help would be welcomeenter image description here I enabled pytest in the .vscode/settings.jsonenter image description here file as some other settings I tried also creating a .env file with PYTHONPATH in it to my root folder cause every tutorial I found work with a virtual environment and not a docker container -
Errors in importing a react library created using rollup
I am writing a React/Next app. I have created a react accordion-component external to the app. I am using rollup to create a package and importing that package into my app. When I run the app I get the error ./node_modules/@zeilsell-user1/accordion-component/dist/esm/index.js Module parse failed: Unexpected token (1:4) You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders use clientfunction getDefaultExportFromCjs (x) { | return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x; | } I do not understand why I am seeing this error. The component is ESM so why the CSJ function? Nexrjs uses webpack, but that should handle csj, I can't find anything about loaders anyway. I am assuming that the issue is on the component side, so I have included the rollup, tsconfig and package files below. Really appreciate any help that the community can offer me as I have been stuck on this problem for ages. my rollup.config.mjs import {nodeResolve} from '@rollup/plugin-node-resolve'; import commonjs from "@rollup/plugin-commonjs"; import typescript from "rollup-plugin-typescript2"; import banner2 from "rollup-plugin-banner2"; import dts from "rollup-plugin-dts"; import packageJson from "./package.json" assert { type: "json" }; export default [ { input: … -
makemigrations ModuleNotFoundError: No module named Insta
I had to re-do my project, and I copied the code from my files [names and directories are virtually the same] When I try to make migrations, this error pops out. I have insta in my settings.py at installed apps. File "<frozen importlib._bootstrap>", line 1206, in _gcd_import File "<frozen importlib._bootstrap>", line 1178, in _find_and_load File "<frozen importlib._bootstrap>", line 1142, in _find_and_load_unlocked ModuleNotFoundError: No module named 'insta'I'm not sure if it will help, but here's my file structure I'm not really sure what to do, could someone help? -
The view Insertemp.views.Insertrecord didn't return an HttpResponse object. It returned None instead
I'm not sure what is coursing the problem.... The view Insertemp.views.Insertrecord didn't return an HttpResponse object. It returned None instead. views.py from django.shortcuts import render from Insertemp.models import EmpInsert from django.contrib import messages def Insertrecord(request): if request.method == 'POST': if request.POST.get('empname') and request.POST.get('email') and request.POST.get('country'): saverecord = EmpInsert() saverecord.empname = request.POST.get('empname') saverecord.email = request.POST.get('email') saverecord.country = request.POST.get('country') saverecord.save() messages.success(request, 'Record saved successfully...!') return render(request, 'Index.html') else: return render(request, 'Index.html'), I have change the code.... from django.shortcuts import render from Insertemp.models import EmpInsert from django.contrib import messages def Insertrecord(request): if request.method == 'POST': if request.POST.get('empname') and request.POST.get('email') and request.POST.get('country'): saverecord = EmpInsert() saverecord.empname = request.POST.get('empname') saverecord.email = request.POST.get('email') saverecord.country = request.POST.get('country') saverecord.save() messages.success(request, 'Record saved successfully...!') return render(request, 'templates/Index.html', {}) else: return render(request, 'templates/Index.html', {}) but still it doesn't display what it should... Index.html <!DOCTYPE html> <html lang="en"> <head> <title>Insert new Record</title> </head> <body> <h1>Create or New record Insert into MySQL(PhpMyAdmin)</h1> <h2>Python Django web Programming</h2> <hr> <form method="POST"> {% cdrf_token %} Employee Name : <input type="text" placeholder="Enter Name" name="empname" required> Email : <input type="text" placeholder="Enter Email" name="email" required> country : <input type="text" placeholder="Enter Country" name="country" required> <input type="submit" value="Insert record"> {% if messages %} {% for message in messages %} <h2 … -
"detail": "CSRF Failed: CSRF token missing."
I was trying to test my API in DJango, but while trying to use a POST request to create a user, the following error shows up: "detail": "CSRF Failed: CSRF token missing." What should I do? Can I remove this? Or how should I pass the CSRF also in testing and in production? In theory, I put the false in CSRF_COOKIE_SECURE, so, I don't know what to do. -
Add Payment to Django project to extend the expire date of posts in a blog?
I'm working on a freelance project with Django-rest framework which contains posts and each post has an expiration date so the client want to add a payment method to it to extend the expiration date. All the tutorials or blogs i followed didn't mention how to change the database if the transaction is successful. I need help in this matter maybe library name that can help me or any suggestion to make that happen. Thanks in advance. -
Why DRF uses PUT to send files?
I'm trying to understand how file management works in Django Rest Framework, and a question lingers in my mind: Why does Django use PUT to update files? Is it possible to do the same with the PATCH method? How would I be able to push binaries through the patch? Example of model: class User(AbstractUser): id = HashidAutoField(prefix='user_', primary_key=True) picture = models.ImageField(blank=True, null=True, verbose_name=_("profile picture"), storage=PublicMediaStorage(), upload_to=upload_to) When I try to send using the patch method it only allows me to send in json format, I don't know if there is any way to user PATCH and form-data. For Patch I have something like this: { "user": { "username": "", "first_name": "", "password": "", "password_confirm": "", "email": "", "picture": null } } -
Complex Django query involving an ArrayField & coefficients
On the one hand, let us consider this Django model: from django.db import models from uuid import UUID class Entry(models.Model): id = models.UUIDField(primary_key=True, default=uuid4, editable=False) value = models.DecimalField(decimal_places=12, max_digits=22) items = ArrayField(base_field=models.UUIDField(null=False, blank=False), default=list) On the other hand, let us say we have a dictionary coefficients looking like: coefficients = {item1_uuid: item1_coef, item2_uuid: item2_coef, ... } Entry.value is intended to be distributed among the Entry.items according to coefficients (with sum(coefficients.values()) = Decimal(1)). Using Django ORM, what would be the most efficient way (in a single SQL query) to get the sum of the values of my Entries for a single Item given those coefficients? For instance, in that specific case, for item1 I want to get 168.5454...: 100 * 1 + 150 * (0.2 / (0.2 + 0.35)) + 70 * 0.2. | Entry ID | Value | Items | |-------|-------|--------------------------------------| | uuid1 | 100 | [item1_uuid] | | uuid2 | 150 | [item1_uuid, item2_uuid] | | uuid3 | 70 | [item1_uuid, item2_uuid, item3_uuid] | coefficients = { item1_uuid: Decimal("0.2"), item2_uuid: Decimal("0.35"), item3_uuid: Decimal("0.45") } So far this is what I was thinking about, unsuccessfully: def get_value_for_item(coefficients: dict[UUID, Decimal], item: Item) -> Decimal: queryset = Entry.objects.filter(items__contains=item.pk) # I'm missing a … -
How to add a new "comment" or "flag" field to every model field of existing model?
Disclaimer: I can wipe out the database anytime. So while answering this, please don't care about migrations and stuff. Imagine me having a model with multiple values: class Compound(models.Model): color = models.CharField(max_length=20, blank=True, default="") brand = models.CharField(max_length=200, blank=True, default="") temperature = models.FloatField(null=True, blank=True) melting_temp = models.FloatField(null=True, blank=True) # more (~20) especially numeric values as model fields Now I want to add a comment to be stored for every value of that model. For example I want to add a comment "measured in winter" to the temperature model field. What is the best approach to do that? My brainstorming came up with: By hand add 20 more model fields like temperature_comment = ... but that sounds not very DRY Add one big json field which stores every comment. But how do I create a Form with such a json field? Because I want to separate each input field for related value. I would probably have to use javascript which I would want to avoid. Add a model for every value and connect them to Compound via OneToOneFields. But how do I then create a Form for Compound? Because I want to create a Compound utilizing one form. I do not want … -
How to pass detailed url to ajax
I build a template in django which displays a lists with 'load more' button. It shows a list loaded from db depend on endpoint like /details/1, /details/2, /details/3 etc. How can I pass the endpoint to url in js ajax so it won't be hardcoded? something like below url: {pk}/json-details/${visible}, main.js const handleGetData = () => { $.ajax({ type: 'GET', url: `3/json-details/${visible}`, success: function (response) { console.log(response.pk) max_size = response.max const data = response.data setTimeout(()=>{ data.map(character => { console.log(character.name) charBox.innerHTML += ` <tr> <td>${ character.name }</td> <td>${ character.height }</td> <td>${ character.mass }</td> <td>${ character.hair_color }</td> <td>${ character.skin_color }</td> <td>${ character.eye_color }</td> <td>${ character.birth_year }</td> <td>${ character.gender }</td> <td>${ character.homeworld }</td> <td>${ character.date }</td> </tr>` }) }, 500) if (max_size) { loadBox.innerHTML = "<h4>No more characters to load</h4>" } }, error: function (error) { console.log(error) } }) } views.py class CollectionJSONDetails(View): def get(self, request, pk, *args, **kwargs): print(kwargs) upper = kwargs.get('num_posts') lower = upper - 10 jsonArray = [] people_data = models.Collection.objects.get(pk=pk) with open(f"./{people_data.file_name}.csv", encoding='utf-8') as file: csvReader = csv.DictReader(file) for row in csvReader: jsonArray.append(row) number_of_characters = len(jsonArray) max_size = True if upper >= number_of_characters else False jsonArray = jsonArray[lower:upper] return JsonResponse({'data': jsonArray, 'max':max_size, 'page_id':pk}, safe=False) JSON are availaible under the … -
double curly braces in quote mark - Django
Could some one tell me the full picture of the use of the quote mark and the double curly braces? <a href="{{ url_for('delete_event', id=event.id) }}" class="text-danger"> The full code is as below. Is it Django synatx {{ ... }} embeded? {% for event in events %} <tr> <td>{{ event.event }}</td> <td>{{ event.start_time }}</td> <td>{{ event.end_time }}</td> <td>{{ event.position }}</td> <td><a href="{{ url_for('delete_event', id=event.id) }}" class="text-danger">Delete</a></td> </tr> {% endfor %} -
Foreign key get parent AND children in queryset
I have the following model: class TopicModel(models.Model): topic = models.ForeignKey('self', on_delete=models.CASCADE) ... some more not relevant fields... I need to get a parent topic and its direct children in a queryset. Currently I use it with this queryset: TopicModel.objects.filter( Q(pk=10) | Q(topic__pk=10) ) I was wondering whether I can do the same in a more simple query without using Q. -
Using OpenCV HandDetector with a webcam in Django
I am working on a Django project that involves using a webcam to play a rock-paper-scissors game against a computer. I have implemented the OpenCV HandDetector algorithm to detect a hand in the webcam video feed, and a Keras classifier to classify the hand gesture. However, I am running into an issue with getting the HandDetector to work properly with the webcam video. I have tried using a single still image from the webcam, but the HandDetector does not work well with just one image. I think the solution is to use a video of the hand, but I am not sure how to implement this in my Django project. Here is the code for my jQuery script that captures the video from the webcam and sends it to a Django view: <div class="container"> <div class="row"> <div class="col-md-6"> <video id="webcam" width="640" height="480" autoplay></video> </div> <div class="col-md-6"> <button id="play-button" class="btn btn-primary" onclick="play()">Play</button> </div> </div> </div> <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> <script> $(document).ready(function() { startWebcam(); }); var video = document.getElementById('webcam'); var stream; function startWebcam() { navigator.mediaDevices.getUserMedia({ video: true, audio: false }) .then(function(localMediaStream) { stream = localMediaStream; video.srcObject = localMediaStream; video.play(); }) .catch(function(err) { console.log("An error occurred: " + err); }); } function play() { // … -
How to create auto add ShortUUIDField in Django
I need to create a django ShortUUIDField that automatically generate the value when the entry is created: Here's my code: def generate_short_uuid(): string_uuid = str(uuid.uuid4()) return string_uuid.replace('-', '')[:12] class ShortUUIDField(models.CharField): def __init__(self, *args, **kwargs): kwargs['default'] = generate_short_uuid kwargs['editable'] = False kwargs['unique'] = True kwargs['blank'] = True kwargs['null'] = True kwargs['max_length'] = 12 super().__init__(*args, **kwargs) def pre_save(self, model_instance, add): if add: while True: try: value = generate_short_uuid() setattr(model_instance, self.attname, value) return value except IntegrityError as e: if 'duplicate key' in str(e): continue raise Here's the model that use the field: class UserProfile(models.Model): uuid = ShortUUIDField() user = models.OneToOneField("users.User", on_delete=models.CASCADE, related_name="profile") Here's the error that occurs when I try to create the entry: django.db.utils.IntegrityError: null value in column "uuid" of relation "profiles_userprofile" violates not-null constraint -
Image not displaying in browser from Django project
I am trying out an ecommerce website where list of products are input in the admin section, everything works well aside the fact that the product image does not display in browser. Have check all the codes and everything seems ok. Displaying this message in my terminal "GET /media/photos/buy-1.jpg HTTP/1.1" 404 4187 Not Found: /media/photos/buy-2.jpg `HTML <h2 class="title">Latest Products</h2> <div class="row"> {% for item in object_list %} <div class="col-4"> <div> <a href="{{ item.get_absolute_url }}"> {% if item.photo %} <img src="{{ item.photo.url }}" alt="" /> {% else %} <img src="{% static 'images/product-1.jpg' %}" alt=""/> {% endif %} <h4>{{ item.title }}</h4> </a> <a href="{{ item.get_absolute_url }}" > <h6>{{ item.get_category_display }}</h6> </a> </div> <div class="rating"> <i class="fa fa-star"></i> <i class="fa fa-star"></i> <i class="fa fa-star"></i> <i class="fa fa-star"></i> <i class="fa fa-star-o"></i> </div> <p class='lead'> {% if item.d_price %} <del><span>${{ item.price }}</span></del> <span>${{ item.d_price }}</span> {% else %} <p>${{ item.price }}</p> {% endif %} </p> </div> {% endfor %} </div>` Model fie `class Item (models.Model): title = models.CharField(max_length=100) price = models.FloatField() d_price = models.FloatField(blank=True, null=True) tax = models.FloatField(blank=True, null=True) category = models.CharField(choices=CATEGORY_CHOICES, max_length=2) label = models.CharField(choices=LABEL_CHOICES, max_length=1) slug = models.SlugField() description = models.TextField() photo = models.ImageField(upload_to='photos', null=False, blank=False) def __str__(self): return self.title def get_absolute_url(self): return … -
django.db.utils.IntegrityError: duplicate key
I have a model for Logs which is as follows: class Log(TimeStampMixin): uuid = models.UUIDField(default=uuid.uuid4, editable=False, unique=True) start_time = models.CharField(max_length=80, null=True, blank=True, default=None) end_time = models.CharField(max_length=80, null=True, blank=True, default=None) message = models.CharField(max_length=80, null=True, blank=True, default=None) def __str__(self): return str(self.message) I just changed message field length to max_length=1000 . After doing makemigrations when I did migrate, it giving me this error. django.db.utils.IntegrityError: duplicate key value violates unique constraint "django_migrations_pkey" DETAIL: Key (id)=(32) already exists. I tried many solution but none of them making sense for my code I also saw other similar questions but they told to write null=True, blank=True, but I already have it in my code -
Django application running inside of a container but cannoct resolve DB outside of it
I have a Django application which I've decided to setup in container as follows: #docker-compose.yml version: "3.9" services: web: build: . command: python /code/manage.py runserver 0.0.0.0:8000 volumes: - .:/code ports: - 8000:8000 depends_on: - db db: image: postgres:13 volumes: - postgres_data:/var/lib/postgresql/data/ environment: - "POSTGRES_HOST_AUTH_METHOD=trust" volumes: postgres_data: with database config in settings as follows DATABASES = { "default": { "ENGINE": "django.db.backends.postgresql", "NAME": "postgres", "USER": "postgres", "PASSWORD": "postgres", "HOST": "db", "PORT": 5432, } } And when I run the containers, the app works correctly with me being able to migrate and insert data into database. However when I try to run the project outside of the container by following steps: python -m venv venv source venv/bin/activate pip install -r requirements.txt python manage.py runserver I am getting an error: Traceback (most recent call last): File "/home/jdoni/code/work/tasks/venv/lib64/python3.10/site-packages/django/db/backends/base/base.py", line 244, in ensure_connection self.connect() File "/home/jdoni/code/work/tasks/venv/lib64/python3.10/site-packages/django/utils/asyncio.py", line 26, in inner return func(*args, **kwargs) File "/home/jdoni/code/work/tasks/venv/lib64/python3.10/site-packages/django/db/backends/base/base.py", line 225, in connect self.connection = self.get_new_connection(conn_params) File "/home/jdoni/code/work/tasks/venv/lib64/python3.10/site-packages/django/utils/asyncio.py", line 26, in inner return func(*args, **kwargs) File "/home/jdoni/code/work/tasks/venv/lib64/python3.10/site-packages/django/db/backends/postgresql/base.py", line 203, in get_new_connection connection = Database.connect(**conn_params) File "/home/jdoni/code/work/tasks/venv/lib64/python3.10/site-packages/psycopg2/__init__.py", line 122, in connect conn = _connect(dsn, connection_factory=connection_factory, **kwasync) psycopg2.OperationalError: could not translate host name "db" to address: Name or service not known The … -
How to make Multiple dependent dropdown in CRUD Django?
Fields are such as; Phone Name(Field1) Samsung Redmi Phone Model(Field2) M30 Note10 Note : Dependency between Phone Name and Phone Model(if select samsung from the dropdown then M30 should comes and if select Redmi from the dropdown then Note10 should come. State(Field3) Karnataka Andhra City(Field4) Bangalore Tirupathi Note : Dependency between State and City(if i select "Karnataka" from the dropdown then "Bangalore" should come and if i select "Andhra" from the dropdown then "Tirupathi" should come. Data & Time(Field5) Company Name(Field6) I need form design Horizontally(col-6) in Separate page Phone Name(Field1) Phone Model(Field2) State(Field3) City(Field4) Data & Time(Field5) Company Name(Field6) I need Retrieving Data from database in Separate page Example: Phone name Phone Model State City Company Name ---------- ----------- ----- ---- ------------- -
Contact form not saving in the Database , is it the views or the HTML?
I have an issue in Django where the contact form after being filled out doesn't save in the database : My views : def CV_page(request): if request. Method == 'POST': form = ContactForm(request.POST) if form.is_valid(): # Save form data to Django models contact = ContactForm(full_name= form.cleaned_data['name'], email_sender= form.cleaned_data['email'], phone_number= form.cleaned_data['phone'], message= form.cleaned_data['message']) contact.save() # Send email to admin send_mail('CV-Website-contact', form.cleaned_data['message'], form.cleaned_data['email'], ['xxxx@xxxx.com', form.cleaned_data['email']]) return HttpResponse('success') #HttpResponseRedirect('success/') # create a success page else: form = ContactForm() else: form = ContactForm() context = {'Abouts': latest_description, 'form': form, 'categories': categories, 'portfolios': portfolios, 'pdf': final_pdf_link} return render(request, 'cv_page.html', context) models.py class Contact(models.Model): id = models.UUIDField(default=uuid.uuid4, unique=True, primary_key=True, editable=False) name = models.CharField(max_length=100, null=True, blank=True) email = models.EmailField(max_length=254, null=False, blank=True) phone = PhoneNumberField(null=True, blank=True, unique=False) message = models.CharField(max_length=2500, null=True, blank=True) created_on = models.DateTimeField(auto_now_add=datetime.datetime.now) updated_on = models.DateTimeField(auto_now=datetime.datetime.now) forms.py class ContactForm(forms.ModelForm): class Meta: model = Contact fields = ['name', 'email', 'phone', 'message'] my HTML: <!-- Contact Section--> <section class="page-section" id="contact"> <div class="container"> <!-- Contact Section Heading--> <h2 class="page-section-heading text-center text-uppercase text-secondary mb-0">Contact Me</h2> <!-- Icon Divider--> <!-- Contact Section Form--> <div class="row justify-content-center"> <div class="col-lg-8 col-xl-7"> <form method="post"> {% csrf_token %} {{form.as_p}} <div class="form-actions"> <button type="submit">Send</button> </div> </form> </div> </div> </div> </section> I believe it is the Contactform … -
ajax request.method= 'POST' is not working in django
I have a problem,Django my ajax post is not working. when i look at the console quantity is not undefined. But my request.post is not working. <form method="POST"> {% csrf_token %} <ul> <li> <div class="form-group quantity-box"> <label class="control-label">Quantity</label> <input class="form-control" id="quantity" value="0" min="0" max="20" type="number" /> </div> </li> </ul> <div class="price-box-bar"> <div class="cart-and-bay-btn"> <a class="btn hvr-hover" data-fancybox-close="" href="#" >Buy New</a> <button type = "submit"> <a class="btn hvr-hover" data-fancybox-close="" id= "qtyButton" data-fancybox-close="" href="{% url 'addCart' %}">Add to cart</a> </button> </form> my js script $('#qtyButton').click(function(e){ e.preventDefault(); var qty = $('#quantity').val(); var id = {{product.id}}; $.ajax({ type: "POST", url: "{% url 'addCart' %}", dataType: 'json', data: { "quantity":qty, "product_id":{{product.id}}, } }); }); my wiew.py file def addCart(request): url = request.META.get('HTTP_REFERER') if request.method == 'POST': post = request.POST quantity = post.get('quantity') id = post.get('product_id') item = Product.objects.get(id=id) Cart.objects.get_or_create(user_id=request.user, product_id=item, quantity=quantity) else: return render(request, 'cart.html') return redirect(request.META.get("HTTP_REFERER", "/")) I tried so many things. But none of them is working. What should i do ?