Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Count total sum of values for a category
I have a table that contains a set of bills. Each bill is categorized. Like CreditCard, Loan, and Personal... Im trying to get the total amount for category. class Debt(models.Model): Categories = [ ('Credit Card', 'Credit Card'), ('Mortgage', 'Mortgage'), ('Loan', 'Loan'), ('Household Bill', 'Household Bill'), ('Social', 'Social'), ('Personal', 'Personal') ] user = models.ForeignKey(User, on_delete=models.CASCADE) creditor = models.ForeignKey(Creditor, on_delete=models.CASCADE) amount = models.FloatField(blank=True,null=True) category = models.CharField(max_length=50, blank=True,null=True, I think that using annotate is the correct approach, but I'm can't work out how to group the categories together to get the total. all_outgoing = Debt.objects.annotate(total=Sum('amount')).filter(category='personal') I don't think I should need to create a annotate for each category, but maybe I do? Is there a better way? Is the better way to wrap in a loop and pass the category onto the filter? Thanks -
Generate a pdf file of the data from database
I want to display this context inside an invoice html page but I seem to be stuck at getting data. I want this data to be displayed at the invoice page. Currently, it is giving me Error:''QuerySet' object has no attribute 'product'' models.py: class PurchaseItem(models.Model): product = models.ForeignKey(Item, on_delete=models.CASCADE) quantity = models.PositiveSmallIntegerField() purchase_price = models.DecimalField(max_digits=6, decimal_places=2) paid_amount = models.DecimalField(max_digits=6, decimal_places=2) views.py: def get_context_data(request, **kwargs): purchases = PurchaseItem.objects.all() context={ "company": { "name": "Mc-Services", "address": "1080, Vienna, Austria", "phone": "(818) XXX XXXX", "email": "contact@mcservice---.com", 'product': purchases.product, 'price' : purchases.product.price, 'quantity' : purchases.quantity, }} return render(request, 'purchase/pdf_template.html', context) and the html file pdf_template.html: <tbody> {% for purchase in purchases %} <tr> <td class="no" >{{purchase.product}}</td> <td class="qty" >{{purchase.quantity}}</td> <td class="total" >${{purchase.product.price}}</td> </tr> {% endfor %} </tbody> -
Is there a way to fix this django stripe integration error?
We are integrating stripe for as us stripe account. There is no connection to India but we get this error... Instead of the payment url, we get this : Request req_OuSWvylGF8wZDi: As per Indian regulations, only registered Indian businesses (i.e. sole proprietorships, limited liability partnerships and companies, but not individuals) can accept international payments. More info here: https://stripe.com/docs/ Please help to fix this error. We tried integrating stripe , backend django for a us based company. But we keep on getting Indian regulations error. We don't know how. There is not a relation to India. -
how to add a python ide using codemirror to a django app
I'm new to Django and web-dev and was looking for a good tutorial explaining how to add a codemirror IDE to a django app but haven't been to successful can anyone lead me in the right direction or just throw up some basic code ie: models.py views.py settings.py etc of a basic python ide set up. any help would be greatly appreciated thanks in advance. -
How to render out DateTime selection on form
I am basically trying to make a website that has a form to fill in for someone to select what equipment they need and have another for returning the equipment, I have it all set up and can see it in the admin panel, everything is working fine but when navigating to the return page as this is set out a little different to the original form to collect and by that I mean instead of "Comments" its "ReturnDate", I have this set as DateField apposed and ran the migrations, now when navigating to the page I can not see a Calander to select a date to return the equipment. Any help would be much appreciated, fairly new to Python, Django. I will attach my views, models, form, etc so you can see what I have done. VIEWS from django.shortcuts import render from django.http import JsonResponse from main.models import WFHSHEET from django.http import HttpResponse, response, HttpResponseRedirect from .forms import WFHLIST, RETURNLIST from django.core.mail import send_mail # Create your views here. def home(response): return render(response, 'home.html', {}) def wfhsheet(response): if response.method == "POST": form = WFHLIST(response.POST) if form.is_valid(): form.save() else: form = WFHLIST() return render(response, "form.html", {"form":form}) def returnsheet(response): if response.method … -
What do "-" user in django admin mean? Can't delete or open
I'm trying to learn Django and following a tutorial, I have a "-" user in my Customer Model, I'm not sure where it came from. If I attempt to delete or open it, the error below appears. I tried to verify if my Customer Model is working by deleting other named users and It's working fine. What does the "-" entry means? Thank you for the help. Customer Model page in Django admin TypeError at /admin/accounts/customer/3/change/ str returned non-string (type NoneType) Request Method: GET Request URL: http://127.0.0.1:8000/admin/accounts/customer/3/change/ Django Version: 4.1.3 Exception Type: TypeError Exception Value: str returned non-string (type NoneType) Exception Location: C:\Users\user\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\contrib\admin\options.py, line 1859, in _changeform_view Raised during: django.contrib.admin.options.change_view Python Executable: C:\Users\user\AppData\Local\Programs\Python\Python311\python.exe Python Version: 3.11.0 Python Path: ['C:\Users\user\Desktop\crm', 'C:\Users\user\AppData\Local\Programs\Python\Python311\python311.zip', 'C:\Users\user\AppData\Local\Programs\Python\Python311\Lib', 'C:\Users\user\AppData\Local\Programs\Python\Python311\DLLs', 'C:\Users\user\AppData\Local\Programs\Python\Python311', 'C:\Users\user\AppData\Local\Programs\Python\Python311\Lib\site-packages'] Server time: Sun, 01 Jan 2023 15:43:55 +0000 I tried to verify if my Customer Model is working by deleting other named users and It's working fine. -
No diffrence after implementing indexes into Django Model
I want to speed-up my app. I work with large dataset ~26 million records like this: enter image description here The long query processing time (page loading) encouraged me to create indexes. But after implementing I dont see any page loading time difference. My models.py file: enter image description here My views.py file: enter image description here My forms.py file: enter image description here I've tried doing few combinations of indexes. 1) enter image description here 2) enter image description here according to query in views.py which is: enter image description here The speed is still as low as in the version without indexes and takes about 20 second to load a page. How to create indexes that works? -
How I can show the table of all user which role is based on specific values
I have a User Table in Django. It has different role values. I would like to show all user which role is based on a specific value. I would like to show all user in Django admin panel which role is couple only. In admin.py: from django.contrib import admin from django.contrib.auth import admin as auth_admin from django.contrib.auth import get_user_model from users.forms import UserChangeForm, UserCreationForm from users.models import EmailConfirmationToken User = get_user_model() @admin.register(User) class UserAdmin(auth_admin.UserAdmin): form = UserChangeForm add_form = UserCreationForm fieldsets = (("User", {"fields": ("name", "wedding_date", "wedding_zip_code", "role", "photo", "subscription", "leads")}),) + auth_admin.UserAdmin.fieldsets list_display = ["username", "name", "is_superuser", "is_active"] search_fields = ["name", "subscription"] -
How to add images in the project Django
My logo doesn't work in Django project: Code bellow: index.html: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Главная</title> {% load static %} <img src="{% static 'media/logo.svg' %}" alt="My logo"> </head> <body> </body> <footer> </footer> </html> settings.py: STATIC_URL = 'static/' The structure of project: When i try yo open yje console it takes: Failed to load resource: the server responded with a status of 404 (Not Found) Logo is in a static/media/logo.svg -
Use Throttling to restrict the number of times a certain request can be made globally
I am using Django Throttling, and want to add a behavior that will throttle users from calling a certain request more than X times in rate - globally. Using AnonRateThrottle or UserRateThrottle is not good enough for me, because it checks the number of times that a certain User or IP address made the request. I want to limit the global calls to a certain api_view, no matter who made the request. For example, if the rate is 1/min and user X made a request, than every other user will be throttled for the next minute. -
How can I retrieve tag attributes from an HTTP XML request in Django REST?
I'm trying to send an XML file as a payload over HTTP to a Django development server on my local machine. I have no issues sending HTTP POST requests with JSON payloads and I understand that XML functionality does not come with Django REST framework out of the box, so I installed djangorestframework-xml. I used a parser decorator in my api view function definition like so: @api_view(['GET', 'POST']) @parser_classes([XMLParser]) def my_view(request): if request.method =='GET': pass if request.method == 'POST': return Response({'received_data': request.data}) The issue is, the way the data is structured, the information I need to parse is stored as tag attributes, like so: <CEF> <Element> <p x="1" y="2"/> </Element> </CEF> And when it is received by Django, request.data does not include attribute tag data: { "received_data": { "Element": { "p": null } } } Is there a header I could add to the HTTP request to preserve the xml tag attribute data? Any pointers are greatly appreciated! I tried different configurations for the tag data, but ultimately, I have no control over the data source and the way the data is structured in the xml file. -
JSONField validation based on another model object
yelp, im stuck. Im trying to build an online bicycleshop and i cant seem to figure this one out. Class Product(models.Model): name_of_bicycle = models.Charfield() Class Bid(models.Model): bid_number = models.PositiveIntegerField() name_of_bidder = models.Charfield() bid = models.JSONField() The JSONField should contain [name_of_bicycle, bidding amount]. Is this possible? Do i have to use JSON schema? I appreciate the help. ——————————————————- -
Why the Imgaes doesn't work in my Django Project
My logo doesn't work in Django project: Code bellow: index.html: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Главная</title> {% load static %} <img src="{% static 'media/logo.svg' %}" alt="My logo"> </head> <body> </body> <footer> </footer> </html> settings.py: STATIC_URL = 'static/' The structure of project: -
How to delete entry in django?
there is a small django project that has methods for creating a topic, creating and editing posts within it. I don't understand how to write a method to delete a post in a topic views.py from django.shortcuts import render, redirect from django.contrib.auth.decorators import login_required from .models import Topic, Entry from .forms import TopicForm, EntryForm from django.http import Http404 @login_required() def new_entry(request, topic_id): topic = Topic.objects.get(id=topic_id) check_topic_owner(topic.owner, request) if request.method != "POST": form = EntryForm() else: form = EntryForm(data=request.POST) if form.is_valid(): new_entry = form.save(commit=False) new_entry.topic = topic new_entry.save() return redirect('composetopic:topic', topic_id=topic_id) context = {'topic': topic, 'form': form} return render(request, 'composetopic/new_entry.html', context) @login_required() def edit_entry(request, entry_id): entry = Entry.objects.get(id=entry_id) topic = entry.topic check_topic_owner(topic.owner, request) if request.method != "POST": form = EntryForm(instance=entry) else: form = EntryForm(instance=entry, data=request.POST) if form.is_valid(): form.save() return redirect('composetopic:topic', topic_id=topic.id) context = {'entry': entry, 'topic': topic, 'form': form} return render(request, 'composetopic/edit_entry.html', context) def check_topic_owner(owner, request): if owner != request.user: raise Http404 i was tried to add delete_entry() function, but its not working -
django still uses StatReloader even though watchman & pywatchman are installed
I wanted to slow down the auto-reload feature of django's runserver for 7 seconds. While searching for a solution, I read on the django documentation https://docs.djangoproject.com/en/4.1/ref/django-admin/#s-runserver that I should install Watchman as well as pywatchman and that django will use that instead for which I can add a timeout period for reload after file change. I also read on https://adamj.eu/tech/2021/01/20/efficient-reloading-in-djangos-runserver-with-watchman/ that after installation django's runserver will show Watching for file changes with WatchmanReloader instead of Watching for file changes with StatReloader. I also add a .watchmanconfig like this: {"ignore_dirs": [".git", ".vscode", "venv", "htmlcov", "media", ]} But on mine it still uses StatReloader even though watchman & pywatchman are installed in accordance with their doc. django version: 4.1.2 python version: 3.8.16 watchman version: 20221225.010033.0 pywatchman version: 1.4.1 Can anybody help? My gratitude before hand -
Django admin panel: How to show models with ManyToMany and OneToMany relationship within another model?
I tried so hard to write a question title that could somewhat point to the problem, but couldn't. So here is the question in details: I have a Product model, a Usage model and a SubUsage model. Usage model has a OneToMAny relationship with SubUsage model, where for every usage there may be various sub_usages, and the Product model has ManyToMany relationship with these two models, in which a product may have different usages and sub_usages. These models are as below: class Usage(models.Model): id = models.UUIDField( primary_key=True, default=uuid.uuid4, editable=False, ) usage_name = models.CharField( max_length=255, null=False, blank=False, unique=True, ) class SubUsage(models.Model): id = models.UUIDField( primary_key=True, default=uuid.uuid4, editable=False, ) sub_usage_name = models.CharField( max_length=255, null=False, blank=False, ) usage = models.ForeignKey( Usage, on_delete=models.CASCADE, ) class Product(models.Model): id = models.UUIDField( primary_key=True, default=uuid.uuid4, editable=False, ) product_name = models.CharField( max_length=255, null=False, blank=False, unique=True, ) usage = models.ManyToManyField(Usage) sub_usage = models.ManyToManyField(SubUsage) Now in the admin panel, I have product form, in which I can choose usages and sub_usages; as the image below: The problem is that, each usage has different sub_usages, which may has the same name as another sub_usage of another usage; I want to be able to know that each item in sub_usages list is related … -
Fetching a collection of documents and sub collections from firestore to django web app
I have a Flutter mobile app that is connected to a Firestore database, where I upload some data from the mobile app. The goal here is to use Django in a web app to display all collections from Firestore with all of their documents and sub-collection fields' values in the form of a table. I managed to fetch a single document with all its values, but when I tried to loop through the documents, I hit a dead end as every time I try something, it fails. And for some reason whenever I try to loop throgh the docs to display all the IDs for example, it only reads the documents which were created manualy from firestore side if that makes any sense. For example here is the output of the following code: all_users_ref_2 = db.collection('users').stream() for users in all_users_ref_2: abc= (u'{} => {}'.format(users.id, users.to_dict())) print(abc) [![enter image description here][1]][1] As you can see there are only 8 docs IDs printed while the reality is I have +80 docs which were created from the mobile app The structure of my database is a bit complex, so I will add some pictures for a clearer image. [![enter image description here][2]][2] as … -
Django UpdateView - how to return an HttpResponse instead of a URL from "get_success_url"
In the get_success_url you are supposed to provide a reverse url, however I want to pass a simple HTTPResponse (without a template), how can I accomplish that with an UpdateView like so? class SomeView(UpdateView): model = MyModel form_class = MyModelForm template_name = 'form.html' def get_success_url(self): response = HttpResponse('', status=204) return response -
Access .env or environment content inside of Django for a package that uses environment variables
So I have to utilize a package that requires an API_KEY set in the environment to function. It works normally when not in Django, so to make an REST API I utilize the package like such: class QAView(APIView): def post(self, request, format=None): try: answer = internet_ml.NLP.no_context.QA.answer(query) content = json.dumps( {"error": "", "response": answer[0], "resources": answer[1]} ) except: content = json.dumps( {"error": "Google API key not present in .env or environment"} ) return Response(content) And this always returns the except / error. The package itself works when not running in Django. How would I fix this? -
Save additional forms in Django
I have an original form (which is the result of three ModelForms) and I'm creating additional forms for two of those in the front-end. Everything is working fine except for when saving the data. The originally rendered form saves correctly all the instances in the database. However, all the 'additionally added forms' won't save. In the form I have this button that with HTMX adds a new form: <button type="button" class="btn btn-tertiary" hx-get="{% url 'buyandsell:create-product' %}" hx-target="#productforms" hx-swap="beforeend">Add new product</button> This 'create-product' partial form corresponds to this view: def create_product(request): producto_form = ProductoForm() imagen_form = ImagenForm() context = { 'producto_form' : producto_form, 'imagen_form' : imagen_form } return render(request, 'buyandsell/partials/producto-form.html', context) But I guess the view I need to change for saving the forms is the original main view. I tried iterating over 'producto_forms' but it doesn't let me (as I think that iteration refers to the fields of the form). This is the view function that is working well before adding additional products: def anunciocreateview(request): if request.method == "POST": anuncio_form = AnuncioForm(request.POST or None) producto_form = ProductoForm(request.POST or None) imagen_form = ImagenForm(request.POST, request.FILES) if all([anuncio_form.is_valid(), producto_form.is_valid(), imagen_form.is_valid()]): anuncio = anuncio_form.save(commit=False) anuncio.anunciante = request.user anuncio.save() producto = producto_form.save(commit=False) producto.anuncio = anuncio … -
How can I select only th row that has a specific sum total less than in Django?
I have this Model class statics(models.Model): user= models.ForeignKey(Users, on_delete=models.CASCADE) amount = models.DecimalField(max_digits = 100, decimal_places = 8, default=0) Let's say I have a table like this: id | amount 1 | 21 2 | 20 3 | 10 4 | 15 I want in results only to select the rows that the sum of thier amount is less then 55 In this case the result should be id | amount 1 | 21 2 | 20 3 | 10 because all these rows amount sum is less than 55 This is what I tried to do: data=statics.objects.annotate(total=Sum('amount')).filter(total__lte=55) But it didn't work as all rows had the total always equal to their amount not the sum -
Why do I get "'Image' object has no attribute 'name'" error when I visit Images database in admin panel, using Django?
I try to implement a ForeignKey in my models and I get an error when I save multiply images to the Image model. In two words the error started to appear when I wrote this line in Views.py: post = instance, I also tried to make it post = instance.id, but I got another error. The post fileld is models.ForeignKey('Post', on_delete=models.CASCADE). As I have understood, when you use ForeignKey you can't put an integer to an object in the field of it's id. This is why I have put a whole instance. What do I do wrong? Thank you in advance. This is my code: Views.py: def adminpanel(request): if request.method == "POST": form = PostForm(request.POST, request.FILES) instance = form.save(commit=False) if form.is_valid(): form.save() images = request.FILES.getlist('image') for image in images: picture = Image.objects.create( post = instance, image = image, ) Models.py: from django.db import models from imagekit.models import ImageSpecField #from PIL import Image import PIL.Image # Create your models here. class Post(models.Model): name = models.CharField(max_length = 100) thumbnail = models.ImageField(upload_to ='uploads/posts/') thumbnail_small = ImageSpecField(source='thumbnail', format='JPEG', options={'quality': 50}) category = models.CharField(max_length = 100, default = 'initial') slug = models.SlugField(default = 'initial',unique = True) body = models.TextField(default = 'initial') created_at = models.DateTimeField(auto_now_add=True) def … -
django admin - add multiple entries to db with single form submit
I have a model Point where i have a field called name charField. I trying to add multiple entries on Point with single Form submission. For example, the form has textarea field where i will entry 10 names line by line and then i try to split names one by one and save to point table. class Point(models.Model): name = models.CharField(blank=True) class PointForm(forms.ModelForm): pointlist = forms.CharField(widget=forms.Textarea, required=False) class Meta: model = Point fields = '__all__' def save(self, commit=True): return super(Point, self).save(commit=False) I tried to add multiple entries with single form submission in django admin page getting below error: super(type, obj): obj must be an instance or subtype of type -
How do I order related objects of ManyToMany field in Django?
So I have a ManyToMany field, and the related objects need to be ordered by id. But somehow I cannot order it as intended. This is how the models look like: class Answer(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE, related_name='answer', null=True) body = models.TextField(blank=True, null=True) class AllAnswers(models.Model): answers = models.ManyToManyField(Answer, null=True) title = models.CharField(blank=True, null=True, max_length=30) created_at = models.DateField(auto_now_add=True) Now, let's say there are five Answer objects (ordered by id) : answer1, answer2, answer3, answer4, answer5. In my views.py, I'm creating an AllAnswers object but cannot give order to the Answer objects, like the code below. AllAnswers.objects.create( title = 'title #1', ) new_article = AllAnswers.objects.get(title='title #1') all_answers = Answer.objects.all().order_by('id') # This would get answer1 through answer5 new_article.answers.add(*all_answers) Now what I expect is the answers in new_article object to be displayed in the order I set. (by id) But in the template, the order is not the way I intended. (I can't figure out which order it is being displayed, but it definitely is NOT by id) # article.html ... {% for a in new_article.answers.all %} {{x.body}} {% endfor %} ... -
How to given reset password email name on django
How can I set custom django when email name when password reset email is sent.