Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Calculate and save the total of an invoice in django
When i add an invoice, the Total is always 0 but when i update without any changes, it s updated with the totalsubtotals(). i understand that there are many calculations and in my case, the total calculation is done before the subtotals. Any recommandations. class Invoice(models.Model): date = models.DateField(default=timezone.now) client = models.ForeignKey('Client',on_delete=models.PROTECT) total = models.DecimalField(default=0, max_digits=20, decimal_places=2) def totalsubtotals(self): items = self.invoiceitem_set.all() total = 0 for item in items: total += item.subtotal return total def save(self, *args, **kwargs): self.total = self.totalsubtotals() super(Invoice, self).save(*args, **kwargs) class InvoiceItem(models.Model): invoice = models.ForeignKey('Invoice', on_delete=models.CASCADE) product = models.ForeignKey(Product, on_delete=models.PROTECT) price = models.DecimalField(max_digits=20, decimal_places=2) quantity = models.DecimalField(max_digits=20, decimal_places=2) subtotal = models.DecimalField(default=0, max_digits=20, decimal_places=2) def save(self, *args, **kwargs): self.subtotal = self.price * self.quantity super(InvoiceItem, self).save(*args, **kwargs) -
Django | Serve two uploaded images version - WebP and JPEG
I just want to ask you for a best practice, how to serve both WebP and JPEG images via Django to users. I have a website about vehicles - there are about 1 000 vehicles added every day and every vehicle has about 10 images. That is a lot of images. I have made a custom "import django-admin command", which parse a vehicle: It downloads a JPEG image from the source (10 images for a single vehicle) Then for all downloaded images a watermark is applied After that, this image is converted to WebP format and uploaded via Django save() to Images table, which has a ForeignKey to a Vehicle (I am using ImageField for that) Then it compresses original JPEG images and via shutil.move these compressed JPEG images are moved to the same folder, where WebP image formats are stored. Because I am using an AMP HTML, I can simply do a fallback from WebP to JPEG for browsers, which has no WebP support. And because images are in the same /media/.../ folder, it works perfectly. But today I have found, that this method is not perfect. When there are the same image names, Django in save() method get_random_string() … -
How to write a shell command in the Procfile to copy a database from production to staging on Heroku?
I wanted to use Procfile in a Django project to copy the database we use in production to the staging environment on Heroku. This would then be done any time there is a deployment on staging. I could not find relevant information however. Using the Heroku CLI, it is pretty straightforward as the below suffice: heroku pg:copy your-app::DATABASE_URL DATABASE_URL -a yourapp-staging The way I would like to use it is via proper use of curl and the Heroku API. So far, the .sh file I use in the Procfile is like this : echo "Beginning workflow specific to STAGING" echo "Turning off the web dynos."; curl -X PATCH https://api.heroku.com/apps/${app_name_or_id} \ -d "{\"maintenance\": true }" \ -H "Content-Type: application/json" \ -H "Accept: application/vnd.heroku+json; version=3" \ -H "Authorization: Bearer $HEROKU_API_KEY" echo "Copying from production database to staging database ..."; """MISSING CODE HERE""" echo "Turning the staging server back on."; curl -X PATCH https://api.heroku.com/apps/${app_name_or_id} \ -d "{\"maintenance\": false }" \ -H "Content-Type: application/json" \ -H "Accept: application/vnd.heroku+json; version=3" \ -H "Authorization: Bearer $HEROKU_API_KEY" Would anyone know how to do it, please? -
Django: admin interface: how to change user password
In Django: I have created a super user and can view all the users I have also implemented forgot password for my user, who can input their email and a password reset link is sent to their email and then the user can reset his password But how can admin change some users password from the admin dashboard -
Which Django model relationship is appropriate?
Let's say I create a Profile extending the Django User Model, each time a new user is created. And I want to store multiple items in a field, for example, 10 track names in the track name field for a particular user, in the Profile(will differ from user to user). Which model relationship can help achieve this? Or do I create a new model for songs, named preferably "songs", and use a model relationship to Profile? What is the best way to do this? models.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) track_name = models.CharField(on_delete= models.CASCADE , related_name="track") artiste_name= models.CharField(on_delete=models.CASCADE , related_name="artiste") album_name = models.CharField(on_delete= models.CASCADE, related_name= "album") class Meta: db_table = "Profile" def __str__(self): return self.track_name -
List only three element n my homepage in django/python
{% for post in BusinessPost %} <li>{{ post.title}} -- {{post.author}} -- {{post.source_date}} </li> {% endfor %} this is my code to get all the element of my model into listView page but i only wat to get the first 3 element of this list. Can anyone help -
Data transfer from one HTML page to another
When creating a technical site, I faced the need to transfer data and save it in a file. I am making a website in Django. In models I create input data. I receive these data in HTML and, if necessary, the user changes them and JS performs the necessary calculations, the results of which are sent to the same page. It is possible to do a lot of analytical work on outgoing data (build graphs, calculate a loan, calculate various project risks). I prefer to create several pages so as not to fill one. All pages have already been built. There was a problem of this nature: On the main page, JS did his job but I do not know how to access this data on other pages. Is there a solution to write a JSON string to a file or send them to Django model (update static data). I read a lot and looked for solutions, but I could not figure it out until the end. Maybe someone knows the solution. Thank you in advance. If need more information, please let me know. This is my first request for help, so please don’t be strict if I cannot ask … -
Django dynamic filtered ListView returning error: get() got multiple values for argument 'self'
I need some help trouble shooting this. I think I'm doing what is suggested by the django docs (https://docs.djangoproject.com/en/3.1/topics/class-based-views/generic-display/), but I keep getting this error: get() got multiple values for argument 'self' textbook_list.html <a href="{% url 'lesson_list' textbook.pk %}"> <button type="button" class="btn btn-info">More Info</button> </a> urls.py urlpatterns = [path('grade/<int:pk>/', TextbookLessonList.as_view(), name='lesson_list')] views.py class TextbookLessonList(ListView): template_name = 'textbook_lesson_list.html' def get_queryset(self): self.textbook = get_object_or_404(Textbook, self=self.kwargs['pk']) #This is the offending line return TextbookLesson.objects.filter(textbook.pk==self.textbook) -
Django Template Condition with css
my Question is: I want do a condition in Django Template with css but it didnt work. <label>{% if not typ.required %} {% trans 'Bitte Auswahl treffen' %}{% endif %}</label> <input type="checkbox" {% if typ.required %} style="display:none;" checked="checked" {% endif %} name="checkbox" data-toggle="toggle" id="{{ typ.typ_id }}" value="{{ cookie_id }}" /> {% if typ.required %} style="display:none;" checked="checked"{% endif %} checked="checked" works but the Style not. If i press f12 to watch the site i see this style in the input type Thank you guys -
Django returning form error but the input seems to be valid
One of my models is a Product model which has 3 different price fields, so that one of its prices can be chosen when creating an order. I created a select input in one of my forms to allow the user to choose one of the prices, but when the form is submitted, Django returns an error telling me to introduce a valid number, even though I checked the request.POST and the value it's sending is a valid number. models.py: class Product(models.Model): ... price_1 = models.DecimalField(max_digits=10, decimal_places=2, null=True, blank=True, default=0) # Separador de miles price_2 = models.DecimalField(max_digits=10, decimal_places=2, null=True, blank=True, default=0) # Separador de miles price_3 = models.DecimalField(max_digits=10, decimal_places=2, null=True, blank=True, default=0) # Separador de miles forms.py: class CartAddProductForm(forms.Form): price = forms.DecimalField() quantity = forms.IntegerField( label ='Amount' ) override = forms.BooleanField(required=False, initial=False, widget=forms.HiddenInput) views.py: @require_POST def cart_add(request, product_id): cart = Cart(request) product = get_object_or_404(Product, id=product_id) form = CartAddProductForm(request.POST) if form.is_valid(): cd = form.cleaned_data cart.add(product=product, quantity=cd['quantity'], price=cd['price'], override_quantity=cd['override']) return redirect('cart:cart_detail') Template: <form action="{% url 'cart:cart_add' product.id %}" method="post"> {% csrf_token %} <div class="form-group"> <label for="id_price">Precio</label> <select name="price" id="id_price" class="select2 form-control" data-toggle="select2" required> <option value="{{ product.price_1 }}" selected>Precio retail: ${{ product.price_1|intcomma }}</option> {% if product.price_2 %} <option value="{{ product.price_2 }}">Precio mayorista: ${{ … -
How can i change the _id for the document django elasticsearch dsl python
For thew document class i want to change to _id used to be a slug or another option @registry.register_document class TestDocument(Document): id = fields.IntegerField(attr='id', multi=True) name = fields.TextField( analyzer=html_strip, fields={ 'raw': fields.TextField(analyzer='keyword'), } ) built_area = fields.TextField( analyzer=html_strip, fields={ 'raw': fields.TextField(analyzer='keyword'), } ) living_area = fields.TextField( analyzer=html_strip, fields={ 'raw': fields.TextField(analyzer='keyword'), } ) project = fields.ObjectField(properties={ 'name': fields.TextField(), 'pk': fields.TextField(), }) this thread mentions the meta, but do not works -
OperationalError at /admin/login/ attempt to write a readonly database
I have deployed my Django application in the CENTOS 7, it up and running , all select operation from data base is working fine and now i am unable to login to admin page and also unable to perform any write operations on the Data base , i am using defaut db.sqlite3 as a my data base, Please i have SELinux is enabled, which we need for other security policies, please help, i have followed all other Stack-overflow answers given chown apache:apache permissions to project directory also for db.sqlite3, Also i have used enabled http_unified as 1 also, but not working PFB below errors attempt to write a readonly database Request Method: POST Request URL: http://192.168.225.45/ Django Version: 3.1 Exception Type: OperationalError Exception Value: attempt to write a readonly database Exception Location: /home/www/project/venv/lib/python3.6/site-packages/django/db/backends/sqlite3/base.py, line 413, in execute Python Executable: /usr/local/bin/python3 Python Version: 3.6.9 ignored_wrapper_args (False, {'connection': <django.db.backends.sqlite3.base.DatabaseWrapper object at 0x7fd9f6760278>, 'cursor': <django.db.backends.utils.CursorDebugWrapper object at 0x7fd9f7f69e48>}) params ['Sunag', 12331, 'M'] self <django.db.backends.utils.CursorDebugWrapper object at 0x7fd9f7f69e48> sql ('INSERT INTO "testapp_candidatemodel" ("name", "rollno", "shirt_size") VALUES ' '(%s, %s, %s)') -
Forbidden (CSRF cookie not set.) Django
I'm trying to make a Post request from my React front-end to Django back-end but I'm getting 403 (forbidden) error everytime I try to make a POST request. I know the problem is probably csrf_token but I used the token both inside my POSTrequest and on my back-end. This following is my JavaScript function makes POSTrequest. function getCookie(name) { let cookieValue = null; if (document.cookie && document.cookie !== "") { const cookies = document.cookie.split(";"); for (let i = 0; i < cookies.length; i++) { const cookie = cookies[i].trim(); // Does this cookie string begin with the name we want? if (cookie.substring(0, name.length + 1) === name + "=") { cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); break; } } } return cookieValue; } export function getCurrentUser() { const url = "http://localhost:8000/accounts/login/"; const method = "POST"; /* const data = JSON.stringify({ username, password }) */ const xhr = new XMLHttpRequest(); const csrftoken = getCookie("csrftoken"); xhr.open(method, url); xhr.setRequestHeader("Content-Type", "application/json"); xhr.setRequestHeader("HTTP_X_REQUESTED_WITH", "XMLHttpRequest"); xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest"); xhr.setRequestHeader("X-CSRFToken", csrftoken); xhr.onload = () => { console.log("status", xhr.status); }; xhr.send("lacazette"); } and this following is the html file I'm trying to send a POST request. <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> {%if … -
Django ORM get average of two concatenated columns
I have 2 models class Order: ... and also I have a model Trade class Trade: x = FK(Order, related_name="x_set") y = FK(Order, related_name="y_set") price = Decimal I need to calculate for each Order an average of all x_set__price values and y_set__price values. I tried something like this, but it doesn't work Order.objects.annotate(average_price=Avg("x_set__price", "y_set__price")) -
Python / Django connection timeout for database or memcached or other connections
I`m setting up a django Server in AWS. Securitygroups are used to configure the connections between the services. When such a securitygroup is closed, there is just a never ending timeout. Example: Django should connect to a database server https://myvp.aws.com/whatever:5432, and the securitygroup denies that, then django just does nothing until the request is canceled by nginx (60s) per default. I would like to tell django/python to stop after 5 seconds, and show me a explicit connection error, so that I can debug that. Where could I set this? In Python? In Django? On my Alpine? Any ideas? -
Uploading multiple files at once - Django
I'm following the way shown below, and everything seems okay. But the problem is, I'm uploading more than photo files (by holding ctrl), but only one of them is uploading actually. Here my codes: views.py: def school_document(request): if request.method == 'POST': form = CreateSchoolDocumentForm(request.POST, request.FILES, use_required_attribute=False) if form.is_valid(): form.save() return HttpResponseRedirect('school_document') else: form = CreateSchoolDocumentForm(use_required_attribute=False) context = { 'form': form } return render(request, 'school_document.html', context) forms.py: ... class Meta: model = SchoolDocument fields = '__all__' widgets = { 'photos': ClearableFileInput(attrs={'multiple': True}), } school_document.html: <form class="form-container" method='POST' enctype="multipart/form-data" style="height: auto;"> ... </form> -
Python django non-nullable field
Here is my models.py class Product(models.Model): product_id = models.AutoField product_name = models.CharField(max_length=50) category = models.CharField(max_length = 50, default="") price = models.ImageField(default=0) sub_category = models.CharField(max_length = 50,default="") desc = models.CharField(max_length=300) pub_date = models.DateField() image = models.ImageField(upload_to="shop/images", default="") And I'm getting the line below. I don't know whether it is warning or error: You are trying to add a non-nullable field 'pub_date' to the product without a default; we can't do that (the database needs something to populate existing rows). What does it mean actually ?? -
DJANGO - How to populate/filter a Select field dynamically from an other Select field inside the same form
I'm pretty new to django and I have some trouble with a form. Currently I have a form working with 10 fields. However what i'm looking for is specific between two Select Field. I want my second Select field to be filtered with the choice of the first Select field. My models are connected to a bdd. models.py class Mission(models.Model): fk_consultant = models.ForeignKey(Consultant, on_delete = models.PROTECT) manager = models.CharField(max_length = 3, blank = True, null = True) project_name = models.CharField(max_length = 50) class Consultant(models.Model): matricule = models.CharField(max_length = 30, blank = True, unique = True) name = models.CharField(max_length = 50) first_name = models.CharField(max_length = 50) fk_teams_gestion = models.ManyToManyField(Team, related_name='gestion', blank=True) Here fk_consultant is correponding to a consultant id in Consultant (we don't see it in the model, it's auto incremented when pushing in the database) forms.py class MissionForm(forms.ModelForm): def __init__(self, cslt, *args, **kwargs): super(MissionForm, self).__init__(*args, **kwargs) self.fields['fk_consultant'].widget = forms.Select( attrs={'class': "form-control", choices=[('', '')] + [(c.id, c) for c in cslt]) self.fields['project_name'].widget = forms.Select(attrs={'class': "form-control"}, choices=[('', '')]) class Meta: model = Mission fields = ['fk_consultant', project_name'] labels = { 'fk_consultant': "Consultant*", 'project_name': "Name of the project*" widgets = { 'fk_consultant': forms.Select(attrs={'class': "form-control"}), 'project_name': forms.TextInput(attrs={'class': "form-control"}) } views.py mission_form = MissionForm(cslt, auto_id='id_start_%s') … -
How to using mysql query in django?
I want to query next id like this in django select CONCAT("EMP",LPAD(IFNULL(MAX(substr(emp_idgen,4,3)+1),"1"),3,"0")) from store_employee; -
How to update Django template after sending date t views.py
ive a problem. in my template i want to click on parts of ingredients to select them by changing their id and when I'm clicking on a button I want the page to show all reciepes where the ingredients are in. Everything works for me. I can select ingredients and send the ajax request to my views.py and select all the reciepes with those ingredients and here comes my problem. I am not able to reload the page without lopsing my context data from the ajax post request I hope i could discribe my problem here ist the part of my views.py: def what_to_cook(request): recipes = Recipe.objects.all() ingredients=Ingredients.objects.order_by().values('ingredient_name').distinct() context = {'recipes':recipes, 'ingredients':ingredients} if request.is_ajax(): tasks = request.POST.getlist('marked_ingredients[]') selected = Ingredients.objects.filter(ingredient_name__in=tasks) print(selected) context = {'recipes':recipes, 'ingredients':ingredients,'tasks':tasks, 'selected':selected} return render(request, "/cooking/what_to_cook.html", context) else: return render(request, "cooking/what_to_cook.html", context) And here is my template: {% extends 'main/base.html' %} {% load main_tags %} {% block head %} {% load static %} <link rel="stylesheet" type="text/css" href="{% static 'cooking.css' %}"> {% endblock %} {% block title %}Kochen?!{% endblock %} {% block subtitle %}Was koche ich heute?{% endblock %} {% block content %} <input type="text" id="myInput" onkeyup="search()" placeholder="Suche Zutaten ..." title="Type in a name"> <ol id="Zutaten"> {% for … -
TemplateDoesNotExist at /users/register/ bootstrap5/uni_form.html
I am building a registration form for my django project, and for styling it I am using crispy forms. But, when I run my server and go to my registration page, I see this error: Internal Server Error: /users/register/ Traceback (most recent call last): File "C:\Users\Dell\Desktop\Django\microblog\venv\lib\site-packages\django\template\backends\django.py", line 61, in render return self.template.render(context) File "C:\Users\Dell\Desktop\Django\microblog\venv\lib\site-packages\django\template\base.py", line 170, in render return self._render(context) File "C:\Users\Dell\Desktop\Django\microblog\venv\lib\site-packages\django\template\base.py", line 162, in _render return self.nodelist.render(context) File "C:\Users\Dell\Desktop\Django\microblog\venv\lib\site-packages\django\template\base.py", line 938, in render bit = node.render_annotated(context) File "C:\Users\Dell\Desktop\Django\microblog\venv\lib\site-packages\django\template\base.py", line 905, in render_annotated return self.render(context) File "C:\Users\Dell\Desktop\Django\microblog\venv\lib\site-packages\django\template\loader_tags.py", line 150, in render return compiled_parent._render(context) File "C:\Users\Dell\Desktop\Django\microblog\venv\lib\site-packages\django\template\base.py", line 162, in _render return self.nodelist.render(context) File "C:\Users\Dell\Desktop\Django\microblog\venv\lib\site-packages\django\template\base.py", line 938, in render bit = node.render_annotated(context) File "C:\Users\Dell\Desktop\Django\microblog\venv\lib\site-packages\django\template\base.py", line 905, in render_annotated return self.render(context) File "C:\Users\Dell\Desktop\Django\microblog\venv\lib\site-packages\django\template\loader_tags.py", line 62, in render result = block.nodelist.render(context) File "C:\Users\Dell\Desktop\Django\microblog\venv\lib\site-packages\django\template\base.py", line 938, in render bit = node.render_annotated(context) File "C:\Users\Dell\Desktop\Django\microblog\venv\lib\site-packages\django\template\base.py", line 905, in render_annotated return self.render(context) File "C:\Users\Dell\Desktop\Django\microblog\venv\lib\site-packages\django\template\base.py", line 988, in render output = self.filter_expression.resolve(context) File "C:\Users\Dell\Desktop\Django\microblog\venv\lib\site-packages\django\template\base.py", line 698, in resolve new_obj = func(obj, *arg_vals) File "C:\Users\Dell\Desktop\Django\microblog\venv\lib\site-packages\crispy_forms\templatetags\crispy_forms_filters.py", line 60, in as_crispy_form template = uni_form_template(template_pack) File "C:\Users\Dell\Desktop\Django\microblog\venv\lib\site-packages\crispy_forms\templatetags\crispy_forms_filters.py", line 21, in uni_form_template return get_template("%s/uni_form.html" % template_pack) File "C:\Users\Dell\Desktop\Django\microblog\venv\lib\site-packages\django\template\loader.py", line 19, in get_template raise TemplateDoesNotExist(template_name, chain=chain) django.template.exceptions.TemplateDoesNotExist: bootstrap5/uni_form.html The above exception was the direct cause … -
Django Rest Framework: maximum recursion depth exceeded while calling a Python object
I am trying to call both following and followers for the User model,i know it gets into recursing position but i don't know how to solve it. Here is the code: class UserSerializer(serializers.ModelSerializer): followers_set = serializers.SerializerMethodField() following_set = serializers.SerializerMethodField() def get_following_set(self, user): return FollowingSerializer(FollowUserModel.objects.filter(profile=user), many=True).data def get_followers_set(self, user): return FollowersSerializer(FollowUserModel.objects.filter(author=user), many=True).data class Meta: model = User fields = ('id','email','username','first_name','last_name','following_set','followers_set') class FollowingSerializer(serializers.ModelSerializer): author = UserSerializer(required=False) class Meta: model = FollowUserModel fields = ("author","profile") class FollowersSerializer(serializers.ModelSerializer): author = UserSerializer(required=False) class Meta: model = FollowUserModel fields = ("author","profile") Does anybody knows the solution? -
Issue reworking the djangocms language chooser as a location chooser
I have a djangocms website with a location chooser built on top of the language switcher (each location only has one language available). The site has 4 countries that are covered by location-specific content. An IP check redirects visitors from those countries to their country-prefixed URL. A visitor not in one of those countries lands on a the global version, with no country prefix. Example: visitor goes to example.com visitor is in US: example.com/us visitor is in CA: example.com If the site visitor wants to override their IP-assigned country choice, they select one of the other locations from a drop-down in the navigation. Example: visitor goes to example.com visitor is in US: example.com/us visitor chooses to view site as if they are in Belgium: example.com/bl The problem I have is that anyone in one of the covered locations can't choose the default, global choice. Example: visitor is in US: example.com/us visitor chooses global view: should be example.com, but they're redirected to example.com/us This is happening because the context processor I have (see below) checks if the user's request.LANGUAGE_CODE is 'en', which it is when they first come to the site (default in settings.py) and when they choose "global" (the language … -
Uploading pdf file through API in django
I'm trying to upload a pdf file through api in django view. Im receving the data in my view using file = request.FILES['file'] I want to pass this 'file'via api to the server. My api headers and post method is below. file_headers = {'Content-Type': 'application/pdf'} file_response = requests.post(Url, data=file, headers=file_headers) But Im getting a response showing 'Unsupported media type "application/pdf" in request.' Im not sure what Im doing wrong here. I would reaaly love to get some help to fix this issue. -
How do I get the number of visitors currently looking at my django website?
I need to find the number of active visitors in my website and display it. Django version is 3.0