Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 -
Djnago Rest frame work custom authentication
I am new to DRF . I have a django application and my project need to create a rest api for the applications. Inside the application I have a model to create api users and password. The model is as follows, class APIManger(models.Model): id = models.BigAutoField(primary_key=True) user = models.CharField(max_length=50, unique=True, verbose_name='API Name') apiuid = models.CharField(max_length=128, default=None, blank=True, null=True, verbose_name='API ID') password = models.CharField(max_length=128, default=None, blank=True, null=True, verbose_name='API Password') REQUIRED_FIELDS = ['user'] class Meta: managed = True db_table = 'adminapi' verbose_name_plural = "Admin API" def get_name(self): return self.user def __str__(self): return self.user def __unicode__(self): return self.user Now I setup the rest frame work as follows, authentication.py from rest_framework import authentication from rest_framework import exceptions from myapp.models.adminapi import APIManger class APIUser(authentication.BaseAuthentication): def authenticate(self, request): username = request.data.get('username', None) password = request.data.get('password', None) if not username or not password: return None try: user=APIManger.objects.get(apiuid=username) except Exception: raise exceptions.AuthenticationFailed('No such user') return (user, None) The views.py is as follows, from .authentication import APIUser class LoginView(APIView): authentication_classes = (APIUser,) def post(self, request, format=None): content = { 'username': str(request.user), 'auth': str(request.auth), # None } return Response(content) Settings.py is as follows, REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework.authentication.TokenAuthentication', 'rest_framework.authentication.SessionAuthentication', 'api.authentication.APIUser', ), 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', ), } Now my AIM … -
Edit item within views in Django
There is some problem, I'm trying to update the product on the client by making changes and clicking on the update button - my page is refreshing w/o updating info, so the product has the same data as before. But in the logs, the status code of the GET request is 200 and shows the updated object in the database. When I try to update through the admin Django dashboard, everything works successfully, the problem is only on the client side of the web application. What issues can there be? Thank you in advance! @login_required(login_url='user-login') @allowed_users(allowed_roles=['Admin']) def product_edit(request, pk): item = Product.objects.get(id=pk) if request.method == 'POST': form = ProductForm(request.POST, instance=item) if form.is_valid(): form.save() return redirect('dashboard-products') else: form = ProductForm(instance=item) context = { 'form': form, } return render(request, 'dashboard/products_edit.html', context) -
Django FormMixin with DetailView
below is my BlogDetailView with FormMixin for separate comment form. Everything is working fine except for the form validation. At the moment Iam able to have CommentForm with initial data where I need the hidden values or have request.POST data sent in, but the hidden value will be missing. What I want is for the form to use the initial data on create and use request.POST data when its an error or update. class BlogDetailView(FormMixin, DetailView): model = Post form_class = CommentForm def get_success_url(self): return self.object.get_absolute_url() def get_context_data(self, **kwargs): context = super(BlogDetailView, self).get_context_data(**kwargs) context['form'] = CommentForm(self.request.POST, initial={ 'post_id' : self.object.id, 'user_id' : self.request.user.id }) context['comments'] = self.object.comment_set.all() return context def post(self, request, *args, **kwargs): self.object = self.get_object() form = self.get_form() if form.is_valid(): return self.form_valid(form) else: return self.form_invalid(form) def form_valid(self, form): print(form.data) form.save() return super(BlogDetailView, self).form_valid(form) -
How to host django with grpc in Production with ssl?
I am using Django with grpc , for this I am using django-rpc-framework. For development , I have used python manage.py grpcrunserver --dev. Now, I have to go for production. Can I use python manage.py grpcrunserver 127.0.0.1:8000 --max-workers 5 for production if yes, then how?, because I don't know how to run it in detached mode. I was thinking to use hypercorn because hypercorn handles http2 , But it also requires ssl certificate, which is good, but when I am connecting client to the server( I am using self signed certificate ,Just to test), I am receiving following error. To generate certificate, I ran following command. openssl req -x509 -newkey rsa:4096 -days 3650 -nodes -keyout ca-key.pem -out ca-cert.pem openssl req -newkey rsa:4096 -nodes -keyout server-key.pem -out server-req.pem openssl x509 -req -in server-req.pem -days 3650 -CA ca-cert.pem -CAkey ca-key.pem -CAcreateserial -out server-cert.pem To run server , I tried following command. hypercorn --keyfile server-key.pem --certfile server-cert.pem kumpali.asgi:application With kreya, I am using ca-cert.pem file as certificate. -
django admin specific redirects
I have a Django website where all urls are pointed to admin like this : urls.py (Root) from django.contrib import admin from django.urls import path urlpatterns = [ path('', admin.site.urls), ] I would like to know how to make specific redirects from one url to another, as I only have one model to manage : localhost/ => localhost/app/computer localhost/app/ => localhost/app/computer I tried adding this to urls.py but it does not work : from django.http import HttpResponseRedirect path('/', lambda request: HttpResponseRedirect('/app/computer/')) I also thought of adding urls.py to app, but I think there might be a conflict as path('') will be on both urls.py, the root and the app -
Web Programming with Python Django and C++
I wonder that Django and C++ are a good couple to code web programming. What do you suggest to develop it? I want to write back-end processes in C++, and other stuffs in Django. -
How to print values horizontally from the list followed by comma after each integer value in Django
I want to print values horizontally from list followed by comma after each integer value alist = [1, 2, 3 4,5] print(alist) result should be like this: 1, 2, 3, 4, 5