Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
i run command django-admin startproject dr it shows zsh: command not found: django-admin?
i run command django-admin startproject dr it show zsh: command not found: django-admin How to solve this problem ? -
Django how to properly test User instance
A few days ago I found a really nice webpage with Patterns and Anti-Patterns in Django. One of the anti-patterns is connected with linking custom user model to other models. Basic on Django documentation and this webpage I would like to know: What are the limitations between calling get_user_model() and settings.AUTH_USER_MODEL? What kind of differences are between those two approaches? How to prepare mock user in tests? Should I create user instance from AUTH_USER_MODEL or get_user_model? from django.contrib.auth import get_user_model User = get_user_model() # or settings.AUTH_USER_MODEL self.custom_user = User.objects.create( username='test', password='password', first_name='test name', email='test@test.test', ) -
request.FILES.get is empty in a Django project
For a project I would like to use two files loaded by the user via two inputs, to apply an external script. My problem is that I get an error because Django doesn’t seem to be able to locate these inputs. So I have an empty object instead of the file. Here are my codes: home.html <!DOCTYPE html> <html lang="fr"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Home</title> </head> <body> <h1>Home</h1> <form action="/external/" method="post" enctype="multipart/form-data"> {% csrf_token %} Input xlsx file :<br><br> <input type="file" name="file1" accept=".xml" required><br> <input type="file" name="file2" accept=".xml" required><br> <input type="submit" value="Valider"><br> </form> </body> </html> views.py from django.shortcuts import render from .scripts.extScript import * def home(request): return render(request, 'home.html') def external(request): f1=request.FILES.get('file1') f2=request.FILES.get('file2') extScript(f1,f2) return render(request,'home.html') urls.py from django.contrib import admin from django.urls import include, path from .views import * urlpatterns=[ path('',home,name="home"), path('external/',external, name="external") ] architecture: DjangoProject | -views.py -urls.py -scripts | -extScript.py templates | -home.html and the error specifies that f1 type is < NoneType > I want to point out that I tried to put f1=request.FILES[‘file1’] and it sends me that ‘file1’ is not found : raise MultiValueDictKeyError(key). If anyone has an idea, I can’t solve this problem, I feel that everything is fine. Besides, … -
Celery Flower didn't responding anything on the command line
I'm trying to up flower on my local machine but flower not responding. I'm using docker. First I up to the Celery worker in to the container like celery -A tasks worker -l info after that I run to the beat different shell. celery -A tasks beat -l info Worker and beat successfully works so I can see received tasks on worker stage. And when I try to run flower, flower did not responding. I tried to following commands and everyone stucks. I cant see any result like "visit me:" on command line and also localhost:5555 not responding. celery flower -A tasks --loglevel=info --broker=redis://redis-dev:6379/0 celery flower -A tasks celery -A tasks flower --address=127.0.0.1 --port=5555 celery -A tasks flower --address=127.0.0.6 --port=5556 My docker-compose file looks like version: "3.8" services: app: build: context: . dockerfile: ./app/Dockerfile command: python -u manage.py runserver 0.0.0.0:8000 volumes: - ./app:/app ports: - "8000:8000" depends_on: - redis-dev environment: APP_REDIS_HOST: redis-dev APP_REDIS_PORT: 6379 APP_REDIS_DB: 0 redis-dev: image: redis:latest ports: - "6379:6379" volumes: - redisdata:/data versions: celery==3.1.19 flower==0.9.2 tornado==4.2 I did suspect to broker was not working but worker and beat works success so I think broker part works. Thanks in advance for any suggestion. -
Django on Nginx and Gunicorn, permission denied 502 bad gateway
I've been following all tutorials and digging into all similar questions but none resolve my problem. I've a django app running on a vps. The django app is located at /home/larapida/webapp directory structure: drwxr-x--- 11 larapida larapida 4096 Dec 21 09:21 . drwxr-xr-x 4 root root 4096 Dec 20 21:17 .. drwxrwxr-x 4 larapida larapida 4096 Dec 20 21:25 .venv srwxrwxrwx 1 larapida www-data 0 Dec 21 08:59 larapida.sock drwxrwxr-x 3 larapida larapida 4096 Dec 21 09:21 logs -rw-r--r-- 1 larapida larapida 27492 Dec 20 19:56 poetry.lock drwxrwxr-x 3 larapida larapida 4096 Dec 20 21:51 public -rw-r--r-- 1 larapida larapida 704 Dec 20 19:56 pyproject.toml drwxr-xr-x 5 larapida www-data 4096 Dec 20 21:48 webapp My django settings: ALLOWED_HOSTS = [ "larapidamolinetto.com", "145.239.197.231", ".localhost", "127.0.0.1", "[::1]", ] my gunicorn service is called larapida.service [Unit] Description=larapida daemon After=network.target [Service] User=larapida Group=www-group WorkingDirectory=/home/larapida/webapp ExecStart=/home/larapida/.venv/bin/gunicorn --access-logfile - --workers 3 --bind unix:/home/larapida/larapida.sock webapp.wsgi:application [Install] WantedBy=multi-user.target and my nginx configuration is: upstream larapida { server unix:/home/larapida/larapida.sock; } server { listen 80 default_server; server_name 145.239.197.231; access_log /home/larapida/logs/nginx/access.log; error_log /home/larapida/logs/nginx/error.log; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/larapida/public/static; } location / { try_files $uri @proxy_to_app; } location @proxy_to_app { include proxy_params; proxy_pass … -
Getting data from sqlite database by calling it from Django by using HTML forms
I have a HTML form : <form action = "" method = "get"> <label for="movie_title">Filmo pavadinimas: </label> <input id="movie_title" type="text" name="movie_title"> <input type="submit" value="OK"> </form> I want to enter the movie title and get all of the actors that casted in that movie, but I don't know how to get to that result even after reading the documentation. DB data: Model for that table: class Filmlist(models.Model): film_id = models.AutoField(primary_key=True) title = models.CharField(max_length=250) description = models.TextField(blank=True, null=True) # This field type is a guess. category = models.CharField(max_length=250) price = models.DecimalField(max_digits=10, decimal_places=5) # max_digits and decimal_places have been guessed, as this database handles decimal fields as float length = models.SmallIntegerField(blank=True, null=True) rating = models.CharField(blank=True, null=True, max_length=250) name = models.CharField(max_length=250) class Meta: managed = False db_table = 'film_list' So to conclude, I have to enter movie title and get all of those actors show under actors row. Is it possible to do that with Django and HTML? -
Is there a way to redirect my the user from my django website to an external website using urlField?
so here is my model.py from django.db import models # Create your models here. class TestSeries(models.Model): name=models.CharField(max_length=120) url_field=models.URLField(max_length=200) def __str__(self): return self.name def save(self, *args, **kwargs): super().save(*args, **kwargs) class Meta: verbose_name_plural="TestSeries" and here is my views.py from django.shortcuts import render from .models import TestSeries from django.views.generic import ListView class TestListView(ListView): context_object_name='test' model=TestSeries template_name='testseries/test_list_view.html' def test_view(request,pk): test=TestSeries.objects.get(pk=pk) return redirect(test.image_url) and my html template {% extends 'home.html' %} {% block content %} {% for obj in object_list %} {{obj.name}}:-<a href="{'url_field'}">{{obj.url_field}}</a> {% endfor %} {% endblock %} Note:- I am able to display the name and the url_field of the object in my html file but as soon as I click on the link it shows an error404, page not found. -
how to post multiple images together in django?
I want to create a post request with multiple images in django. I tried creating a different model for images and connected it to my 'vehicle' model using OnetoOneField, but it only allows to post 1 image at a time.(this method is shown below) I also tried to get multiple images as a comma-separated string but when I post my images as a list of binary images it shows 'invalid type' error. I just need to create an API for posting multiple images in one go. Here is my model.py file - class VehicleImage(models.Model): image_id = models.AutoField(primary_key=True) image = models.ImageField(upload_to="media") def __str__(self): return self.vehicle.auction_title class Vehicle(models.Model): auction_title = models.TextField() vehicle_images = models.ManyToManyField(VehicleImage, blank=True) vehicle_images_list = models.TextField() def __str__(self): return self.auction_title Serializer.py files - class VehicleImageSerializer(serializers.ModelSerializer): class Meta: model = VehicleImage fields = "__all__" class VehicleSerializer(serializers.ModelSerializer): vehicle_images = VehicleImageSerializer(many=True, read_only=True) class Meta: model = Vehicle fields = "__all__" def create(self, validated_data): images_data = validated_data['vehicle_images_list'] vehicle = Vehicle.objects.create(**validated_data) if images_data!="": for data in images_data.split(','): image = VehicleImage.objects.get(image_id=data) vehicle.vehicle_images.add(image) return vehicle Views.py file class add_vehicle(ListCreateAPIView): queryset = Vehicle.objects.all().order_by('-vehicle_id') serializer_class = VehicleSerializer pagination_class = CustomPagination def post(self, request, format=None): # creating the Vehicle vehicle_serializer = VehicleSerializer(data=request.data) if vehicle_serializer.is_valid(): vehicle_serializer.save() return Response({ "response":{"vehicle_id":vehicle_serializer.data['vehicle_id']}, "status_code":200}, status … -
How to async sending API request process in Django?
I'm doing a project in which, on loading(render) a page through views, an API request is sent. I want to async the API request process, i.e in intervals of 10sec, API requests should be sent. -
Import model without id field as primary key with django import_export
just tried out django-import-export to import som things from a csv-file. Followed the doc but I always get an error when trying to import the following Model: class Token(models.Model): key = models.CharField(db_index=True,unique=True,primary_key=True, ) pool = models.ForeignKey(Pool, on_delete=models.CASCADE) state = models.PositiveSmallIntegerField(default=State.VALID, choices=State.choices) then the resource class: class TokenResource(resources.ModelResource): class Meta: model = Token skip_unchanged = True report_skipped = True fields = "key" Now when importing a csv-file i get the following errors: Error row number: 1 - 'id' Traceback (most recent call last): File "/backend/.venv/lib/python3.9/site-packages/import_export/resources.py", line 667, in import_row instance, new = self.get_or_init_instance(instance_loader, row) File "/backend/.venv/lib/python3.9/site-packages/import_export/resources.py", line 359, in get_or_init_instance instance = self.get_instance(instance_loader, row) File "/backend/.venv/lib/python3.9/site-packages/import_export/resources.py", line 346, in get_instance import_id_fields = [ File "/backend/.venv/lib/python3.9/site-packages/import_export/resources.py", line 347, in <listcomp> self.fields[f] for f in self.get_import_id_fields() KeyError: 'id' There is no field id within my model the primary key field is key so why it is not taken? Or could it be that a model must have an id field to get imported? I know that this ids are taken for comparision and so on but there is a primary key field within the model, so I do not understand why this is not taken. How could I change this without having to … -
Django Models - Column save based on primary key when post
This is my model.py class AppointmentMaster(models.Model): id = models.AutoField(primary_key=True) user_key = models.CharField(max_length=30,blank=True,unique=True) phone_number = models.CharField(max_length=20, blank=True, null=True) email = models.CharField(max_length=20, blank=True, null=True) and i'm using viewsets.ModelViewSet for post details.I want to save user_key automatically when create a new row from post api. I want output like { "id":1, "user_key":"USER-1", "phone_number":"90000000", "email":"abc@gmail.com" } -
DJango - Two Different Views from Different Apps into a single Template
Django beginner here. I am trying to make a an app for where users can make connections, post stuff, chat, etc. There are two user types - Parents and Child. For this I extended the AbstractBaseUser model and created two another models - Parent and Child with a OneToOne link to the User. #accounts/models.py class User(AbstractBaseUser, PermissionsMixin): REQUIRED_FIELDS = [] EMAIL_FIELD = "email" USERNAME_FIELD = 'email' objects = UserManager() email = models.EmailField(unique=True) first_name = models.CharField(max_length=DefaultModel.MAX_LENGTH, unique=False) last_name = models.CharField(max_length=DefaultModel.MAX_LENGTH, unique=False) profile_photo = models.ImageField(default='uploads/profile/default_profile.jpg', upload_to=content_image_name) cover_photo = models.ImageField(default='uploads/profile/default_cover.jpg', upload_to=content_image_name) username = AutoSlugField(populate_from='first_name', unique=True, sep='.') bio = models.CharField(max_length=255, blank=True, default="Nothing to see here !") is_child = models.BooleanField(default=False) is_parent = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) # storing timestamps for users. created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) CHOICES = (('M','Male'),('F','Female'),('O','Other')) gender = models.CharField(max_length=10, choices=CHOICES) def get_absolute_url(self): return "/users/{}".format(self.username) def __str__(self): return "{} {}".format(self.first_name, self.last_name) class Child(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) friends = models.ManyToManyField('self', blank=True, related_name='friends', db_column='friends',) def __str__(self): return "{} {}".format(self.user.first_name, self.user.last_name) class Parent(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) connections = models.ManyToManyField('self', blank=True, related_name='connections', db_column='connections',) def __str__(self): return "{} {}".format(self.user.first_name, self.user.last_name) As you can see a Child can only be a friend with another Child and a Parent … -
How do you save Textarea form data line by line using Django's CreateView?
I have a Model and would like to save data as a batch by using a textarea form in Django. The data shall be save line by line, which I am using splitlines(), each data is comma separated by split(","). I am operating the manipulation in the form_valid() function but I can't seem to get it right. Only the last line is saved successfully. forms.py class DataForm(forms.ModelForm): textarea_data = forms.CharField(widget=forms.Textarea) class Meta: model = Item exclude = ('part_number','length','height','weight') views.py class InsertData(generic.CreateView): model = Item form_class = DataForm def get_success_url(self): return reverse('item_list') def form_valid(self, form): self.object = form.save(commit=False) textarea_data = form.cleaned_data['textarea_data '] data_line_list = textarea_data.splitlines() for each_line in data_line_list: each_line_list = each_line.split(",") self.object.part_number = each_line_list[0] self.object.length = each_line_list[1] self.object.weight = each_line_list[2] self.object.height = each_line_list[3] self.object.save() May I know where did I go wrong. Should the manipulation be done some where else? -
Add a new table row with HTMX
I am trying to add a new table row with Htmx. By clicking the "Add A New Row" button, a new row should be added to the table. I can't get the row in the secondary_hx.html to be added to the table, instead it results as three forms next to each other without or . Any help would be appreciated. Thank you in advance. My code is like this: main.html: <table id="myTable"> <thead> <tr> <th>1</th> <th>2</th> <th>3</th> </tr> </thead> <tbody id="Tbody"> <tr> <td> <button class="add_button" type="submit" hx-post="/add_row/" hx-target="#Tbody" hx-swap="beforeend" > Add A New Row </button> </td> </tr> </tbody> </table> partials/secondary_hx.html: <tr hx-target="this" hx-swap="outerHTML"> <td>{{ form.a }}</td> <td>{{ form.b }}</td> <td>{{ form.c }}</td> </tr> -
Programming Error: No result found Previous SQL was not a query in Django
I'm sending post request to the SQL Stored Procedure where I couldn't able to pass in the SQL it showing as no result. Even I tried the same approach for another API and passing it to another Stored Procedure which worked well. Programming Error at /api/Data/StartShift/ No results. Previous SQL was not a query. views.py: Here "IP" is empty @api_view(['POST', 'GET']) def UserStartShift(request): if request.method == 'GET': users = tblUserShiftDetails.objects.all() serializer = UserShiftStartSerializers(users, many=True) return Response(serializer.data) elif request.method == 'POST': UserId = request.POST.get('UserId') Ip = request.POST.get('Ip') PortNumber = request.POST.get('PortNumber') print("UserId-->", UserId) print("Ip-->", Ip) print('Portnumber-->', PortNumber) cursor = connection.cursor() cursor.execute('EXEC [dbo].[Usp_StartShift] @UserId=%s, @IP=%s, @Port=%s', (UserId, Ip, PortNumber,)) result_set = cursor.fetchall() response_data=[] for row in result_set: response_data.append( { "UserId":row[0], "Ip":row[1], 'PortNumber':row[2] } ) return Response(response_data, status=status.HTTP_200_OK) Here, is the Stored Procedure which I tried to access from Django SP: GO SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO ALTER Procedure [dbo].[Usp_StartShift] @UserId varchar(100), @IP nvarchar(255), @Port nvarchar(255) as begin insert into tblUserShiftDetails(UserId, IPAddress, PortNumber) values(@userid,@ip,'CD_'+@port) end -
TypeError: setQty is not a function. Can someone fit it. i cant solve that problem. Thanks beforehand
`<Form.Select as="select" value={qty} onChange={(e) => setQty(e.target.value)}> {[...Array(product.countInStock).keys()].map((x) => ( {x + 1}))} ` Here is the code... -
how do i get email delivery report(IP addresses (if more devices received email) ,message opened time, received time) python django [duplicate]
I have sent email to a test email address using smtp.EmailBackend python Django, how do i get email delivery report(IP addresses (if more devices received email) ,message opened time, received time) -
date filter in django template - isoformat
When I use this snippet in django template <td id="tdId_{{ i.0 }}4">{{i.4|date:'c'}}</td> it outputs 2021-12-01T08:34:54. I'm losing some information. In the database is 2021-12-01 08:34:54.000 How can I achieve the correct result in django template? -
escpos-python printing is working fine on local server but not working on live server
ESCPOS PYTHON ERROR, printing is working fine on local server but not working on live server. PLEASE HELP -
Validation error on nested writable serializer
I have a writable nested serializer like this - class AddressSerializer(serializers.ModelSerializer): class Meta: model = publicAddress fields = "__all__" class customerSerializer(serializers.ModelSerializer): publicAdd = AddressSerializer(many=True) class Meta: model = customerMaster fields = ['id','publicAdd'] def create(self, validated_data): Address = validated_data.pop('publicAdd') customer = customerMaster.objects.create(**validated_data) for addres in Address: publicAddress.objects.create(customer=customer, **addres) return customer this all works fine until I apply validation such as class AddressSerializer(serializers.ModelSerializer): class Meta: model = publicAddress fields = "__all__" validators = [ UniqueTogetherValidator( queryset=publicAddress.objects.all(), fields=['customer', 'someValue'] ) ] And defining read_only_fields = ('customer',) in AddressSerializer won't help either. Now it throws an error such as cust field is always required and to send the cust value via api. Any help on how to validate this without an error? -
How to filter forms in django?
I am trying to make a rating system with django. So, I have: class Region(models.Model): name = models.CharField(max_length=50) slug = models.SlugField(max_length=50, unique=True) def __str__(self): return self.name class Salesman(models.Model): region = models.ForeignKey(Region, related_name='region', on_delete=models.CASCADE) name = models.CharField(max_length=40) surname = models.CharField(max_length=40) def __str__(self): return self.name class Rating(models.Model): RATING_CHOICES = [(i, str(i)) for i in range(1,6)] salesman = models.ForeignKey(Salesman, related_name='salesman', on_delete=models.CASCADE) region = models.ForeignKey(Region, related_name='regions', on_delete=models.CASCADE) phone = models.CharField(max_length=15, blank=True) rating = models.IntegerField(choices=RATING_CHOICES, blank=False) sent_time = models.DateTimeField(auto_now_add=True) def __str__(self): return f"{self.rating}" It is my model. In the first page user should select the region and then form should be opened with salesman, phone and rating fields. And salesman fields must show those salesmen who work in the selected region. My forms.py is here: class RateAddForm(ModelForm): class Meta: model = Rating exclude = ('region',) def __init__(self, region=None, **kwargs): super(RateAddForm, self).__init__(**kwargs) if region: self.fields['salesman'].queryset = Salesman.objects.filter(region=region) But still it shows me all salesmen regardless of their region. My views.py is here: def report_add(request): if request.method == 'POST': form = RateAddForm(request.POST) if form.is_valid(): message = "Thanks!" form.save() return HttpResponse(message) else: form = RateAddForm() else: form = RateAddForm(request.POST) return render(request, 'account/report.html', {'form': form}) Are there anything I missed or would you suggest any good method? Thanks in … -
django pagination for controller
How to add pagination here? @method_decorator(admin_decorator()) def post(self, request): try: controller = UserListController(data=request.data) return Response(status=status.HTTP_200_OK, data=controller.get_data()) except Exception as e: print(e) return Response({"message": "Internal Server Error"}, status=status.HTTP_500_INTERNAL_SERVER_ERROR) -
How to do updateview in django using ajax
models.py from django.db import models # Create your models here. class Login(models.Model): username=models.TextField(max_length=30) password=models.TextField(max_length=30) class CreateProduct(models.Model): title = models.CharField(max_length=200) description = models.CharField(max_length=200) image = models.FileField(blank=True) def __str__(self): return self.title views.py from django.db import models from django.db.models import fields from django.shortcuts import redirect, render from django.views.generic import TemplateView,CreateView,FormView,ListView,DetailView from django.views.generic.edit import UpdateView from django.contrib.auth.models import User,auth from .models import CreateProduct from django.urls import reverse_lazy from django.shortcuts import get_object_or_404 # Create your views here. def home(request): return render(request,'index.html') def login(request): if request.method=="POST": username=request.POST['username'] password=request.POST['password'] user = auth.authenticate(username=username, password=password) if user is not None: auth.login(request, user) return redirect('productslist') else: return redirect('/') else: return render(request, 'index.html') class ProductsList(ListView): model = CreateProduct context_object_name = 'products' template_name = "productslist.html" class ProductsCreate(CreateView): model = CreateProduct fields = ['title','description','image'] template_name = "productscreate.html" success_url=reverse_lazy('productslist') class ProductsDetailView(DetailView): template_name = "productsdetail.html" queryset = CreateProduct.objects.all() context_object_name = 'products' model = CreateProduct class ProductsUpdate(UpdateView): model = CreateProduct fields = ['title','description','image'] template_name = "productsupdate.html" queryset = CreateProduct.objects.all() success_url=reverse_lazy('productsdetail') productdetail.html <!DOCTYPE html> {% load static %} <html lang="en"> <head> <!-- <title>Bootstrap Example</title> --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script> </head> <body> <nav class="navbar navbar-inverse"> <div class="container-fluid"> <!-- <div class="navbar-header"> <a class="navbar-brand" href="#">WebSiteName</a> </div> --> <ul class="nav navbar-nav"> <li … -
How to get the name of the same file uploaded as Response when downloading in python Django
I uploaded and downloaded the file. I do not get the name of the file I uploaded when I downloaded it. I try to program in python Django, any solution to solve this. def mDownloadResume(request, userid): profile = UserProfile.objects.get(id=userid) ts = profile.up_auth_user_id print(ts) resumefilename = Resume.objects.get(rs_auth_user_id=ts) vs = resumefilename.rs_original_name us = resumefilename.rs_auth_user_id ts = resumefilename.rs_saved_name contentype = "application/pdf" filepath = os.path.join(BASE_DIR , "Resume", ts) if os.path.exists(filepath): with open(filepath, 'rb') as fh: response = HttpResponse(fh.read(), content_type=contentype) response['Content-Disposition'] = 'inline; filename=' +os.path.basename(filepath) \ return response raise Http404 -
Cant able to access the django application hosted on nginx in another system in same lan network (windows)
Not able to access the django application in another system which is hosted on nginx in window's machine under same lan network. getting "This site cant be reached" page. Please do needful