Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Enabling HTTP/2 Support in daphne with django
When I run this command command: daphne -e ssl:443:privateKey=key.pem:certKey=crt.pem server.asgi:application --port 8000 --bind 0.0.0.0 The error I get is as follows Starting server at ssl:443:privateKey=key.pem:certKey=crt.pem, tcp:port=8000:interface=0.0.0.0 HTTP/2 support enabled Configuring endpoint ssl:443:privateKey=key.pem:certKey=crt.pem Traceback (most recent call last): ... FileNotFoundError: [Errno 2] No such file or directory: '/usr/src/app/crt.pem' Can someone tell how to fix this error? -
How to increase number of workers in Daphne with Django
With gunicorn I can increase thenumber of workers using -w 17 command: gunicorn server.asgi:application --bind 0.0.0.0:8000 -w 17 -k uvicorn.workers.UvicornWorker How can I do that with daphne to utilize the CPU available? command: daphne server.asgi:application --port 8000 --bind 0.0.0.0 -
How to show the errors in the template?
Working on a simple project using Django, and just finished the login/register form. What I'm trying to do is to show up the errors when the user doesn't do something in the right way(ex: not matching the password) I did the login/register form by using this library from django.contrib.auth import authenticate, login, logout and It did pretty well. How can I show the errors in the template? -
Django - How to check if the email already exist in the data base and if its mine or not
Am new to django and am trying to make a function where the user can change their info from their profile page but if I dont change the email I still get the validation error that the email already exist in the database. Forms.py def clean_email(self): email = self.cleaned_data['email'].lower() try: u = CustomerUser.objects.get(email=email) except CustomerUser.DoesNotExist and self.user == self.request.user: return email raise forms.ValidationError( 'Er bestaat al een account met het e-mailadres dat je hebt ingevuld. ' 'Gebruik dan alsjeblieft een ander e-mailadres.') Views.py @method_decorator(login_required(login_url='login'), name='dispatch') class Profile(SuccessMessageMixin ,UpdateView): form_class = UserInfo template_name="user/profile_page.html" success_message = f'Uw account is bijgewerkt' success_url = reverse_lazy("profile") def get_object(self): return self.request.user -
How do you fix ERROR: Command errored out with exit status 1:
I was running pip install -r requirements.txt when I got the following error. Does anyone know what I should do? Thank you. ERROR: Command errored out with exit status 1: command: /usr/bin/python3 -u -c 'import io, os, sys, setuptools, tokenize; sys.argv[0] = '"'"'/t mp/pip-install-fwxlr_gd/rcssmin_c5dddfcdb3f74060b8db70dc6865dacd/setup.py'"'"'; __file__='"'"'/tmp/pi p-install-fwxlr_gd/rcssmin_c5dddfcdb3f74060b8db70dc6865dacd/setup.py'"'"';f = getattr(tokenize, '"'"' open'"'"', open)(__file__) if os.path.exists(__file__) else io.StringIO('"'"'from setuptools import s etup; setup()'"'"');code = f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code , __file__, '"'"'exec'"'"'))' install --record /tmp/pip-record-as1v9v4s/install-record.txt --single-v ersion-externally-managed --user --prefix= --compile --install-headers /web/.local/include/python3.6m /rcssmin cwd: /tmp/pip-install-fwxlr_gd/rcssmin_c5dddfcdb3f74060b8db70dc6865dacd/ Complete output (16 lines): running install running build running build_py creating build creating build/lib.linux-x86_64-3.6 copying ./rcssmin.py -> build/lib.linux-x86_64-3.6 running build_ext building '_rcssmin' extension creating build/temp.linux-x86_64-3.6 gcc -pthread -Wno-unused-result -Wsign-compare -DNDEBUG -O2 -g -pipe -Wall -Wp,-D_FORTIFY_SOURCE= 2 -fexceptions -fstack-protector-strong --param=ssp-buffer-size=4 -grecord-gcc-switches -m64 -mtune=g eneric -D_GNU_SOURCE -fPIC -fwrapv -fPIC -DEXT_MODULE=_rcssmin -UEXT_PACKAGE -I_setup/include -I/usr/ include/python3.6m -c rcssmin.c -o build/temp.linux-x86_64-3.6/rcssmin.o In file included from rcssmin.c:18:0: _setup/include/cext.h:34:20: fatal error: Python.h: 그런 파일이나 디렉터리가 없습니다 #include "Python.h" ^ compilation terminated. error: command 'gcc' failed with exit status 1 ---------------------------------------- ERROR: Command errored out with exit status 1: /usr/bin/python3 -u -c 'import io, os, sys, setuptools , tokenize; sys.argv[0] = '"'"'/tmp/pip-install-fwxlr_gd/rcssmin_c5dddfcdb3f74060b8db70dc6865dacd/set up.py'"'"'; __file__='"'"'/tmp/pip-install-fwxlr_gd/rcssmin_c5dddfcdb3f74060b8db70dc6865dacd/setup.py '"'"';f = getattr(tokenize, '"'"'open'"'"', open)(__file__) if os.path.exists(__file__) else io.Strin gIO('"'"'from setuptools import setup; setup()'"'"');code = … -
Legends not visible in django piechart
I created a donut pie chart using django. But it is not showing all the legends. Most of them are invisible.Pie chart Here is my django code. Plz suggest me the changes so that all legends are properly visible. def __get_fiat_piechart(balances, fiat): EPS = 0.009 return { 'charttype': "pieChart", 'chartdata': { 'x': [x['currency'] for x in balances if x['amount_fiat'] > EPS], 'y1': [x['amount_fiat'] for x in balances if x['amount_fiat'] > EPS], 'color':'blue', 'extra1': { "tooltip": { "y_start": "", "y_end": fiat, } } }, 'chartcontainer': "fiat_container", 'extra': { 'x_is_date': False, 'x_axis_format': '', 'tag_script_js': True, 'jquery_on_ready': False, 'donut':True, 'donutRatio':0.5, 'chart_attr':{ 'labelThreshold':0.0001, 'labelType':'\"percent\"',} } } -
Passing default values into an unbound django form
I have two select classes that I am trying to create in an unbound form. The data selections are only relevant to the presentation that is created in the view, so are throwaways and do not need to be saved in a model. The challenge I have is that I can pass in the field listings ok, but how do I set "default" checked / selected values so that the form becomes 'bound'? views.py def cards(request): sort_name = [] sort_name.append("Alphabetic Order") sort_name.append("Most Popular") sort_name.append("Least Popular") sort_name.append("Highest Win Rate") sort_name.append("Lowest Win Rate") sort_id = range(len(sort_name)) sort_list = list(zip(sort_id, sort_name)) <more code to make filt_list and zip it> if request.method == 'POST': form = cardStatsForm(request.POST, sortList=sort_list, filtList=filt_list) if form.is_valid(): do something else: do something else else: form = cardStatsForm(filter_list, sort_list) forms.py class cardStatsForm(forms.Form): def __init__(self, filterList, sortList, *args, **kwargs): super(cardStatsForm, self).__init__(*args, **kwargs) self.fields['filts'].choices = filterList self.fields['filts'].label = "Select player rankings for inclusion in statistics:" self.fields['sorts'].choices = sortList self.fields['sorts'].label = "Choose a sort order:" filts = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple, choices=(), required=True) sorts = forms.ChoiceField(choices=(), required=True) The difficulty I am having is the the form fails the "is_valid" test since it is not bound, and I have the "required=true" setting (so that the user must select … -
Django +docker-compose + Celery + redis - How to use Redis deployed in my own remote server?
I have a Django app deployed in Docker containers. I have 3 config environnements: dev, preprod and prod. dev is my local environnement (localhost) and preprod/prod are remote linux environnements. It works when using the "public" Redis server and standard config. But I need to use our own Redis deployed in Docker container in a remote server (192.168.xx.xx) with name container redis_cont. And I do not really know how to config. I do not know if it is possible? I would appreciate some help. docker-compose version: '3.7' services: web: restart: always build: context: ./app dockerfile: Dockerfile.dev restart: always command: python manage.py runserver 0.0.0.0:8000 volumes: - ./app:/usr/src/app ports: - 8000:8000 env_file: - ./.env.dev entrypoint: [ "/usr/src/app/entrypoint.dev.sh" ] depends_on: - redis healthcheck: test: ["CMD", "curl", "-f", "http://localhost:8000/"] interval: 30s timeout: 10s retries: 50 redis: container_name: redis_cont <= container running in remote linux server image: "redis:alpine" celery: build: context: ./app dockerfile: Dockerfile.dev command: celery -A core worker -l info volumes: - ./app:/usr/src/app env_file: - ./.env.dev depends_on: - web - redis celery-beat: build: context: ./app dockerfile: Dockerfile.dev command: celery -A core beat -l info volumes: - ./app:/usr/src/app env_file: - ./.env.dev depends_on: - web - redis settings.py CELERY_BROKER_URL = 'redis://redis:6379' CELERY_RESULT_BACKEND = 'redis://redis:6379' CELERY_ACCEPT_CONTENT = … -
cannot import name 'url' from 'django.conf.urls'
I have been trying to makemigrations in my django project but I keep getting this error constanly even though I'm using path instead of url can someone please help me? The error is being caused by the froala_editor path but I don't understand why. -
Django ModelForm Foreign Key Dropdown
I'm having a problem and I couldn't find the error. My dropdown with foreign key is showing "Client object(1)", but my models, views and forms is similar for all views that have the same situation. Model: class Cliente(models.Model): nome = CharField(max_length=50) cnpj = IntegerField() dateCriacao = DateTimeField(auto_now_add=True) def __self__(self): return self.nome Model for product: class ProdutoCliente(models.Model): def filePath(produto, file): return os.path.join('produtos', produto, file) numeroSerie = CharField(max_length=30, null=True) produto = CharField(max_length=30) file = FileField(upload_to=filePath) cliente = ForeignKey(Cliente, on_delete=CASCADE) dateCriacao = DateTimeField(auto_now_add=True) def __self__(self): return self.id Views: def NewCustomerProducts(request): createCustomerProducts = CustomerProductsForm() if request.method == 'POST': createCustomerProducts = CustomerProductsForm(request.POST or None) if createCustomerProducts.is_valid(): createCustomerProducts.save() return redirect('products:Customer_Products') else: createCustomerProducts = CustomerProductsForm() context = {'createCustomerProducts' : createCustomerProducts} return render(request, 'produtos/NewCustomerProducts.html', context) forms: class CustomerProductsForm(ModelForm): numeroSerie = fields.CharField (blank=True) class Meta: model = ProdutoCliente fields = [ 'numeroSerie', 'produto', 'cliente', 'file' ] labels = { 'numeroSerie': ('Número de Série'), 'produto': ('Produto'), 'cliente': ('Cliente'), 'file': ('Arquivo') } result: https://imgur.com/Cft5AOW -
Django: When a user updates a Profile Model information, the default User username adds ('username',)
I have a Profile model that updates the default django model User by using signals. The model is as follows: class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, null=True, blank=True) name = models.CharField(max_length=200, blank=True, null=True) email = models.EmailField(max_length=500, blank=True, null=True) username = models.CharField(max_length=200, blank=True, null=True) created = models.DateTimeField(auto_now_add=True) id = models.UUIDField(default=uuid.uuid4, unique=True, primary_key=True, editable=False) def __str__(self): return str(self.username) The signal to send the information updated by the user to the default Django User is as follows: def updateUser(sender, instance,created, **kwargs): profile = instance user = profile.user if created == False: user.name = profile.name, user.email = profile.email, user.username = profile.username, user.save() post_save.connect(updateUser, sender=Profile) The updated User username changes to the following format: ('username',). Do you have any idea of why that is happening? I have failed in identifying the error. Than you in advance. -
How to send information between two html using json and POST?
In 'cart.html' I have a form of id="order-selection-cart" which is for selecting user's order, which the user wants to make payment for. <select id="order-selection-cart" onchange="order_cart()" class="form-control"> {% for order in orders_for_user %} <option>{{order.id_zamowienie}}</option> {% endfor %} </select> In the same html page, I also display the selected order value ({{order.id_zamowienie}} in a form of id="order-selection-cart": <div class="row cart-box" style="background-color:rgb(226, 226, 226);"> <h10>Szczegóły zamówienia </h10> <h4 type="value" id="order-details"></h4> </div> Now, I want to go to 'checkout.html' by clicking a button of name 'Zamawiam' and I have done it like this: <div class="row cart-box" style="background-color:rgb(226, 226, 226);"> <h4>Suma zamówienia</h4> <h10>Suma: {{cart_total|floatformat:2}} zł</h10> <br> <a class="btn btn-primary" href="{% url 'checkout' %}" role="button">Zamawiam</a> </div> This code works, but I have a problem with remembering selected user's order which he wants to make payment for. Let's say I selected option 2, I want to remember it and when clicked 'Zamawiam' I want to go to 'checkout.html' where this value (2) can be accessed and not changed when it is again changed (if user changes it in cart.html in other window for example). At first I have had js code which was changing value of selected option in 'cart.html': // ordernumber update in cart.html function order_cart() … -
How to modify the error form of the authentication in Django?
Working on a simple project using Django 4 and just finished the login register form, and now I'm working to show the errors if a credential is entered wrong. What I'm trying to do is to modify the error text that is shown. I show the errors on template: {{form.errors}} , and this is the result: How can I remove the password2 word from the form in the template? -
DRF. Trying to create a record that requires an instance of another DB object, and keep getting "int() argument must be a string..."
I'm new to Django and DRF and I'm really struggling with something. I'm attempting to create a record in a table that has a foreign key. We'll say the models looks like this: class Foo(models.Model): foo_id = models.IntegerField( primary_key=True, ) name = models.CharField( max_length=256, ) class Bar(models.Model): bar_id = models.CharField( primary_key=True, max_length=256 ) name = models.CharField( max_length=256, ) foo = models.ForeignKey( Foo, models.SET_NULL, related_name='rel', ) When I try this: Bar.objects.create( bar_id = "A1", name = "John", foo = 5 ) I get the error that I would expect: Cannot assign "5": "Bar.foo" must be a "Foo" instance. But if I try: Bar.objects.create( bar_id = "A1", name = "John", foo = Foo.objects.get(foo_id=7) ) I get: int() argument must be a string, a bytes-like object or a number, not 'Foo' Really don't understand as I'm sure I've created records like this elsewhere. -
How to list objects of the same date?
I want to list all items in my template, but I want to list items under the same year. For example, under the 2021 title, model objects for that year should be listed. Year titles should come dynamically. How can I do it? views.py def press_list(request): press_contents = PressContent.objects.all().order_by('-date') context = { 'press_contents': press_contents } return render(request, "press_list.html", context) models.py class PressContent(models.Model): label = models.CharField(max_length=500) url = models.URLField(max_length=500) date = models.DateTimeField(blank=True, null=True) press_list.html {% for press in press_contents %} <div class="card" style="width: 18rem; margin:15px"> <div class="card-header"> {{ press.date.year }} </div> <ul class="list-group list-group-flush"> <li class="list-group-item"><a href="{{ press.url }}">{{ press.label }}</a></li> # Other objects from this year should come here. </ul> </div> {% endfor %} To be clear: 2021 obj 1 obj 2 2020 obj 3 obj 4 ... ... -
Nginx 403 while accessing static files in docker volumes
I am trying to serve static files in docker volumes for my Django project. Nginx is able to access the files(403) error. I tried to solve this in different ways like updating the file permission. Nginx I am installed in a normal way without a container and Django, Postgres database is running in a container Nginx configuration server { listen 80; server_name 139.59.73.115; location / { include proxy_params; proxy_pass http://127.0.0.1:8000; } location /static { root /var/lib/docker/volumes/m3-mobiles_m3-mobiles-assets/_data/; } } -
how to send django website user input data to external python script
I am trying to create a webpage where users input two data and then I receive that data and pass that to an external python script I cannot enter the python script the Django since its very big <form action='generate' method='post' > {% csrf_token %} enter the current status:<input type="text" name="status"></br> enter the water_level:<input type="text" name="level"></br> <input type="submit" value="submit"> </form> ''' I am receiving the value entered by the user into views. generate function as follows ''' def generate(request): a=int(request.POST["status"]) b=int(request.POST["level"]) out=run(sys.executable,['C:\Users\siddhant\Desktop\internship\indicator\work\templates\water.py',"a","b"],shell=False,stdout=PIPE) print(out) I want to run the water.py file here only bypassing the input a and b from os import read from random import randint import sys from tkinter.constants import X from datetime import* import pandas as pd import numpy as np from pandas.core.base import DataError from time import time start_time = datetime.now() # do your work here x=sys.argv[1] current_level=sys.argv[2] I want to pass the received input a and b to x and current_level respectively -
How to use ListSerializer for create and update multiple records in django rest framework?
Here is the way to create and update multiple records at once in django rest framework using ListSerializer. This way is very sort and and give fast response. When you want to create a objects then pass id: null because id is required field and when you want to update the records then pass specific id. Here is the answer: models.py class BookDetail(models.Model): author = models.ForeignKey('bookapp.Author', null=True, on_delete=models.CASCADE) title = models.CharField(max_length=255, null=True, blank=True) price = models.CharField(max_length=100, null=True, blank=True) discount = models.FloatField(default=0) tax_percentage = models.IntegerField(default=0) total_price = models.FloatField(default=0) created_at = models.DateTimeField(auto_now_add=True, editable=False) modified_at = models.DateTimeField(auto_now=True) serializer.py class BookDetailsListSerializer(serializers.ListSerializer): def update(self, instance, validated_data): # Perform creations and updates. ret = [] for data in validated_data: if "id" in data and data['id'] not in ['', None]: BookDetail.objects.filter(id=data['id']).update(**data) ret.append(data) else: ret.append(BookDetail.objects.create(**data)) return ret class BookDetailsSerializer(serializers.ModelSerializer): class Meta: model = BookDetail fields = ['id', 'author', 'title', 'price', 'discount', 'tax_percentage', 'total_price'] list_serializer_class = BookDetailsListSerializer extra_kwargs = { # We need to identify elements in the list using their primary key, # so use a writable field here, rather than the default which would be read-only. 'id':{ 'read_only': False, 'allow_null': True, }, 'author':{ 'required': True, }, 'title':{ 'required': True, }, 'price':{ 'required': True, }, 'discount':{ 'required': True, … -
How to use seaborn in django for graph
Anyone has any idea how to show grpah on browser of seaborn in django, if have any one has idea explain this -
Passing numeric data containing < or > django to javascript
am having a problem with char inside numeric data, it's too large to be cleaned. anyways. I want to replace < and > from value. just posting relevant codes. views.py def search_result(request): if request.method == "POST": ChemSearched = request.POST.get('ChemSearched') tarname = BINDLL.objects.filter(targetnameassignedbycuratorordatasource__contains=ChemSearched).exclude(ki_nm__isnull=True)[:120] return render(request, 'Search/search_result.html',{'ChemSearched':ChemSearched,'tarname':tarname}) Html side <script> data=[{% for Bindll in tarname %} { group: '{{ Bindll.targetnameassignedbycuratorordatasource }}', variable:'{{ Bindll.zincidofligand}}', value: {{Bindll.ki_nm|safe}} }, {% endfor %}]; which is used by graph d3.js. all go well unless I have '<' or '>' in value I'll have this result Uncaught SyntaxError: Unexpected token '>' or if use escape value: {{Bindll.ki_nm|escape}} Uncaught SyntaxError: Unexpected token '&lt' any function to be used in Html side javascript to replace char or anything and keep only numeric like regex replace. thanks. -
How do I bypass login or Login while testing secure API's in django
How do I bypass login while testing secure API's in django? Currenlty I am trying to login but getting the following error: -
How to resolve "required positional argument: 'on_delete' " while upgrading django and python version?
I recently got a task to upgrade my whole Django project to newer version. Currently we are using python version = 2.7 and django version = 1.11.3 When I am upgrading the django version to 2.2.16 and python version to 3.7.12 Now I am getting error - TypeError: init() missing 1 required positional argument: 'on_delete' I want two suggestions first how can I add on_delete to all the models of all the apps in my whole project and secondly to which python and django version I should migrate my project to ? It would be so helpful to me....Thank You in Advance. -
Displaying images from database in Django
I am new to Django, and I am doing a simple web application that saves and displays products. But my problem is when I tried to display the product information I could display everything except the product image. You can see my code below. settings.py in the static section: MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' The main urls.py: from django.contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), path('', include('pages.urls')), path('products/',include('products.urls')), ] + static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT) The models.py of the Products application: from django.db import models from django.db.models.deletion import CASCADE from django.db.models.fields import CharField, DateField, DateTimeField from datetime import datetime from django.db.models.fields.related import ForeignKey, ManyToManyField # Create your models here. class Product(models.Model): categories = [ ('Phone', 'Phone'), ('Computer', 'Computer'), ] name = models.CharField(max_length = 50, default='Nothing', verbose_name='title') content = models.TextField(default='Empty', null = True, blank = True, verbose_name='description') price = models.DecimalField(max_digits = 5, decimal_places = 2, default=0.0) image = models.ImageField(upload_to = 'photos/%y/%m/%d', default='media/photos/default/default_product.png', verbose_name='picture') active = models.BooleanField(default = True) category = models.CharField(max_length=50, null=True, choices=categories) def __str__(self): return self.name class Meta: #verbose_name = 'name' ordering = ['-name'] And finally in the products.html: {% block content %} {% comment … -
django.utils.datastructures.MultiValueDictKeyError: 'title' django
views.py class ProductsCreate(CreateView): model = Products template_name = "productscreate.html" serializer = Productserialize success_url=reverse_lazy('productslist') def productsAdd(request): if request.method == "POST": product=Products() product.title = request.POST['title'] product.description = request.POST['description'] product.image = request.FILES.get('image') product.save() return render(request,'productslist.html') else: return render(request,'productscreate.html') form.html <form data-bind="submit: save" enctype="multipart/form-data" > {% csrf_token %} <table border="1"> <tr> <td>Title: <input type="text" name="title" id="title" data-bind="text: $data.title"></td> <br> </tr> <tr> <td>Description: <textarea name="description" id="description" data-bind="text: $data.description">Description</textarea></td> <br> </tr> <tr> <td>Image: <input type="file" name="image" id="image" ></td> <br> </tr> <tr> <td><button type="button" id="submit" data-bind="click: save">Submit</button></td> </tr> </table> </form> <script> var ViewModel = function () { var self = this; self.title = ko.observable(""); self.description = ko.observable(""); self.save = function () { var formdata = new FormData(); formdata.append('image', $('#image')[0].files[0]); // formdata.append('title', ko.observable("")); // formdata.append('description', ko.observable("")); formdata = { title: self.title, description: self.description, }; console.log(formdata) $.ajax({ type: 'POST', url: "{% url 'productsadd' %}", data: formdata, headers: {'X-CSRFToken': csrftoken}, processData: false, contentType: false, success: function (data){ alert('The post has been created!') window.location = '{% url "productslist" %}'; }, error: function () { alert("fail"); } }); }; }; ko.applyBindings(new ViewModel()) </script> When i create a new form it shows multidict key error in title I don't know where is the issue in title I have given same html name in … -
Django Admin Panel Form Displaying in Background
This is the first time I am seeing this problem in the Django admin panel. The admin panel forms are being displayed in the background, as attached in the screenshot, making it impossible to add/update anything. Admin panel The form is however visible when zooming out the browser content to 25%, but makes it very difficult to see any content. Zoomed out