Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django ignores if 'add_customer' in request.POST: and saves the form
if all fields are valid my view ignores the if 'add_customer' in request.POST: and goes directly to if Orderform.is_valid(): I cannot change the order because it should read values from field like: if 'add_customer' in request.POST: add_customer_id = Orderform.cleaned_data.get('Customer').ID request.session['add_customer_id'] = add_customer_id return redirect('add_order_view') template: <form action="/backend/ordrer/add/" method="post"> {% csrf_token %} <div class="row g-2 justify-content-md-center"> <div class="col-md-6 pt-2"> <div class="input-group mb-3"> {{ Orderform.Customer }} <input type="hidden" name="add_customer_id" value="{{ item.ID }}"> <button class="btn btn-success mb-3" name="add_customer"><i class="uil-user-plus"></i>Vælg kunde</button> </div> I cannot do write all if '..' two times like: if Orderform.is_valid(): if 'add_customer' in request.POST: add_customer_id = Orderform.cleaned_data.get('Customer').ID request.session['add_customer_id'] = add_customer_id return redirect('add_order_view') else: edit_form = Orderform.save() edit_order_id = edit_form.pk request.session['edit_order_id'] = edit_order_id or is it a common way? -
KeyError DRF when posting
I get KeyError when I post and I don't write either email or telephone. In my code, either email or telephone are required but not both of them. Why is this happening? This is the serializer: class OrderSerializer(serializers.ModelSerializer): class Meta: model = order fields = '__all__' extra_kwargs = { 'email': {'required': False}, 'phonenumber': {'required': False}} def create(self, validated_data): order= Order.objects.create( email=validated_data['email'], phonenumber=validated_data['phonenumber'], food=validated_data['food'] ) This is the model: class Order(models.Model): date = models.DateTimeField(auto_now_add=True) email = models.EmailField(max_length=200, unique=True) phonenumber = models.IntegerField(unique=True) food= models.ManyToManyField('Food', related_name='orders', blank=True) def __str__(self): return self.food -
How to put multiple instances of the same ModelForm on a webpage in Django 3 (Python 3.8)?
I am currently trying to make a webpage that displays multiple instances of the same form on a webpage, in which each form will correspond to a different instance of a model. I have made a simplified hypothetical situation to try and explain... So, for example, you have a django app with two models that store information about people's pets. One is called Species and it stores the breed, height, and weight of the pet, and the other is called Dog and it stores the Species (ForeignKey), name, and location. models.py: class Species(models.Model): breed = models.CharField(max_len=50) height = models.CharField(max_len=50) weight = models.CharField(max_len=50) def __str__(self): return self.breed class Dog(models.Model): species = models.ForeignKey(Species, on_delete=models.CASCADE) name = models.CharField(max_length=50) location = models.CharField(max_length=50) def __str__(self): return self.name Now lets say you already have a dictionary containing the name and breed of a bunch of pet dogs, and now we need to take the user to a page that has a form for each dog in the provided list, so that the location of the dog can be put in. This is the part that I don't know how to do... In my forms.py I created a ModelForm that has all the fields from my model, … -
Why is my Django e-commerce project registering multiple orders for each order made?
I am learning Python by building a simple e-commerce store using Django. I've been following this tutorial for guidance. When I pass an order on the site (on localhost), the order is registered 2 times in the backend. Ie: Order #1, Order #2 in the admin panel. I am wondering how I can merge both so 1 order passed on the site = 1 order on the dashboard? In order 1, the field complete is set to True and the Transaction is filled. In order #2, the Pickup time & Type are both set. Models.py class Order(models.Model): customer = models.ForeignKey(Customer, on_delete=models.SET_NULL, blank=True, null=True) date_ordered = models.DateTimeField(auto_now_add=True) complete = models.BooleanField(default=False, null=True, blank=False) transaction_id = models.CharField(max_length=100, null=True) CHOICES = (('in-store','in-store'), ('curbside','curbside')) pickup_type = models.CharField(max_length=10, choices=CHOICES) pickup_time = models.DateTimeField(null=True, blank=False) View.py def store(request): if request.user.is_authenticated: customer = request.user.customer order, created = Order.objects.get_or_create(customer=customer, complete=False) items = order.orderitem_set.all() cartItems = order.get_cart_items else: items = [] order = {'get_cart_total':0, 'get_cart_items':0, 'shipping':False} cartItems = order['get_cart_items'] products = Product.objects.all() context = {'products': products, 'cartItems':cartItems} return render(request, 'store/store.html', context) def processOrder(request): transaction_id = datetime.datetime.now().timestamp() data = json.loads(request.body) if request.user.is_authenticated: customer = request.user.customer order, created = Order.objects.get_or_create(customer=customer, complete=False) total = float(data['form']['total']) order.transaction_id = transaction_id if total == float(order.get_cart_total): order.complete = … -
How to link already uploaded image in django db
I want to avoid file duplication for if user already have uploaded an image file in db. Django ImageField adds an suffix to the image file if the file already exists. I tried using the solution given by allcaps in following question: Use already uploaded image in Django's ImageField But it only gives me an drop-down option in the upload section, but it doesn't contain anything. -
ImportError: cannot import name 'Flow' from partially initialized module 'firstapp.models.flows' (most likely due to a circular import), how to design
I have a problem, probably in my design. In my Django project I have a 'Flow' object with 'event_reason' field in it, Foreign key to 'Event' object, therefore I need to import Event object, (otherwise I get the error: Cannot create form field for 'event_reason' yet, because its related model 'Event' has not been loaded yet). Therefore my code of my models is (in models/flows.py) from .events import Event class Flow(models.Model): amount = models.DecimalField(max_digits=17, decimal_places=2, default=0.0) flow_type = models.IntegerField(default=-1, choices=FLOW_CHOICES) ... event_reason = models.ForeignKey('Event', on_delete=models.DO_NOTHING, default=None, related_name='events_flow',blank=True, null=True) In addition I have 'amount' and 'flow_type' fields in the 'Flow' objects and I want that the 'post_save' signal will save a new Flow associated to this Event. Therefore the Event model code is (in models/events.py): from .flows import Flow class Event(models.Model): ... amount = models.IntegerField(default=0) flow_type = models.IntegerField(default=-1, choices=FLOW_CHOICES) @receiver(post_save, sender=Event) def my_handler(sender, **kwargs): new_flow = Flow.objects.create(...) And I get the error ImportError: cannot import name 'Flow' from partially initialized module 'firstapp.models.flows' (most likely due to a circular import) I understand that I cannot my a circular import but I want this functionality to work. How to solve this problem? Should I design the objects otherwise? Thank you -
Django formset get field and update it
I have a formset which provides my articles in a row: class OrderItems(models.Model): ID = models.AutoField(primary_key=True) Item = models.ForeignKey('Products', on_delete=models.DO_NOTHING) Quantity = models.IntegerField('Quantity') UnitPrice = models.DecimalField('UnitPrice', max_digits=10, decimal_places=2) TotalPrice = models.DecimalField('TotalPrice', max_digits=10, decimal_places=2) OrderNo = models.ForeignKey('Orders', on_delete=models.DO_NOTHING) and the formset: Itemformset = Itemform(queryset=OrderItems.objects.filter(OrderNo__OrderNo=order_no_int, OrderNo__UserID=request.user.id), form_kwargs={'user': request.user.id}, initial=[{ 'Item': product.ID, 'Quantity': 1, 'UnitPrice': product.Price, 'TotalPrice': product.Price} for product in choosen_products ]) So normaly if I update the quantity I will on a regular form save the field data in session and load it again for the totalprice field. But if I have more then one articles the formset adds a prefix to every formset, and I can't access the field anymore becuase every field gets a own ID. How would it be possible to update the total price if I change the quantity? <div class="input-group bootstrap-touchspin"> {{ items.Quantity }} <button class="btn btn-success" name="update_quantity"><i class="uil-sync"></i></button> </div> view: if 'update_quantity' in request.POST: updated_quantity = Orderform.cleaned_data.get('form-0-Quantity') request.session['Updated_Quantity'] = updated_quantity return redirect('add_order_view') It saves fine in the model with quantity and total price because I overwrite the field for now but I want also display the total price in the template. -
Browsable API: Requests through HTML form work, but not through Raw Data
In Django, I have create and update methods in serializers.py and I'm testing them through the browsable API in the django admin interface. However, when I try to make a PUT request through the Raw Data form, it doesn't actually call the update method I have written. However, when I try to make a PUT request via the HTML form, it does actually call the update method. Does anyone know why this is? I'm using Django==3.1.6 djangorestframework==3.12.2 -
Django - querying by a for loop
I have to fetch the total wrote posts number by each user @staff_member_required def counter(request): posts = Post.objects.all().count() users = User.objects.all() for user in users.iterator(): written_posts = Post.objects.filter(author=user).count() context = {'users': users, 'written_posts': written_posts, 'posts': posts} return render(request, 'account/counter.html', context) But it returns me for all users the same user's number of posts. Anyone can give a piece of advice? -
Django3: How to setup OneToOneField that works with inline admin correctly?
I would like to create a pipeline instance and create the corresponding input file together. My models I have a structure like this. class Pipeline(models.Model): input_file = models.OneToOneField( 'InputFile', on_delete=models.CASCADE, null=False, parent_link=True ) class InputFile(models.Model): pipeline = models.OneToOneField( 'Pipeline', on_delete=models.CASCADE, null=False, parent_link=False ) I tried different combinations of parent_link=True/False, but nothing worked. Only if I set parent_link=True everywhere both instances are created, however, then it is impossible to delete them again. My admin.py looks like: class InputFileAdmin(admin.StackedInline): model = InputFile class PipelineAdmin(admin.ModelAdmin): inlines = [Inputfile] admin.site.register(Pipeline, PipelineAdmin) Whatever combination I always get errors either during creation or deletion. -
Django - Optional field with Serializer
I want to automatically generate the "path" field of my model when I use the create method of my serializer. Otherwise I would like to be able to pass this field in my request to be able to modify it later. I haven't found a way to make a single field of my template optional. Here is my model : models.py class Shop(models.Model): name = models.CharField(max_length=255) category = models.ForeignKey(ShopCategory, on_delete=models.SET_NULL, null=True, blank=True) description = models.TextField(blank=True, null=True) path = models.CharField(max_length=255, unique=True) mustBeLogged = models.BooleanField(default=False) deliveries = models.FloatField(default=7) def __str__(self): return self.name Here is my code : serializer.py class ShopSerializer(serializers.ModelSerializer): class Meta: model = Shop exclude = ['path'] def create(self, validated_data): path = validated_data["name"].replace(" ", "-").lower() path = unidecode.unidecode(path) unique = False while unique == False: if len(Shop.objects.filter(path=path)) == 0: unique = True else: # Generate a random string char = "abcdefghijklmnopqrstuvwxyz" path += "-{}".format("".join(random.sample(char, 5))) shop = Shop.objects.create(**validated_data, path=path) shop.save() return shop views.py def post(self, request): """For admin to create shop""" serializer = ShopSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) return Response(serializer.errors) -
Accessing model field in ManyToMany relation in Django
I am following the example in the documentation: https://docs.djangoproject.com/en/3.2/topics/db/models/#extra-fields-on-many-to-many-relationships from django.db import models class Person(models.Model): name = models.CharField(max_length=128) def __str__(self): return self.name class Group(models.Model): name = models.CharField(max_length=128) members = models.ManyToManyField(Person, through='Membership') def __str__(self): return self.name class Membership(models.Model): person = models.ForeignKey(Person, on_delete=models.CASCADE) group = models.ForeignKey(Group, on_delete=models.CASCADE) date_joined = models.DateField() invite_reason = models.CharField(max_length=64) In this case, given a Person object, how can I access all the groups that Person is in? -
What is the best way to remove a third-party Django app with models in database?
I have a third-party application in my Django project that I'd like to remove. My problem is that if I simply remove it from INSTALLED_APPS, all the models and associated tables that it created in my database will be kept. I know I can manually DROP thoses tables afterwards but I'm wondering if there is a recommended or "clean" way to do so with Django migrations. I created a migration file in one of my apps (the one that used this third-party app) with a migrations.DeleteModel(name='ThirdPartyModel') but it fails to execute because this model is managed by the other app. What is left it to write a RawSQL migration whith a DROP TABLE thirdpartyapp_thirdpartymodel and a DELETE FROM django_content_type WHERE app_label = thirdpartyapp AND model = thirdpartymodel. Is there any other options? How is this type of operations supposed to be done? I'm using Django 3.0. -
GeocoderUnavailable at /
I was doing a Django project that can measure the distance between user and the user's inputted location. For this, I installed geopy and geoip2. Here is my views.py file. from django.shortcuts import render,get_object_or_404 from .models import Measurement from .forms import MeasurementModelForm from geopy.geocoders import Nominatim from geopy.distance import geodesic from .utils import get_geo # Create your views here. def calculate_distance_view(request): obj= get_object_or_404(Measurement,id=1) form=MeasurementModelForm(request.POST or None) geoloactor = Nominatim(user_agent='measurements') ip = '100.37.240.15' country, city, lat, lon = get_geo(ip) #print(country) location = geoloactor.geocode(city) #print('###',location) pointA=(lat,lon) if form.is_valid(): instance = form.save(commit=False) destination_ = form.cleaned_data.get('destination') destination = geoloactor.geocode(destination_) #print(destination) d_lat=destination.latitude d_lon=destination.longitude pointB=(d_lat,d_lon) distance = round(geodesic(pointA,pointB).km,2) instance.location = location instance.distance= distance instance.save() context={ 'distance':obj, 'form':form, } return render(request,'measurements/main.html',context=context) But when I open my browser for the most time it shows this error: GeocoderUnavailable at / HTTPSConnectionPool(host='nominatim.openstreetmap.org', port=443): Max retries exceeded with url: /search?city=New+York&format=json&limit=1 (Caused by ReadTimeoutError("HTTPSConnectionPool(host='nominatim.openstreetmap.org', port=443): Read timed out. (read timeout=1)")) or It Sometimes show different error like: GeocoderInsufficientPrivileges at / Non-successful status code 403 I also tried Photon instead of Nominatim. And the most ridiculously things is that it may work after sometimes. I reckon try and catch might resolve the problem, but I want to know why those errors are occurred … -
How to handle flow of data between groups?
I am building a Django project that lets business owners track their order status. As in, if there is an order of 50 items. The business owner needs to track what is the current status of that specific order. Possible status include : Received Added to cart (at the godown) Packed Bill Generated Dispatched etc Now, each of these statuses will be updated by different users (with appropriate permissions of the group they have been added to). How can I specify the flow of data update. As in, if 'Orange is the group that has appropriate permissions to update the status as 'Added to Cart' and 'Blue' is to update the status as 'Packed' then how can I make sure the person in the 'Blue' group cannot view the order details until the user with 'Orange' group has not updated the status as 'Added to Cart' This is my first question on stackoverflow so if there is any information that you think is missing please let me know. -
How to rename Django settings directory?
By default when creating a new project in Django with: apps/# django-admin startproject example it creates a root directory using the project name: /apps/example/ and inside this root directory it creates a directory with the same name, containing the settings files for the whole project: apps/example/example/ How can I rename the settings directory from apps/example/example/ to apps/example/config/? -
Python list does not work in django with ChartJS
I'm creating a web application where I need to create a few charts. I'm using django 3 and ChartJS. I have created one list for the labels and one list for the data to be inserted into ChartJS. The problem I'm having is that no matter what I try or do the data just will not show up in the graph. When I try to access the data by writing it on the page it does work, but it does not work at all when inserting it into ChartJS for some reason. According to the ChartJS documentation the data field can receive a list of values so I dont understand why this is not working. I have searched quite a lot for solutions to this using google and stackoverflow and while I found some similar threads on stackoverflow, the solutions did not work for me. I tried converting to json, other ways of inserting the data, using a for loop etc, but nothing seems to work no matter what I do. In the web application the labels and values are dynamically created, but at this time to troubleshoot the problem easier I have just created two lists by hand and … -
Python dict giving KeyError even when the key is present in dict
I created a dict by filtering a model like this: article_name_list = ['article name 1', 'article name 2', 'article name 3'...] article_objs = Article.objects.filter(name__in=article_name_list) article_map = {article.name: article.id for article in article_name_list} It gives a dict as expected, something like this: >>> article_map {'article name 1': 10, 'article name 2': 20, 'article name 3': 30, ....} If I try one of the keys, it works, but doesn't work for another key like this: >>> article_map['article name 1'] 10 >>> article_map['article name 3'] 30 >>> article_map['article name 2'] KeyError: 'article name 2' >>> 'article name 2' in article_map False This is weird because I used the article_name_list to filter the articles, but still one of the articles is showing as not present. I verified that both data types are same (string). But still I am unable to find the issue. Extra test: I also checked by using Ctrl + F and searching 'article name 2', and the key is shown included in the search results (This means there are no invisible or unicode characters). P.S. There are around 200+ items in article_map dict, but this key error is only for some (8) items. I can't skip these items that are not … -
Switch django cache backend according to URL
How to use django per-view cache which for the same view uses memcached for some URLs and filesystem cache for others ? -
Read password, django model
I know that django saves passwords like a single-way hash, but for reasons of my app I need to encode an object and I want to use the user's same password, but when I want to use that object I have to decrypt using the same password but the value that returns is hash and it couldn't be possible -
Filtering Django data by dictionary and regular expression?
I was trying to combine filtering Django data through a combination of dictionary and regular expression. So my dictionary looks like this: dict = {'city': '.*?Philadelph.*?$'} And I want to filter the data such that all the rows I retrieve have its city index contains the string "Philadelph". table.objects.all().filter(**dict) However, this does not give me the rows I desire; in fact, it gives me no row at all while all the rows with index "city" have values "Philadephia". I'd appreciate any insights into what might have gone wrong here and how I can begin fixing it. Thank you! -
django edit profile in views if filefield is empty
i am tryng to ignore filefield if its empty but dont works and everytime clears img path in database how can i fix? @login_required def EditProfile(request): user = request.user.id profile = Profile.objects.get(user__id=user) BASE_WIDTH = 400 if request.method == 'POST': form = EditProfileForm(request.POST, request.FILES) if form.is_valid(): if not profile.picture: pass else: profile.picture = form.cleaned_data.get('picture') profile.name = form.cleaned_data.get('name') profile.profile_info = form.cleaned_data.get('profile_info') profile.save() return redirect('index') else: form = EditProfileForm() context = { 'form':form, } return render(request, 'edit_profile.html', context) -
Django-Baton Configuration
I am trying to install and configure the Django-baton to my django project, I followed the steps in the official documentation : Here is my Installed_apps in settings.py : INSTALLED_APPS = [ 'baton', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'users.apps.UsersConfig', 'crispy_forms', 'baton.autodiscover', ] and at the end of the file BATON = { 'SITE_HEADER': 'Coficab Administration', 'SITE_TITLE': 'Coficab Admin', 'INDEX_TITLE': 'Site administration', 'CONFIRM_UNSAVED_CHANGES': True, 'SHOW_MULTIPART_UPLOADING': True, 'ENABLE_IMAGES_PREVIEW': True, 'CHANGELIST_FILTERS_IN_MODAL': True, 'CHANGELIST_FILTERS_ALWAYS_OPEN': False, 'CHANGELIST_FILTERS_FORM': True, } Also changed my admin url in the urls.py but the display is showing as follows : -
Is "sessions" empty by default in Django? And if, how is the automated login managed?
I'm trying to view all the (keys,values) pair of the sessions-attribute, since I'm writing our cookie-policy thus I need to know exactly what Django sets as default. I have the following view: def MySessions(request): keys =[] values = [] for key, value in request.session.items(): values.append(value) keys.append(key) context = {"keys":keys,"values":values} return render(request,"my_app/my_sessions.html",context = context) and the template {% extends "my_app/base.html" %} {% block content %} {% load static %} <p> {{keys}} </p> <p> {{values}} </p> {% endblock %} In at my page I just have (please let me know, if there's a more easy way to accomplish this) [] [] Unless I have made a mistake, is "session" then empty by default e.g no session is set by Django by default? And if it is, how does Django then log me in automatically? -
Django: problem of displaying uploaded images
I'm building a photo blog via Django, it has a very basic structure: 1)a list page: each post has a cover picture 2)severals detail pages correspondant: each page contains multiple pictures. At the list page, things are all good, the cover picture displayed correctely, but for the detail web page, the pictures that I uploaded from django admin won't show up, though they can be found in the local folder \media. I checked the page in Chrome, I got this: <img src(unknown) alt>. I'm confused. Thanks a lot for your time and help. structure : lyv_dev #project name --settings.py --urls.py media --upload1.jpg --upload2.jpg --upload3.jpg -- ... project #app name -- templates --projects -- base.html -- list.html -- detail.html -- urls.py -- admin.py -- views.py static -- css -- style.css db.sqlite3 manage.py models.py from django.db import models from django.urls import reverse # models project class Project(models.Model): title = models.CharField(max_length = 250) slug = models.SlugField(max_length = 250, unique_for_date = 'publish') text = models.TextField() year = models.IntegerField(default = 2020) # couv: this is a cover picture couv = models.FileField(blank=True) height = models.IntegerField(default=0) weidth = models.IntegerField(default=0) class Meta: ordering = ('-publish', ) def __str__(self): return self.title def get_absolute_url(self): return reverse('projects:project_detail', args=[self.slug]) # Images related …