Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Three questions about django-autocomplete-light
I use django-autocomplete-light in my Django project. I build create new article for list articles. And with this third application, I want to use for autocomplete and create new one form for name of the Journal, Journal years and volume and issue. For example, in my models, the main model is Article with the field: journal, journal year, volume and issue. This field has a foreign key in its model. Also, in template I use depends on dropdown. name of the journal -> year journal -> volume and issue How does it work? If the user would like to add his article to the site. He select name of the journal, journal year and volume and issue. If it does not have information in foreign key, he can create new information about it. I could build it but I have some problem. Depends on dropdown work good, but If I use create new one, I want to assign it to a foreign key. For example, the User created journal, year, volume and issue, and then when other user want to add in the same journal, year, volume and issue they can do it. Now new Foreign key to create in … -
Uncaught SyntaxError: Unexpected token ':' on django channels
messages.js let loc = window.location let wsStart = 'ws://' if (loc.protocol == 'https') { wsStart = 'wsss://' } let endpoint = wsStart + loc.host + loc.pathname varsocket = new WebSocket(endpoint) socket.onopen = async function(e: Event) { //-----------------> Eroor comes here e: Event) { console.log('open', e) } socket.onmessage = async function(e: MessageEvent) { console.log('message', e) } socket.onerror = async function(e: Event) { console.log('error', e) } socket.onclose = async function(e: CloseEvent) { console.log('close', e) } error: Uncaught SyntaxError: Unexpected token : on django channels please help me what is the error how to solve this -
Unable to retrieve API data using axios
I'm trying to build a simple login using an API but keep facing errors import React from "react"; import { useState } from "react"; import axios from "axios"; import { useNavigate } from "react-router-dom"; export default function Login() { const navigate = useNavigate(); const [formData, setFormData] = useState({ uid: "", password: "", blocked: 0 }); const handleSubmit = (e) => { e.preventDefault(); console.log(formData); const data = JSON.stringify(formData); console.log(data); axios .post("https://myphysio.digitaldarwin.in/api/login/", data) .then(function (response) { console.log(response); console.log("Successfully Logged in "); navigate("/success"); }) .catch(function (error) { console.log(error); }); }; return ( <form onSubmit={handleSubmit}> <h3>Login</h3> <div className="form-group"> <label>uid Name</label> <input name="uid" className="form-control" placeholder="Enter your uid Name" value={formData.uid} onChange={(e) => setFormData({ ...formData, uid: e.target.value })} /> </div> <div className="form-group"> <label>Password</label> <input type="password" name="password" className="form-control" placeholder="Enter password" value={formData.password} onChange={(e) => setFormData({ ...formData, password: e.target.value }) } /> </div> <button type="submit" className="btn btn-primary btn-block"> Submit </button> </form> ); } The error I keep facing is console log of error POST https://myphysio.digitaldarwin.in/api/login/ 500 (Internal Server Error) Error: Network Error at createError (createError.js:16:1) at XMLHttpRequest.handleError (xhr.js:117:1) POST https://myphysio.digitaldarwin.in/api/login/ net::ERR_CONTENT_LENGTH_MISMATCH 500 (Internal Server Error) -
In PyCharm I can run the configuration of the project but can't debug the project
I'm getting trouble with debugging a Django 4.0 application with Pycharm 2021.2 (Professiontal Edition). I have configured the Run/Debug Configurations with the right Python Interpreter. It's the basic configurations. Running with Shift + F10 runs the project, but debugging (Shift + F9) gives the error message: Connected to pydev debugger (build 212.4746.96) <dir>/env/bin/python /opt/pycharm-2021.2/plugins/python/helpers/pydev/pydevd.py --multiproc --qt-support=auto --client 127.0.0.1 --port 46579 --file /home/caco/Workspace/CodeChallenges/desafio-dev-system/desafio-dev/manage.py runserver 8000 <dir>/env/bin/python: can't find '__main__' module in '' Process finished with exit code 1 In other project the debugging mode is runnig accordingly. I already destroyed .idea dir and closed and opened Pycharm again, but the problem persists. -
Update Nested User Serializer With Image avatar
I want to add an avatar image to my profile serializer which is nested in the User Serializer as a one-to-one field. Im having issues getting the file to upload on the front end and I want to make sure I have everything correct in my backend Django DRF. I am using Djoser for the urls with DRF API. Please take a look and let me know if there is anything I might be missing. I have no errors with the "put" request on the frontend but the file is not being uploaded to my avatar file path and obviously not saving in the nested user object neither. I can update the avatar from the DRF with no issues as well. Model.py class Profile(models.Model): user = models.OneToOneField(User, primary_key=True, on_delete=models.CASCADE) name = models.CharField(max_length=100, blank=True, null=True) occupation = models.CharField(max_length=100, blank=True, null=True) residence = models.CharField(max_length=100, blank=True, null=True) email = models.CharField(max_length=100, blank=True, null=True) active_id = models.BooleanField(default=True) avatar = models.ImageField(null=True, blank=True, upload_to ='uploads/profile_pics',default='uploads/default.jpg') def __str__(self): return self.user.username # def get_image(self): # return self.avatar.path def save(self, *args, **kwargs): super(Profile, self).save(*args, **kwargs) img = Image.open(self.avatar.path) if img.height > 300 or img.width > 300: output_size = (300, 300) img.thumbnail(output_size) img.save(self.avatar.path) Serializers.py class ProfileSerializer(serializers.ModelSerializer): user = serializers.StringRelatedField(read_only=True) class Meta: … -
How to update Celery tasks in production?
I have a Django application and some scheduled tasks handled by Celery. I use RabbitMQ as a message broker. Locally, everything works as supposed, but in production, celery worker runs old tasks that don't even exist anymore. I've tried adding worker restart to my celery worker Kubernetes-deployment -file, but that didn't make any difference. Here's what I tried: spec: containers: - name: celery-worker command: ["/bin/sh"] args: - -c - >- celery -A project_name -b 10.0.240.179 worker -l info && celery restart -A project_name -b 10.0.240.179 worker -l info This runs the worker pod without errors but it still uses the old, already deleted tasks. Is there a way how I could get updated tasks from Django's settings.py? -
How to solve error message: no such column: auctions_auction.image_url
I'm creating an aunction website where users will submit a form with the link to an image when creating a new listing. This link/url will then be converted and displayed as an image on the website. I keep getting this error when I upload the details of the form including the link to the image - ""OperationalError at /create/ no such column: auctions_auction.image_url."" How can I clear this error? VIEWS.PY from django.shortcuts import render, redirect from .forms import AuctionForm def create_listing(request): form = AuctionForm() if request.method == 'POST': form = AuctionForm(request.POST, request.FILES) if form.is_valid: form.save() return redirect('index') else: form = AuctionForm() context = {'form': form} return render(request, 'auctions/create-listing.html', context) FORMS.PY from .models import Auction from django import forms from django.forms import fields class AuctionForm(forms.ModelForm): class Meta: model = Auction fields = ['title', 'description', 'current_bid', 'image_url'] MODELS.PY from django.db import models from django.core.files import File from urllib.request import urlopen from tempfile import NamedTemporaryFile class Auction(models.Model): title = models.CharField(max_length=25) description = models.TextField() current_bid = models.IntegerField(null=False, blank=False) users_bid = models.IntegerField(null=False, blank=False) image_upload = models.ImageField(upload_to='images/') image_url = models.URLField(verbose_name="URL", max_length=255, unique=True) created_at = models.DateTimeField(auto_now_add=True) def save(self, *args, **kwargs): if self.image_url and not self.image_upload: img_temp = NamedTemporaryFile(delete=True) img_temp.write(urlopen(self.image_url).read()) img_temp.flush() self.image_upload.save(f"image_{self.pk}", File(img_temp)) super(self).save(*args, **kwargs) def __str__(self): return … -
ImportError: Failed to import test module: Django Tests
I have written some tests for model, views and serializer. All tests are running fine except for the serializer tests. Creating test database for alias 'default'... System check identified no issues (0 silenced). ........E ====================================================================== ERROR: testapp.tests.test_serializers (unittest.loader._FailedTest) ---------------------------------------------------------------------- ImportError: Failed to import test module: testapp.tests.test_serializers Traceback (most recent call last): File "C:\Python310\lib\unittest\loader.py", line 436, in _find_test_path module = self._get_module_from_name(name) File "C:\Python310\lib\unittest\loader.py", line 377, in _get_module_from_name __import__(name) File "F:\Python\django-advanced\testproj\testapp\tests\test_serializers.py", line 19, in <module> AutoSlugField(), from_field(SlugField()) File "C:\Python310\lib\site-packages\django_extensions\db\fields\__init__.py", line 155, in __init__ raise ValueError("missing 'populate_from' argument") ValueError: missing 'populate_from' argument ---------------------------------------------------------------------- Ran 9 tests in 0.034s FAILED (errors=1) Destroying test database for alias 'default'... I am getting the above error when I run python manage.py test Here is my file tree - My project name - testproj My app name - testapp testproj/ ┣ .hypothesis/ ┃ ┣ examples/ ┃ ┃ ┣ 89906a9970b0f6fa/ ┃ ┃ ┃ ┗ 7210af19145ec2a8 ┃ ┃ ┗ f79909d6c0990774/ ┃ ┃ ┗ 7210af19145ec2a8 ┃ ┗ unicode_data/ ┃ ┗ 13.0.0/ ┃ ┃ ┗ charmap.json.gz ┣ testapp/ ┃ ┣ migrations/ ┃ ┃ ┣ __pycache__/ ┃ ┃ ┃ ┣ 0001_initial.cpython-310.pyc ┃ ┃ ┃ ┣ 0002_alter_tag_name.cpython-310.pyc ┃ ┃ ┃ ┣ __init__.cpython-310.pyc ┃ ┃ ┃ ┗ __init__.cpython-38.pyc ┃ ┃ ┣ 0001_initial.py ┃ ┃ ┣ … -
How can I filter users as a choice in a foreign key django forms?
I'm stuck with a problem to filter project managers from a foreign key field in django forms. I want to exclude superusers and other user roles except project manager. Models.py class Projects(models.Model): id=models.AutoField(primary_key=True) project_name=models.CharField(max_length=255) project_manager=models.ForeignKey(CustomUser,on_delete=models.CASCADE, limit_choices_to={'is_project_manager__eq : 1 '}) client_name=models.ForeignKey(Clients,on_delete=models.CASCADE, null=True) project_pic=models.ImageField(upload_to='static/website/project-images') project_start_date=models.DateField(null=True) project_end_date=models.DateField(null=True) project_description=models.TextField(null=True) created_at=models.DateTimeField(auto_now_add=True) updated_at=models.DateTimeField(auto_now=True) is_draft = models.BooleanField(default=True) objects=models.Manager() class Meta: verbose_name_plural = 'Project' def __str__(self): return f'{self.project_name}' Forms.py class ProjectForm(forms.ModelForm): class Meta: model = Projects fields = ['project_name', 'project_manager', 'client_name', 'project_pic', 'project_start_date', 'project_end_date', 'project_description'] Views.py def project_list(request): projects = Projects.objects.all() if request.method == 'POST': form = ProjectForm(request.POST, request.FILES) if form.is_valid(): form.save() project_name = form.cleaned_data.get('project_name') messages.success(request, f'{project_name} has been successfully added.') return redirect('project_list') else: form = ProjectForm() context = { 'projects' : projects, 'form' : form, } template_name ='project-admin/project-list.html' return render(request, template_name, context) CustomUser/Models.py Here is their own roles to set them as a project manager, inventory admin, and client class CustomUser(AbstractUser): is_inventory_admin = models.BooleanField('Is Inventory Admin', default=False) is_project_manager = models.BooleanField('Is Project Manager', default=False) is_client = models.BooleanField('Is Client', default=False) class Meta: db_table = 'auth_user' -
Django: Display the same form multiple times in the same view
I need to open the same form multiple times while looping trough some items. This is the form: class CancelRefundForm(forms.forms.Form): cancel = forms.BooleanField(label='Check to cancel the refund', required=True ,widget=forms.CheckboxInput(attrs={ 'class': 'hidden-checkbox', 'name': 'hiddenCheckBoxName' } )) item = forms.IntegerField( required=True, widget=forms.NumberInput(attrs={ 'class': 'cancel-item-input', 'value': '', 'type': 'hidden' }), ) This is the HTML: <div class="order-items-display"> {% for item in order.orderitem_set.all %} <div class="single-order-item"> <span > <a href="{{ item.item.get_absolute_url }}"> <img src="../../../media/{{ item.item.main_image }}" alt="{{ item.item.title }} image"> </a> </span> <span class="order-item-details"> <h3><a href="{{ item.item.get_absolute_url }}"> {{ item.item.title }} {% if item.replica %} <small>(Replica)</small> {% endif %} </a></h3> <p><strong>Price: </strong>{{ item.old_price }}€</p> {% if item.quantity > 1 %} <p><strong>Quantity: </strong>{{ item.quantity }}</p> <p><strong>Total: </strong>{{ item.get_old_total_price }}€</p> {% endif %} {% if order.refund_deadline > nowDate %} <p><b>The deadline for requesting a refund ends in {{ order.refund_deadline }}(30 days)</b></p> {% else %} <p><b>The deadline for requesting a refund ended in {{ order.refund_deadline }}.</b></p> {% endif %} <button class="myBtnPri update-cart" data-product="{{item.id}}" data-action="add"> <a class="mySecLink" href="#"> Buy Again </a> </button> {% if item.refund_requested %} <p><b>Refund requested: </b> {{ item.refund_requested }}</p> <p><b>Refund granted: </b> {{ item.refund_granted }}</p> <form action="{% url 'order-details' order.slug %}" method="POST" class="cancel-form"> {% csrf_token %} {{ cancelForm.item }} <label for="{{ cancelForm.cancel.id_for_label }}" class="myCheckbox"> {{ … -
TypeError: 'User' object is not iterable
I am working with a payment system in my django E commerce Project. But it shows me that user is not iterable . Here's the code @login_required def payment(request): saved_address = BillingAddress.objects.get_or_create(user=request.user)[0] if not saved_address.is_fully_filled(): messages.info(request,f'Please complete shipping address!') return redirect('checkout') if not request.user.profile.is_fully_filled(): messages.info(request,f'Please complete profile details!') return redirect('profile') store_id = '$$$$$$$$$$$$$$$' API_key= '$$$$$$$$$$$$$$$@ssl' mypayment = SSLCSession(sslc_is_sandbox=True, sslc_store_id=store_id, sslc_store_pass=API_key) status_url= request.build_absolute_uri(reverse('complete')) mypayment.set_urls(success_url=status_url, fail_url=status_url, cancel_url=status_url, ipn_url=status_url) order_qs=Order.objects.filter(user=request.user,ordered=False) order_items=order_qs[0].orderitems.all() order_item_count=order_qs[0].orderitems.count() order_total=order_qs[0].get_totals() mypayment.set_product_integration(total_amount=Decimal(order_total), currency='BDT', product_category='Mixed', product_name=order_items, num_of_item=order_item_count, shipping_method='Courier', product_profile='None') current_user=request.user mypayment.set_customer_info(name=current_user.profile.full_name, email=current_user, address1=current_user.profile.address_1, address2=current_user.profile.address_1, city=current_user.profile.city, postcode=current_user.profile.zipcode, country=current_user.profile.country, phone=current_user.profile.phone) mypayment.set_shipping_info(shipping_to=current_user.profile.full_name, address=saved_address.address, city=saved_address.city, postcode=saved_address.zipcode, country=saved_address.country) response_data = mypayment.init_payment() return render(request,'payment/payment.html',context={}) it work untill i wrote the last line response_data = mypayment.init_payment() the server shows this TypeError at /payment/pay/ 'User' object is not iterable Request Method: GET Request URL: http://localhost:8000/payment/pay/ Django Version: 3.2.8 Exception Type: TypeError Exception Value: 'User' object is not iterable Help me with this. Thanks in advance -
django modeltranslation doesn't work with such queryset
I'm new to programming. In my blog I want to show a list of categories. If I create a queryset like this: Category.objects.all() my django-modeltranslation works perfectly. But I want to get categories of only published posts. Then my queryset is: Post.objects.values('category__name').filter(is_published=True) However, django-modeltranslation doesn't work. I get values from 'name' field instead 'name_en' or 'name_ru' fields. What is wrong? Here's my models.py : class Category(models.Model): name = models.TextField(max_length=100) url = models.SlugField(max_length=160, unique=True) class Post(models.Model): title = models.TextField('title', max_length=150) category = models.ManyToManyField(Category, related_name='posts', blank=True) -
The model appears but the profile edit form don't appear on it, any idea why?
On my social app that I'm working on, there's still one issue. On my ProfileDetailView, to click on "Edit Profile" the model form appear but there's no form. It was working before but when I fixed the close button and I don't know what happened.. I copied the model html from bootstrap so i probably deleted/changed something and forgot to re-do it.. Form: from django import forms from .models import Profile, Post, Comment class ProfileModelForm(forms.ModelForm): class Meta: model = Profile fields = ('first_name', 'last_name', 'bio', 'avatar') Views: from django.contrib.auth import authenticate, login, logout from django.db import IntegrityError from django.http import HttpResponse, HttpResponseRedirect from django.http.response import JsonResponse from django.shortcuts import render, redirect, resolve_url, get_object_or_404 from django.urls import reverse, reverse_lazy from django.core import serializers from django.core.paginator import Paginator from django.contrib import messages from django.contrib.auth.models import User from django.db.models import Q from django.contrib.auth.decorators import login_required from django.contrib.auth.mixins import LoginRequiredMixin from itertools import chain from .models import Relationship, Post, Profile, Like from django.views.generic import TemplateView, View, UpdateView, DeleteView, ListView, DetailView from .forms import ProfileModelForm, PostModelForm, CommentModelForm def search_view(request): if request.method == "POST": searched = request.POST['searched'] profiles = Profile.objects.filter(slug__contains=searched) return render(request, 'network/search.html', {'searched':searched, 'profiles':profiles}) else: return render(request, 'network/search.html', {}) class ProfileDetailView(LoginRequiredMixin, DetailView): model = Profile … -
Current parameters in url set in the next url in django
I have a url like this http://127.0.0.1:8000/orders/?from=&to=&status=1 I have an button in that page to export all orders but if i have a status I need to send this as an parameter in that url to filter before export <a href="{% url 'orders:export' %}">Export</a> How can I send parameters to that export function -
Django + Google Storage (GCP) multiple bucket
For now i use django 1.11 and using google cloud platform (google storage) to store pdf. my bucket is not open for public and everything was fine, but now i need to store public file (people with link can access uploaded pdf file) I was thinking is it possible for me to have options(choose the bucket target) when upload to google storage? Maybe something like this codes from django.db import models from storages.backends.s3boto import S3BotoStorage class MyModel(models.Model): file_1 = models.FileField() # Uses default storage file_2 = models.FileField(storage=S3BotoStorage(bucket='other-bucket')) I want to do the same as this, but using GCP instead of AWS django-storages with multiple S3 Buckets I'm sorry if this question is too basic, but I've never found the answer until now Thanks for your attention, and hope you can help me and the others who faced the same problem. -
How to get the sum of values in Django template for loop or how i can implement the same in Django view
this is my template <div class="row m-5 p-3 border bg-white"> <table class="table "> <tr> <th>Project Name</th> <th>Total Partnership</th> </tr> {% for pages in page %} <tr> <td>{{pages.name}}</td> <td> {% for i in pages.partnership_set.all %} {{i.partnership}}% {% endfor%} </td> </tr> {% endfor %} </table> </div> my output is: |project Name | Total Partnership | |-------------|-------------------| |project 1. | 100%. | |project 2. | 20% 30% 40%. | |project 3. | 45% 30%. | i just wanted this total partnerships to be added and displayed.how can i do it either in template or else in view? -
How to config media in Django using xampp apache mod_wsgi?
I have a project in Django. It runs completely normally on Local. But when I use XAMPP Apache MOD_WSGI to grow up the web, it can't be run, because it has many folders in the media folder. How can I solve this problem? Thank you very much -
djangosaml2idp problems with launch: saml2.sigver.MissingKey: http://localhost:8000/saml2/metadata/
I'v been trying to launch project(example_setup folder): https://github.com/OTA-Insight/djangosaml2idp/tree/master/example_setup ican anybody answer to men according with documentation. But it does not working. First problem, as I undesrtand is in date of methadata in SP(idp_metadata.xml)- validUntil="2020-12-27T12:41:18Z"> . It does not valid at the moment, and was changed to future date, as example(validUntil="2030-12-27T12:41:18Z"). But nex I got another problem when trying to sign in to SP(localhost:8000) in my browser, I have more problem: Error during SAML2 authentication IncorrectlySigned In attempts to find problem, I found the place where it is occured. In original it iis in tryexcept block, and can't be found easy. Traceback (most recent call last): File "/home/dmitriy/projects/djangosaml2idp/example_setup/idp/djangosaml2idp/views.py", line 251, in get req_info = idp_server.parse_authn_request(request.session['SAMLRequest'], binding) File "/home/dmitriy/projects/djangosaml2idp/example_setup/idp/venv/lib/python3.8/site-packages/saml2/server.py", line 238, in parse_authn_request return self._parse_request(enc_request, AuthnRequest, File "/home/dmitriy/projects/djangosaml2idp/example_setup/idp/venv/lib/python3.8/site-packages/saml2/entity.py", line 1036, in _parse_request _request = _request.loads(xmlstr, binding, origdoc=enc_request, File "/home/dmitriy/projects/djangosaml2idp/example_setup/idp/venv/lib/python3.8/site-packages/saml2/request.py", line 110, in loads return self._loads(xmldata, binding, origdoc, must, File "/home/dmitriy/projects/djangosaml2idp/example_setup/idp/venv/lib/python3.8/site-packages/saml2/request.py", line 51, in _loads print(self.signature_check(xmldata, origdoc=origdoc, File "/home/dmitriy/projects/djangosaml2idp/example_setup/idp/venv/lib/python3.8/site-packages/saml2/sigver.py", line 1662, in correctly_signed_authn_request return self.correctly_signed_message(decoded_xml, 'authn_request', must, origdoc, only_valid_cert=only_valid_cert) File "/home/dmitriy/projects/djangosaml2idp/example_setup/idp/venv/lib/python3.8/site-packages/saml2/sigver.py", line 1653, in correctly_signed_message return self._check_signature( File "/home/dmitriy/projects/djangosaml2idp/example_setup/idp/venv/lib/python3.8/site-packages/saml2/sigver.py", line 1503, in _check_signature raise MissingKey(_issuer) saml2.sigver.MissingKey: http://localhost:8000/saml2/metadata/ Internal Server Error: /idp/login/process/ Some key is missing: Error during SAML2 authentication MissingKey http://localhost:8000/saml2/metadata/ My idp_metada … -
How to loop through values in JSON and assign to another dictionary
I am developing a Python/Django web app. I am trying to parse JSON into a python dictionary, read the values in the dictionary, and assign the values to another dictionary if certain conditions are met. JSON is structured like this: {content: {cars: [0, 1, 2]}, other_stuff: []} Each car has multiple attributes: 0: {"make", "model", "power"...} Each attribute has three variables: make: {"value": "Toyota", "unit": "", "user_edited": "false"} I am trying to assign the values in the JSON to other dictionaries; car_0, car_1 and car_2. In this case the JSON response is otherwise identical considering each car, but the 'make' of the first car is changed to 'Nissan', and I'm trying to then change the make of the car_0 also to 'Nissan'. I'm parsing JSON in the following way: local_cars = [car_0, car_1, car_2] # Dictionaries which are already initialized. print(local_cars[0]['make']['value']) # Prints: Toyota (yes) print(local_cars[1]['make']['value']) # Prints: Toyota (yes) print(local_cars[2]['make']['value']) # Prints: Toyota (yes) counter = 0 if request.method == 'POST': payload = json.loads(request.body) if bool(payload): print(len(local_cars)) # Prints: 3 print(counter, payload['cars'][0]['make']['value']) # Prints: Nissan (yes) print(counter, payload['cars'][1]['make']['value']) # Prints: Toyota (yes) print(counter, payload['cars'][2]['make']['value']) # Prints: Toyota (yes) print(counter, local_cars[0]['make']['value']) # Prints: Toyota (yes) print(counter, local_cars[1]['make']['value']) # Prints: Toyota … -
Django unsupported operand type(s) for +=: 'int' and 'method'
I was trying to implement a simple logic in my e-commerce website where I will be calculating total cart price by looping through orders and getting their price with the help of get_final_price but suddenly this error occurred so please help me Function due to which error is occurring def get_total(self): total_sum = 0 for order_item in self.items.all(): total_sum += order_item.get_final_price() return total_sum Models.py file from django.db import models from django.conf import settings from django.db.models.deletion import CASCADE from django.db.models.fields import DateTimeField from django.urls import reverse # # Create your models here. CATEGORY_CHOICES = ( ('S', 'Shirts'), ('SW', 'Sports wear'), ('OW', 'Outwear') ) LABEL_CHOICES = ( ('P', 'primary'), ('S', 'secondary'), ('D', 'danger') ) class Item(models.Model): title = models.CharField(max_length=100) price = models.FloatField() discount_price = 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() def __str__(self): return self.title def get_absolute_url(self): return reverse("product", kwargs={ 'slug' : self.slug }) def get_add_to_cart_url(self): return reverse("add_to_cart", kwargs={ 'slug' : self.slug }) def get_remove_from_cart_url(self): return reverse("remove_from_cart", kwargs={ 'slug' : self.slug }) class OrderItem(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) ordered = models.BooleanField(default=False) item = models.ForeignKey(Item, on_delete=models.CASCADE) quantity = models.IntegerField(default = 1) def __str__(self): return f"{self.quantity} of {self.item.title}" def get_total_item_price(self): return self.quantity*self.item.price def get_total_discount_item_price(self): … -
Why Django modelform is submitted with enter key
I'm using Django modelform and it's submitted by pressing the enter key. This is what I wanted, but I don't know why it works. I didn't add any JS codes related to keydown but other codes to practice Ajax. Also, I found out that when there's only one input inside the form, it's submitted with the enter key, but my form has two inputs. What I'm doing is to add a comment on a post like instagram. I used Ajax to create a comment instance. models.py class Comment(models.Model): parent_post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name="comments") author = models.CharField(max_length=10) content = models.CharField(max_length=100) forms.py class CommentForm(ModelForm): class Meta: model = Comment exclude = ["parent_post"] HTML {% for post in posts %} <form method="POST" data-id="{{post.id}}" class="d-flex align-items-center w-100 mt-2"> {% load widget_tweaks %} <!-- this is a django package for easy CSS --> {% csrf_token %} {{ form.non_field_errors }} <div class="fieldWrapper"> {{ form.author.errors }} {{ form.author|add_class:"form__author"|attr:"placeholder:name" }} </div> <div class="fieldWrapper w-100"> {{ form.content.errors }} {{ form.content|add_class:"form__content"|attr:"placeholder:content" }} </div> <button class="btn btn-sm btn-warning w-auto">Write</button> </form> {% endfor %} JS (Here I didn't put the codes after getting JSON response from views.py) const forms = document.querySelectorAll("form"); forms.forEach((value) => { const post_id = Number(value.getAttribute("data-id")); value.addEventListener("submit", (e) => { … -
Django memory leak after network disconnected?
The question is Django 2.2 DRF 3.8.2 When the connection is disconnected after a REST request, the RAM is not cleared. That is, data from the database is unloaded and remains in RAM, somewhere deep in Django. How can such a problem be overcome ? -
Migrating Django TextChoices to IntegerChoices
In Django (3.2.8), I have a set of TextChoices, which I would like to change to IntegerChoices. I will keep the keys the same, just the values in the database stored will just differ. I do this for consistency and I'm fixing some legacy code. Naturally, I changed the TextChoices to IntegerChoices, and the corresponding field to an IntegerField. As expected however, upon migrating, I get a django.db.utils.DataError: invalid input syntax for type integer: "option1". I feel like there should be a way that I can define a mapping for this migration to happen, but wasn't able to find any documentation on this. -
When is the space bar becoming + django model Textarea
When my comment is saved instead to showing spaces it replaces it with plus signs For example: My Comment: Hey Guys Please Help me The Comment shown: Hey+Guys%0D%0APlease+Help+me Is this in another format or something if so please tell me how to change it I use a Textarea model form Comment if code is needed Thanks a Lot -
Default storage delete method not working under windows [WinError 123]
I have the following issue. I wrote a unit test which works great under UNIX but breaks for Win10. I am uploading a file using Djangos default_storage: from django.core.files.storage import default_storage uploaded_file = SimpleUploadedFile(self.testfile_name, file.read(), content_type='multipart/form-data') response = self.client.post(url, {'file': uploaded_file}, *args, **kwargs)) testfile_new_path = response.data.get('file') ... default_storage.delete(testfile_new_path) When I want to remove the file after my test, I get an [WinError 123] error stating that the file doesn't exist. Actually this is true because testfile_new_path looks like this: C:\workspace\project\media\http:\testserver\media\path\to\my_file.txt Obviously, something is broken. I wonder how to do this properly. After all, I am using default Django methods. Thx!