Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Update database when CSV file is updated
I have data on a CSV file that I have imported into the DB, and display the data into my index.html as a HTML table. The CSV is updated frequently Is there anyway to update the data in the DB from the CSV file every hour or day, or even every time rhe file is updated? -
How to convert GROUP BY sql to Django orm
for exmaple, the sql is SELECT *, COUNT(*) FROM message_like WHERE receiver_id = 1 GROUP BY bbs_article_id, bbs_comment_id ORDER BY - time; I hope that the result is queryset, not a dict. -
Convert function base view to class based view (DRF)
can someone help me convert this function component to class based view (rest framework concrete view)? I tried converting but landed with errors where serializer is false. Product image is required in the query. class Product(models.Model): title = models.CharField(max_length=200, unique=True) slug = models.SlugField(max_length=200, unique=True) description = models.TextField() price = models.DecimalField(max_digits=10, decimal_places=2, null=True, blank=True) stock = models.IntegerField() is_available = models.BooleanField(default=True) brand = models.ForeignKey(Brand, on_delete=models.CASCADE) category = models.ForeignKey(Category, on_delete=models.CASCADE) created_date = models.DateTimeField(auto_now_add=True) updated_date = models.DateTimeField(auto_now=True) class ProductImage(models.Model): image = models.ImageField(upload_to=get_upload_path) product = models.ForeignKey(Product, on_delete=models.CASCADE, related_name="product_images") def store(request, category_slug): cat = None products = None if category_slug != None: cat = get_object_or_404(Category, slug=category_slug) products = Product.objects.filter(category=cat) product_count = products.count() else: products = Product.objects.filter(is_available=True) products.count() context = { 'products': products, 'product_count': product_count } return render(request, 'store.html', context) what i tried with rest framework. Serializers: class ProductImageSerializer(serializers.ModelSerializer): class Meta: model = ProductImage fields = ('image',) class ProductSerializer(serializers.ModelSerializer): product_images = ProductImageSerializer(many=True, read_only=True) class Meta: model = Product fields = "__all__" def create(self, validated_data): profile_data = validated_data.pop('product_images') product = Product.objects.create(**validated_data) return product View: I tried with concrete views, product is filtered by category. class Store(generics.ListCreateAPIView): queryset = Product.objects.filter(is_available=True) serializer_class = ProductSerializer lookup_field = 'category_slug' lookup_url_kwarg = 'category_slug' def list(self, request, *args, **kwargs): queryset = self.get_queryset() cat_slug = … -
got an unexpected keyword argument 'max_lenght' . I don't know whats wrong with my code. Please somebody help me
from os import name from sre_constants import CATEGORY from unicodedata import category from django.db import models # Create your models here. CATEGORY = ( ('Stationary', 'Stationary'), ('Electronics', 'Electronics'), ('Food', 'Food'), ) class Product(models.Model): name = models.CharField(max_lenght=100, null=True) category = models.CharField(max_lenght=20, choices=CATEGORY, null=True) quantity = models.PositiveIntegerField(null=True) got an unexpected keyword argument 'max_lenght', how to solve this problem? -
How to retrieve Django model object using ForeignKey?
I am new to Django and I am having dificulty of understanding how search Querys and work. I have these models: User = settings.AUTH_USER_MODEL class List(models.Model): user = models.ForeignKey(User, default=1, null=True, on_delete=models.SET_NULL) name = models.CharField(max_length=200) class ListShared(models.Model): shared_list = models.ForeignKey(List, on_delete=models.CASCADE, related_name="shared_list") user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="sub_user") Idea is that single user can have any number of lists and share those lists to other users if they choose to do so. I am trying write three querys: Return all Lists created by user Return all Lists that are shared to user Return all above So far it seems that 1. can be achieved with : parent = User.objects.get(username=user_name) lists = parent.list_set.all() and 2. with: lists = ListShared.objects.filter(user__exact=user) But I can't seems to find a way to return every that user is connected to (3.). How can I achieve this? -
How can I configure launch.json so it could type automatic response?
I need python manage.py collectstatic run before python manage.py runserver when I run 'launch.json' in VSCode. Another problem, 'python manage.py collectstatic' almost always requires typing 'yes' or 'no'(python manage.py collectstatic), before continuing to execute. Can I make it send 'yes' automatically? { // Use IntelliSense to learn about possible attributes. // Hover to view descriptions of existing attributes. // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 "version": "0.2.0", "configurations": [ { "name": "Python: CollectStatic", "type": "python", "request": "launch", "program": "${workspaceFolder}\\manage.py", "args": [ "collectstatic" ], "django": true, "justMyCode": false }, { "name": "Python: Django", "type": "python", "request": "launch", "program": "${workspaceFolder}\\manage.py", "args": [ "runserver" ], "django": true, "justMyCode": false }, ], "compounds": [ { "name": "collectstatic/runserver", "configurations": ["Python: CollectStatic", "Python: Django"], "stopAll": true } ] } -
"Uncaught (in promise) Error: Request failed with status code 403" instead of redirecting to login page
Instead of getting redirected to the login page i get a 403 error when my JWT Token expired. What i'm trying to accomplish is that when the token expires or there is any other issue that leads to the token not being valid it redirects to the login page. But when the token (line 22-25 inside App.js is where the code related to the redirect is). AuthContext.js import React, { useEffect, useState } from 'react' import { API } from "../api" import axios from "axios" import { isAfter, isEqual, parseISO, sub } from 'date-fns' export const AuthContext = React.createContext(null) export function AuthContextProvider({ children }) { const [accessTokenExpiration, setAccessTokenExpiraton] = useState(undefined); const getUser = () => { return JSON.parse(localStorage.getItem('user')) } const isLoggedIn = () => { return localStorage.getItem('user') !== null } const [user, setUser] = useState(() => { return isLoggedIn() ? getUser() : null; }) const [shouldGoToLogin, setShouldGoToLogin] = useState(() => { if (!user || !user.access_token || !user.refresh_token) { return true; } return false; }) const logout = async () => { if (!user) { return; } const { access_token } = user; localStorage.removeItem('user') setUser(null); return axios.post(API.auth.logout, { headers: { "Authorization": `Bearer ${access_token}`, "Content-Type": "application/json" }, withCredentials: true }); } const … -
django modelform not seeing model
Anyone can help me with this ModelForm has no model class specified.. Already go through the code many times. Is there anything wrong with my code? I have go through other people that have same problem with me and address it but still have the same problem. forms.py class ProfileUpdateForm(ModelForm): class meta: model = User fields = [ 'full_name', 'address', 'postcode', 'phone_number', 'birthdate', ] models.py class User(AbstractBaseUser, PermissionsMixin, models.Model): uuid = models.UUIDField(default=uuid.uuid4, editable=False, unique=True) class StateChoices(models.TextChoices): AB = 'AB', _('AB') AC = 'AC', _('AC') email = models.EmailField( verbose_name='email address', unique=True, db_index=True, ) full_name = models.CharField( max_length=100, blank=True, ) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) address = models.CharField(max_length=150, blank=False) city = models.CharField(max_length=50, blank=False) state = models.CharField( max_length=15, choices=StateChoices.choices, default=StateChoices.SELANGOR, ) postcode = models.CharField(max_length=10, blank=False) phone_number = models.CharField(max_length=15, blank=False) update_profile = models.BooleanField(default=False) birthdate = models.DateField(auto_now=False, null=True, blank=True) is_lecturer = models.BooleanField(default=False) is_student = models.BooleanField(default=True) created_at = models.DateTimeField(auto_now_add=True, editable=False) updated_at = models.DateTimeField(auto_now=True, editable=False) objects = UserManager() USERNAME_FIELD = "email" def get_full_name(self): return self.full_name def __str__(self): if self.full_name == "": return f"{self.email}" else: return f"{self.full_name}" views.py def profileupdate(request, pk=None): key = request.user.pk user_pk = get_object_or_404(User, pk=key) if request.method == "POST": form = form = ProfileUpdateForm(request.POST, instance=user_pk) if form.is_valid(): form.save() return redirect('index') else: form = ProfileUpdateForm(instance=user_pk) … -
Insert multiple records in one query in mongodb using drf
I need to insert multiple records in the mongodb atlas. I am using djongo as database engine in my DRF backend. To save a single record, I send the data from React frontend and in the views.py file, I use the following code serializer = MySerializer(data=req.data) serializer.is_valid(raise_exception=True) serializer.save() And it works fine. But if I need to save multiple records in the database, I am sending a list of records and do this, for data in req.data['data']: serializer = MySerializer(data=data) serializer.is_valid(raise_exception=True) serializer.save() So, if the list is big, it takes a lot of time to insert all the records and I guess it is because all records are inserted by a separate query to the database. How can I insert all the records in the database quickly? -
python script returns The view website.views.buttonclick2 didn't return an HttpResponse object. It returned None instead
I am using django. I have added the below function into my views.py file. When i first start vs code the holehe GUI executes and the window pops up for me to enter text. However when I start the server and click the button on the holehe HTML page I receive the error "The view website.views.buttonclick2 didn't return an HttpResponse object. It returned None instead." I have tried adding at the bottom return render(request, 'holehe.html') however this doesnt work. Please can someone advise where I am going wrong ? def buttonclick2(request): if request.method == "POST": return def compile_terminal_command(terminal_command, last_line_index) : # The last line index stores the line where the command thread has to output in the listbox # since the listbox may have also received more commands in that span and the thread may take # some time to give output command_summary = terminal_command.split(' ') # Split the command and args. os.environ["PYTHONUNBUFFERED"] = "1" # MAKE SURE THE PREVIOUS OUTPUT IS NOT RECIEVED # > We use the subprocess module's run method to run the command and redirect output and errors # to the pipe from where we can extract it later. # > I will suggest running this … -
Websocket 502 Bad Gateway
I've two container for wsgi and asgi. wsgi server is running on 127.0.0.8000: gunicorn app.wsgi:application --bind 127.0.0.1:8000 Also asgi server is running on 127.0.0.1:8001 using of daphne: daphne -b 127.0.0.1 -p 8001 app.asgi:application I have a websocket request like this: wss://app.example.com/ws/chat/f770eef/ But unfortunately these errors occur in the system: i) nginx log says: 2022/05/22 13:15:29 [error] 463129#463129: *9 upstream prematurely closed connection while reading response header from upstream, client: 11.198.111.11, server: app.example.com, request: "GET /ws/chat/f770eef/ ii) Requests do not reach daphne. asgi.py import os from django.core.asgi import get_asgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'app.settings') application = get_asgi_application() nginx cofing: server { listen 443; listen [::]:443; server_name app.example.com; root /var/www/html; ... location /ws/ { proxy_pass http://127.0.0.1:1335; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; proxy_redirect off; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Host $server_name; proxy_read_timeout 300s; proxy_connect_timeout 75s; } ... } -
Make a get request with a multiple value param in django requests Module?
I have a webservice that give doc list. I call this webservice via get_doc_list. but when I pass 2 values to id__in, it return one mapping object. def get_doc_list(self, id__in): config = self.configurer.doc params = { "id__in": id__in, } response = self._make_request( token=self.access_token, method='get', proxies=self.proxies, url=config.service_url, params=params, module_name=self.module_name, finalize_response=False ) return response How can I fix it?! -
Automatic deployment of my django website after making changes
i have deployed my Django portfolio using nginx server.but now i want a feature in which i make changes to my Github repo and then it will get automatic deployed to my nginx server. how can i do this?. thankyou -
Add Serial Number on Django Form [closed]
I want to add serial no on the top of body with auto increment after submit form -
Django Return Queryset from Database table by filtering using Dictionary values
My goal is to return rows from the books table using values sent by a user through a search form. The search form contains multiple fields author, ISBN and title. NB: In the code, the author field is a char, but converted to ID based on authors name due to foreign key relation. In this code, there's a get request converted to Dictionary and transformed to allow it to query data from the books table. def search(request): form = BooksForm() if request.method == 'GET': # convert get request to dictionary book_search = dict(request.GET) print("data before cleaning", book_search) #get the name from the dictionary get request author_name =request.GET['author'] #get the author id from the author table author = Author.objects.filter(full_name__contains=author_name).values() #get author_id from author queryset author_id = author[0]['id'] #update the dict with the author id to allow search in books models (foreing key) book_search['author'] = author_id print("data after cleaning",book_search) result_set = Book.objects.filter(**book_search) print("book search queryset",result_set) Problem: When I query the books table using the dictionary it returns an empty query set and I want it to return books from in table. Does anyone have an idea of how I can make the code work? -
Build a custom authentication flow in a hosted django app for pydrive2
I am using Django as backend. I need to create a custom auth flow for pydrive2. I cannot use gauth.LocalWebserverAuth() as that is suitable only on local machines. I see this sample code at pydrive documentation for custom auth flow. from pydrive2.auth import GoogleAuth gauth = GoogleAuth() auth_url = gauth.GetAuthUrl() # Create authentication url user needs to visit code = AskUserToVisitLinkAndGiveCode(auth_url) # Your customized authentication flow gauth.Auth(code) # Authorize and build service from the code AskUserToVisitLinkAndGiveCode is the part that I am unable to understand. What should this function do? Should my backend redirect to the URI that I added as the redirect URI on google drive console? Or should I redirect the user to the auth_url link? -
Django server not reloading on file changes
I just cloned a Django project from my Github for maintenance on another machine, installed all the dependencies then ran the server. Everything seems to be working fine except the fact that the server does not reload when I make file changes (on all python files). Changes in static files are not reflected too. Things to note: Django 4.0.3 Python 3.9.0 Environment manager is Pipenv. Settings.py DEBUG = True TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, "templates")], I don't have a custom runserver command I have the suggestions on this question but they didn't work. Any help would be greatly appreciated. -
Django error when using if condition on integar
I want to write if condition on integer when write if condition on string its is working but when I want to write same condition its not working. {% if 209 in l.label %} Book Now ! {% else %} Booked! {% endif %} -
Не вызывается Modal window после нажатия кнопки
делаю свой первый сайт, использую django, python, bootstrap 5, хочу что бы после заполнения формы человек нажал кнопку "отправить" и после этого всплыло модальное окно в котором будет написано что "все ок, ваша заявка создана" <div class="row mt-5 mb-5 p-2"> <form action="{% url 'feedback_view' %}" method="POST"> {% csrf_token %} <div class="col-md-6 mb-2"> <label for="exampleInputName" class="form-label">Ваше Имя</label> <input name="name" class="form-control" id="exampleInputName" aria-describedby="NameHelp"> </div> <div class="col-md-6 mb-2"> <label for="exampleInputphone" class="form-label">Ваш Телефон</label> <input name="phone" class="form-control" id="exampleInputphone" aria-describedby="NameHelp" placeholder="+7 (918) 000-00-00"> </div> <button type="submit" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#exampleModal">Отправить</button> </form> </div> <button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#exampleModal">Отправить_btn</button> но почему-то кнопка 'отправить' не работает, но работает кнопка 'отправить_btn' которую я сделал для теста проблемы. все что я понял на данный момент что мне мешает type="submit" тк. во второй кнопке стоит type="button". как мне решить эту проблему, учитывая что это кнопка отправки формы? это код окна: {% if messages %} {% for message in messages %} <div class="modal fade" id="exampleModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="exampleModalLabel">Modal title</h5> <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button> </div> <div class="modal-body"> <p class="reviews">{{ message }}</p> </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button> <button type="button" class="btn btn-primary">Save changes</button> </div> </div> </div> </div> {% endfor %} {% endif … -
Static files are not loaded generating pdf from html when application run in ASGI layer
I use Weasyprint to generate pdf from HTML. When I configure ASGI static files are not loaded in pdf, if I run the application in WSGI then the static file loads correctly. How can I solve this issue? -
Django - annotate query for if queried user is followed by current user
So I have this code below that given a user_uuid I look up the info of a user. All request come with a auth token that contains the current user's uuid. If the current user queried for their own profile then the is_current_user key should be true, which is done with the item['is_current_user'] = user_uuid == request.user.uuid line and then I have another flag for if the current user is following the queried user which is item['is_following'] = FollowUser.objects.filter(follower=str(request.user.uuid), followee=user_uuid).exists(). As you can see these are very ugly hacks and I was wondering if I could add these values to the annotate function. def get_user_info(request, user_uuid): try: query_annotated = User.objects.annotate( follower_count=Count('followee_id', distinct=True), followee_count=Count('follower_id', distinct=True)).get(pk=user_uuid) except User.DoesNotExist as e: return Response(dict(error=str(e), user_message='User not found.'), status=status.HTTP_404_NOT_FOUND) serializer = FullUserSerializer(query_annotated) # TODO: This is a hack the above annotation is not working item = serializer.data item['is_following'] = FollowUser.objects.filter(follower=str(request.user.uuid), followee=user_uuid).exists() item['is_current_user'] = user_uuid == request.user.uuid return Response(item, status=status.HTTP_200_OK) -
Websocket connection using djangochannelsrestframework
Websocket connection connects and disconnects after a second and shows the following error. Tried different ports still gives the same error Error image -
Django, csrf token not set
in settings.py: #SESSION_COOKIE_SAMESITE = 'Strict' SESSION_COOKIE_HTTPONLY = True #CSRF_COOKIE_SECURE = True #SESSION_COOKIE_SECURE = True CSRF_TRUSTED_ORIGINS = [ "http://localhost:3000",'http://127.0.0.1:8000'] in views.py: @method_decorator(csrf_protect,name='dispatch') class LoginView(views.APIView): permission_classes = [AllowAny,] serializer_class = serializer.LoginSerializer def post(self,request): data = serializer.LoginSerializer(data=request.data) print(data.is_valid()) print(data.errors) if data.is_valid(): email = data.data['email'] password = data.data['password'] auth = authenticate(username=email,password=password) if auth: login(request,auth) return HttpResponse(request.session.session_key ,status=200) else: print(password == "") if email == "" and password =="": return HttpResponse('both email and password field are empty',status=400) elif email == "": return HttpResponse('email field is empty',status=400) elif password == "": print("Here") return HttpResponse('passowrd field is empty',status = 400) the problems occur in frontend, (localhost:3000) but here is part of login component: let handleSubmit = (e)=>{ e.preventDefault() axios.post('http://127.0.0.1:8000/login/',login,{withCredential:true},{headers: {'Content-Type': 'application/json','X-CSRFToken':Cookies.get('csrftoken')}}).then( (res)=>{ console.log(res.data) } } I am getting: Forbidden-Csrf token not set on the backend, but when i login from backend 127.0.0.1:8000/login it works fine, and session id is set as https only cookie, csrf is set in cookies, but when i do it from frontend, it gives an error any idea? -
Django exposes raw html on rendered website
I am learning Django with the documentation tutorial: https://docs.djangoproject.com/en/4.0/intro/tutorial03/ I have just completed the "Write views that actually do something" part, but somethings is definitely amiss. Even though I copied the code 1:1, this is the render I get: Last two bits of code I edited: index.html in polls/templates/polls directory: {% if latest_question_list %} <ul> {% for question in latest_question_list %} <li><a href="/polls/{{ question.id }}/">{{ question.question_text }}</a></li> {% endfor %} </ul> {% else %} <p>No polls are available.</p> {% endif %} views.py in polls directory: from django.http import HttpResponse from django.template import loader from .models import Question def index(request): latest_question_list = Question.objects.order_by('-pub_date')[:5] template = loader.get_template('polls/index.html') context = { 'latest_question_list': latest_question_list, } return HttpResponse(template.render(context, request)) def detail(request, question_id): return HttpResponse("You're looking at question %s." % question_id) def results(request, question_id): response = "You're looking at the results of question %s." return HttpResponse(response % question_id) def vote(request, question_id): return HttpResponse("You're voting on question %s." % question_id) -
Getting CORS error only when running django app through docker-compose
I have a Django backend app using Django-rest-framework. Currently, I'm developing the frontend with React using Axios to make HTTP requests. Whenever I run my app using python manage.py runserver and make a request from the React client, I get the expected response. Nevertheless, if I start my app using docker-compose, I get the No 'Access-Control-Allow-Origin' header is present on the requested resource response. This is my docker-compose.yaml services: db: image: postgres volumes: - /var/lib/docker/volumes/mobilequoter/db/data:/var/lib/postgresql/data ports: - ${DB_PORT}:5432 environment: - POSTGRES_USER=${DB_USER} - POSTGRES_PASSWORD=${DB_PASSWORD} - POSTGRES_DB=${DB_NAME} web: build: . command: gunicorn mobilequoter.wsgi --bind 0.0.0.0:${PORT} env_file: .env volumes: - .:/code ports: - 8000:${PORT} environment: - DB_HOST=db - DB_PORT=5432 depends_on: - db This is is my settings.py (with the settings related to CORS: handler = EnvHandler() SECRET_KEY = handler.SECRET_KEY DEBUG = handler.DEBUG ALLOWED_HOSTS = handler.ALLOWED_HOSTS CORS_ALLOWED_ORIGINS = handler.CORS_ALLOWED_ORIGINS SHELL_PLUS = 'ipython' INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', # third party 'rest_framework', 'drf_yasg', 'storages', 'django_extensions', 'corsheaders', # local 'mobilequoter.helper', 'mobilequoter.authentication', 'mobilequoter.client', 'mobilequoter.quote', 'mobilequoter.sale', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] This are my env vars related to hosts: ALLOWED_HOSTS=127.0.0.1,localhost CORS_ALLOWED_ORIGINS=http://127.0.0.1:3000,http://localhost:3000 This is my axios client: import axios from "axios"; const axiosClient = axios.create({ baseURL: process.env.REACT_APP_BACKEND_URL …