Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to access user instance in custom login system?
I want to make a very custom login system and I'm failing to receive the user instance when the token is sent within the headers. I have number of APIs which need to work with and without users logged in and need to access the user.id (primary key). In my custom Login, I want to get the user instance and do a custom check. But I can never access the user even though the token is created and is being sent within the header. I'm sending the token in header within Postman: "Authorization": "Token {{token}}" settings.py: ..... INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'channels', 'corsheaders', 'pgtrigger', 'rest_framework', 'rest_framework.authtoken', 'myapp' ] ..... AUTH_USER_MODEL = "myapp.User" ..... login.py: from typing import Any from django.db.models import Q from rest_framework.authentication import BasicAuthentication, SessionAuthentication, TokenAuthentication from rest_framework.authtoken.models import Token from rest_framework.permissions import IsAuthenticated, AllowAny from rest_framework.request import Request, QueryDict from rest_framework.views import APIView import bcrypt from myapp.util.functions import contains, API_CallBack from myapp.util.classes import Error from myapp.models.user.user import User class Endpoint(APIView): authentication_classes = [BasicAuthentication, SessionAuthentication] permission_classes = [AllowAny] def post(self, request: Request): # -------------------- # Get and Check Data # -------------------- print() print(request.user) // NOT GETTING THE USER HERE print() par: QueryDict = … -
Django 4.1 not identifying static file
i'm a beginner with Django and have been working a small project that requires quite a bit of styling. However, for some reason, Django isn't picking up on my static css file. This is what I have in settings.py folder. from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent TEMPLATES_DIR = Path(BASE_DIR) / 'templates' STATIC_DIR = Path(BASE_DIR) / 'static' # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/4.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'django-insecure-nke)1=*9!e-26=n8_u@eki%9#o7=*@wn@mhg-84#i&s@s8ofr$' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'CalculatorApp' ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'Calculator.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [TEMPLATES_DIR,], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'Calculator.wsgi.application' # Database # https://docs.djangoproject.com/en/4.1/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', } } # Password validation # https://docs.djangoproject.com/en/4.1/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, … -
I have a problem in submitting comments to server using json and fetch in django
I am working on a bookstore project using django and javascript. I want to allow user to add comments on each book and send the comment without reloading the page using JSON html: <form id="addcomment"> {% csrf_token %} <input hidden name='thecommentuser' value="{{ request.user.id }}" id="commentsubmitter"> <input hidden name='thecommentbook' value="{{ book.id }}" id="commentbook"> <textarea name='thecomment'id="comment"></textarea> <input type="submit"> </form> script: document.addEventListener('DOMContentLoaded', function() { document.querySelector('#addcomment').onsubmit = function() { fetch('/comments', { method: 'POST', body: JSON.stringify({ thecomment: document.querySelector('#comment').value, thecommentuser: document.querySelector('#commentsubmitter').value, thecommentbook: document.querySelector('#commentbook').value, })})}}); models.py: class comments(models.Model): comment = models.CharField(max_length= 100) commentuser = models.ForeignKey('User', on_delete=models.CASCADE, default=None) commentbook = models.ForeignKey('books', on_delete=models.CASCADE, default=None) def serialize(self): return { 'thecomment': self.comment, 'thecommentuser': self.commentuser, 'thecommentbook': self.commentbook } urls.py: urlpatterns = [ path('comments', views.addcomments, name='comments') ] views.py: @csrf_exempt @login_required def addcomments(request): if request.method == 'POST': print('posted') data= json.loads(request.body) comment = data.get('thecomment', '') commentuser = data.get('thecommentuser') commentbook = data.get('thecommentbook', '') cuser = User.objects.get(id = commentuser) cbook = books.objects.get(id = commentbook) thecommentt = comments( thecomment=comment, thecommentuser=cuser, thecommentbook=cbook ) thecommentt.save() when I open the comments in the admin page I don't find any submitted data and the page reload upon submitting a comment. the order of print('posted') in views.py isn't displayed to me upon adding a comment and that means that the request isn't sent … -
TypeError at /studentform Field 'prn_no' expected a number but got ('1',)
I had a problem here....so I have created a MySql databases and connected it with Django framework, my website'titled 'School Management System' has 5 tables and all of them work flawlessly whether it is fetching data from user through Django forms and storing it in mysql database or vice versa but Student and faculty table returns same error as mentioned below : TypeError at /studentform Field 'prn_no' expected a number but got ('1',). I dont understand what is it that is leading to this error. Rest all I tried deleting my whole Django migration and creating it again my python manage.py makemigration python manage.py migration But still the same error. Below are some snippets of my code: studentform.html {% extends 'base.html' %} {% block title %}Student{% endblock title %} {% block body %} <div class="container"> <br> <form class="row g-3" method="post" action="/studentform"> {% csrf_token %} <div class="col-md-4"> <label for="prn_no" class="form-label">prn_no</label> <input type="number" class="form-control" id="prn_no" name="prn_no" required> </div> <div class="col-md-4"> <label for="fname" class="form-label">fname</label> <input type="text" class="form-control" id="fname" name="fname" required> </div> <div class="col-md-4"> <label for="lname" class="form-label">lname</label> <input type="text" class="form-control" id="lname" name="lname" required> </div> <div class="col-md-4"> <label for="DOB" class="form-label">DOB</label> <input type="date" class="form-control" id="DOB" name="DOB" required> </div> <div class="col-md-4"> <label for="Address" class="form-label">Address</label> <input type="text" class="form-control" … -
Randomly changing text in django base template
I have just started learning Django. Currently I am building project with several apps. I have templates folder at the project level which contains base.html. This file contains Bootstrap5 elements Navbar and Card (quote). At the app level I also have templates folder that contains several html files. All of them extends base.html from project level. I would like to randomly change the text in quote Card, so every time when bowser render template from app level it displays new quote. I have Model named Quotes at the app level and I can use quote=Quotes.objects.all(?).first() to select random entry. But I have no idea how to connect to the base.html. Could you give me a hint how to solve my problem? <!--templates/base.html--> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <!-- CSS only --> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-Zenh87qX5JnK2Jl0vWa8Ck2rdkQ2Bzep5IDxbcnCeuOxjzrPF/et3URy9Bv1WTRi" crossorigin="anonymous"> <!-- JavaScript Bundle with Popper --> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-OERcA2EqjJCMA+/3y+gxIOqMEjwtxJY7qPCqsdltbNJuaOe923+mo//f6V8Qbsw3" crossorigin="anonymous"></script> <title>{% block title %}{% endblock title %}</title> </head> <body> <!--NAVBAR--> <nav class="navbar navbar-expand-lg bg-light"> <div class="container-fluid"> <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarNav"> <ul class="navbar-nav"> <li class="nav-item"> <a class="nav-link active" aria-current="page" href="#">Home</a> </li> <li class="nav-item"> <a … -
Why upgrading django version to 3.2 makes project run "ValueError: Empty module name"?
when I upgrade django version from 3.1 to 3.2 and run my django project, I faced this error: Exception in thread django-main-thread: Traceback (most recent call last): File "/usr/lib/python3.8/threading.py", line 932, in _bootstrap_inner self.run() File "/usr/lib/python3.8/threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "/.../Kamva-Backend/venv/lib/python3.8/site-packages/django/utils/autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "/.../Kamva-Backend/venv/lib/python3.8/site-packages/django/core/management/commands/runserver.py", line 125, in inner_run autoreload.raise_last_exception() File "/.../Kamva-Backend/venv/lib/python3.8/site-packages/django/utils/autoreload.py", line 87, in raise_last_exception raise _exception[1] File "/.../Kamva-Backend/venv/lib/python3.8/site-packages/django/core/management/__init__.py", line 398, in execute autoreload.check_errors(django.setup)() File "/.../Kamva-Backend/venv/lib/python3.8/site-packages/django/utils/autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "/.../Kamva-Backend/venv/lib/python3.8/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/.../Kamva-Backend/venv/lib/python3.8/site-packages/django/apps/registry.py", line 91, in populate app_config = AppConfig.create(entry) File "/.../Kamva-Backend/venv/lib/python3.8/site-packages/django/apps/config.py", line 210, in create app_module = import_module(app_name) File "/usr/lib/python3.8/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1011, in _gcd_import File "<frozen importlib._bootstrap>", line 950, in _sanity_check ValueError: Empty module name I tried to run the project, but it fails with previous error. -
Heroku/ S3/ Django - Timed out running buildpack Python when pushing code to Heroku
I have deployed a django project onto Heroku and used S3 for statics. The S3 bucket is working: if I upload a picture on heroku, it gets uploaded on "websitename.3.amazonaws.com/static/". However, there is still 2 problems and I feel these 2 are actually related, as I didnt have that issue before I setup S3. First problem, the actual staticfiles dont seem to be working with Heroku: I can see them on the S3 bucket, but small styling tests (which are in statics) fail. Second problem, I get timed out when uploading statics with git push heroku master. remote: -----> $ python manage.py collectstatic --noinput remote: -----> Timed out running buildpack Python and I need disable statics if I wan to push anything. Interesting fact, if I run $ python manage.py collectstatic --noinput, I do not get timed out. However, it takes easily 25 minutes to upload collect. When I run heroku run python manage.py collectstatic --dry-run --noinput, no error is returned either. I am a bit insure what code to post, as this is the first time I attempting to do something like this and I dont see be to getting any error message beside "timeout". I found a few … -
DoesNotExist at /settings : Profile matching query does not exist
@login_required(login_url='signin') def settings(request): user_profile = Profile.objects.get(user=request.user) if request.method == 'POST': if request.FILES.get('image') == None: image = user_profile.profileimg bio = request.POST['bio'] location = request.POST['location'] user_profile.profileimg = image user_profile.bio = bio user_profile.location = location user_profile.save() if request.FILES.get('image') !=None: image = request.FILES.get('image') bio = request.POST['bio'] location = request.POST['location'] user_profile.profileimg = image user_profile.bio = bio user_profile.location = location user_profile.save() return render(request, 'setting.html', {'user_profile' :user_profile}) user_profile = Profile.objects.get(user_profile=request.user) Hello i am trying to run this code for a social app i am creating and i cant proceed further because i keep getting an error message and i cant proceed. please i need help with this thank you. -
How to group by and get latest record in group contain all of fields in Django?
Imagine we have a table like this: id name type created_at 1 James male 2022-03-02 2 Jane female 2022-04-02 3 Kirk male 2022-03-04 4 Sarah female 2022-04-04 5 Jason male 2022-03-05 And i want to group by type and just get latest records based on created_at. So i tried this code and not bad: result = User.objects.values('type').annotate( latest_date=Max('created_at'), ) When print the result i face to this: <QuerySet [ {'type': 'male', 'latest_date': '2022-03-05'}, {'type': 'female', 'latest_date': '2022-04-04'} ]> My question is: Where is other fields id and name? I expect to get: <QuerySet [ {id: 5, name: 'Jason', 'type': 'male', 'latest_date': '2022-03-05'}, {id: 4, name: 'Sarah', 'type': 'female', 'latest_date': '2022-04-04'} ]> -
Content not visible on webpage
I am creating a database website with python and django. My problem is that the content I try to get data from my class' fields doesn't appear on the id-page on django. I am able to make a successful search, and I get links for my searches. The name-field is visible in searches and on the page, but nothing else appears. When I click on the link, I go to luokka_id/number. I must be missing something but can't figure out what the problem is. models.py class luokka(models.Model): nimi = models.CharField('Pääkäyttöluokka', max_length=100) vara = models.CharField('Varakäyttöluokka', max_length=100) varaaja = models.CharField('Varakäyttöluokka', max_length=100) def __str__(self): return self.nimi and on the näytä_luokka.html (show class): {% extends 'tietokanta/base.html' %} {% block content %} <center> {{luokkalistaus}} {{luokka}} {{ luokka.nimi }} {{ luokka.vara }} {{ luokka.varaaja }} </center> {% endblock %} and views.py: def näytä_luokka(request, luokka_id): luokkalistaus = luokka.objects.get(pk=luokka_id) return render(request, 'tietokanta/näytä_luokat.html', {'luokkalistaus': luokkalistaus}) I don't get any errors to help me out here. It's just an empty page, but it should show some extra data. Thank you for your help, a beginner -
Django Form - Selection dependent on another field
I am creating application to manage home budget. I've got a few models - Date, Expense, Category, Income. It looks like this class Date(models.Model): name = models.CharField(max_length = 15) user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='date') class Category(models.Model): name = models.CharField(max_length=100) budget = models.DecimalField(max_digits=8, decimal_places=2) user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='category') date = models.ForeignKey(Date, on_delete=models.CASCADE, related_name='date', default='Styczeń 2022') class Expense(models.Model): name = models.CharField(max_length=100) amount = models.DecimalField(max_digits=8, decimal_places=2) category = models.ForeignKey(Category, on_delete=models.CASCADE) account = models.ForeignKey(Account, on_delete=models.CASCADE, related_name="account") user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='expense') date = models.ForeignKey(Date, on_delete=models.CASCADE, default='Styczeń 2022') class Income(models.Model): name = models.CharField(max_length=100) amount = models.DecimalField(max_digits=8, decimal_places=2) account = models.ForeignKey(Account, on_delete=models.CASCADE, related_name="account_income") user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='income') How can I make the category selection dependent on the date in ExpenseForm? Each category has its own date. I need to display categories only for the selected date in the expense form. This is because the user does not know which category to select if they have several of the same one. For example, "Food" for "January 2022", "February 2022" and "March 2022". This is how my ExpenseForm looks now: class ExpenseForm(forms.ModelForm): class Meta: model = Expense fields = ('name', 'amount', 'category', 'account', 'date',) def __init__(self, user, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['category'] = forms.ModelChoiceField(queryset=user.category.all()) self.fields['account'] = … -
Current path didn't match the url patterns - Django
I am unable to get the url redirected to one of the patterns defined in the url routing file. web.py from django.urls import path from django.contrib import admin from heyurl import views urlpatterns = [ path('admin/', admin.site.urls), path('', views.index, name='index'), path('store', views.store, name='store'), path('/metrics/', views.get_month_metrics, name= 'metrics'), ] views.py (Includes the function that is getting called along with the libraries included) from django.shortcuts import render, redirect from django.http import HttpResponse from .models import Url, Click from django.core.validators import URLValidator, ValidationError from heyurl.utils import db_services, helper from django_user_agents.utils import get_user_agent from django.template.defaulttags import register from datetime import datetime def get_month_metrics(request, url): today = datetime.now() ident = Url.objects.filter(short_url= url) ident = ident[0].id # GETTING THE CLICKS THIS MONTH clicks_this_month = Click.objects.filter(url=ident, created_at__year=today.year, created_at__month=today.month) # TOTAL CLICKS PER BROWSER safari = Click.objects.filter(url=ident, browser__contains='safari') chrome = Click.objects.filter(url=ident, browser__contains='chrome') firefox = Click.objects.filter(url=ident, browser__contains='firefox') # TOTAL CLICKS PER PLATFORM mobile = Click.objects.filter(url=ident, platform='Mobile') pc = Click.objects.filter(url=ident, platform='PC') #CONTEXT TO DISPLAY ON DATA PANEL context = { 'url': url, 'clicks': len(clicks_this_month), 'safari': len(safari), 'chrome': len(chrome), 'firefox': len(firefox), 'mobile': len(mobile), 'pc': len(pc), } return render(request, 'heyurl/metrics.html', context) Now I tried hardcoding and supplied the exact pattern that it says is missing by changing the web.py as follows urlpatterns … -
Deleting database object via a button in Vue component
I am using Django as backend and using VueJS via Vite for frontend. I currently make a GET request for data through "api/recipes". I am looking to add a button in my Vue component to make a DELETE request for the appropriate recipe. Format is not an issue, the recipes could appear in a list style with each having their button to simply DELETE. The idea would be to use the fetch API, however it is the logic of eventually deleting an object from backend I do not understand. App.vue <template> <div> <button @click="fetchRecipes">Fetch Recipes</button> <div> <ul> <li v-for="recipe in recipes"> {{ recipe.name }} <span v-if="!recipe.popular">(Not very popular!)</span> </li> </ul> </div> </div> </template> <script> export default { data() { return { recipes: [], } }, methods: { async fetchRecipes() { // Perform an Ajax request to fetch the list of recipes let response = await fetch("http://localhost:8000/api/recipes/") let data = await response.json() this.recipes = data.recipes } } } </script> urls.py from django.contrib import admin from django.urls import path from mainapp.views import index, recipes_api urlpatterns = [ path('', index), path('api/recipes/', recipes_api), ] models.py from django.db import models class Recipe(models.Model): name = models.CharField(max_length=350) popular = models.BooleanField(default=False) def __str__(self): return self.name def to_dict(self): return … -
Django Error: join() argument must be str, bytes, or os.PathLike object, not 'tuple'
I am using Djagno 4.1.2. I successfully used the built in Class Example(CreateView): from django.views.generic.edit When I submitted the form I received an error because Django didn't know what to do next. I had forgotten to put in the success_url I imported from django.urls import reverse_lazy and my view looked like this: from django.shortcuts import render from django.views.generic.edit import CreateView from Techtips.models import Techtip from django.urls import reverse_lazy class TechtipCreateView(CreateView): model = Techtip fields = ['title', 'year', 'year2', 'make', 'model', 'description'] template_name = 'techtips/create_techtip.html', success_url = reverse_lazy('home') The next time I tried to use this view I received the following error: join() argument must be str, bytes, or os.PathLike object, not 'tuple' Environment: Request Method: GET Request URL: http://127.0.0.1:8000/techtips/create/ Django Version: 4.1.2 Python Version: 3.10.8 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'Techtips', 'Home', 'accounts', 'phonenumber_field'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback (most recent call last): File "C:\Users\Logan\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\handlers\exception.py", line 55, in inner response = get_response(request) File "C:\Users\Logan\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\handlers\base.py", line 220, in _get_response response = response.render() File "C:\Users\Logan\AppData\Local\Programs\Python\Python310\lib\site-packages\django\template\response.py", line 114, in render self.content = self.rendered_content File "C:\Users\Logan\AppData\Local\Programs\Python\Python310\lib\site-packages\django\template\response.py", line 90, in rendered_content template = self.resolve_template(self.template_name) File "C:\Users\Logan\AppData\Local\Programs\Python\Python310\lib\site-packages\django\template\response.py", line 72, in resolve_template return select_template(template, using=self.using) File "C:\Users\Logan\AppData\Local\Programs\Python\Python310\lib\site-packages\django\template\loader.py", line 42, … -
Python/Django not refreshing current date on server
I am using calendar on my server. The current day should be marked but it is not refreshing it. As a result, marked day is the day of server restart. Do you have any solution to this issue? I want it to mark correct day, not the day on which server occurred. Thanks for help. -
Django UniqueConstraint with expressions fails
I am trying and failing to create a UniqueConstraint for a model combining a TruncDate expression of a datetime field and a couple of other fields following the approach here: https://docs.djangoproject.com/en/4.1/ref/models/constraints/#expressions The idea is that each User can only create one Point per day for a Definition This will work if I just use the TruncDate expression, or if I don't use the expression and create a constraint using fields = ("bucket", "user", "definition") but fails if I try to combine the expression with other fields. Database is Postgresql. Can anyone shed any light? models.py class Point(models.Model): definition = models.ForeignKey(Definition, on_delete=models.CASCADE) user = models.ForeignKey(User, on_delete=models.CASCADE) bucket = models.DateTimeField(default=timezone.now) value = models.DecimalField(decimal_places=5, max_digits=10) class Meta: ordering = ["-bucket", "definition"] constraints = [ UniqueConstraint( TruncDate("bucket"), "user", "definition", name="max_daily_frequency", ) ] test.py class TestPoint(TestCase) def test_make_point(self) u = User.objects.create() d = Definition.objects.create() p = Point.objects.create(user=u, definition=d, value=Decimal(1)) assert p.pk This fails with the following: /usr/local/lib/python3.10/site-packages/factory/base.py:40: in __call__ return cls.create(**kwargs) /usr/local/lib/python3.10/site-packages/factory/base.py:528: in create return cls._generate(enums.CREATE_STRATEGY, kwargs) /usr/local/lib/python3.10/site-packages/factory/django.py:117: in _generate return super()._generate(strategy, params) /usr/local/lib/python3.10/site-packages/factory/base.py:465: in _generate return step.build() /usr/local/lib/python3.10/site-packages/factory/builder.py:262: in build instance = self.factory_meta.instantiate( /usr/local/lib/python3.10/site-packages/factory/base.py:317: in instantiate return self.factory._create(model, *args, **kwargs) /usr/local/lib/python3.10/site-packages/factory/django.py:166: in _create return manager.create(*args, **kwargs) /usr/local/lib/python3.10/site-packages/django/db/models/manager.py:85: in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) /usr/local/lib/python3.10/site-packages/django/db/models/query.py:671: … -
Virtual Environments not showing the packages I've installed
I've been using virtual environments without problems but lately when I activate a certain environment and I try to run the project I get an error that some packages are not installed, if I do a pip list I get a list for a lot of packages that I haven't installed on this environment and if i go to the Site-Packages folder on the venv I can see the ones I've install The list I get asgiref 3.5.2 autopep8 1.7.0 black 22.6.0 click 8.1.3 colorama 0.4.5 contourpy 1.0.5 cycler 0.11.0 dj-database-url 1.0.0 Django 4.1 django-decouple 2.1 django-heroku 0.3.1 djangorestframework 3.14.0 fonttools 4.37.4 gunicorn 20.1.0 isort 5.10.1 kiwisolver 1.4.4 matplotlib 3.6.1 mypy-extensions 0.4.3 numpy 1.23.4 packaging 21.3 pathspec 0.9.0 Pillow 9.2.0 pip 22.2.2 platformdirs 2.5.2 psycopg2 2.9.3 pycodestyle 2.9.1 pyparsing 3.0.9 python-dateutil 2.8.2 pytz 2022.5 setuptools 63.2.0 six 1.16.0 sqlparse 0.4.2 toml 0.10.2 tomli 2.0.1 tzdata 2022.2 whitenoise 6.2.0 The List i should get asgiref==3.5.2 beautifulsoup4==4.11.1 boto3==1.24.66 botocore==1.27.66 dj-database-url==1.0.0 Django==4.1 django-bootstrap4==22.2 django-heroku==0.3.1 django-storages==1.13.1 gunicorn==20.1.0 jmespath==1.0.1 Pillow==9.2.0 psycopg2==2.9.3 python-dateutil==2.8.2 python-decouple==3.6 s3transfer==0.6.0 six==1.16.0 soupsieve==2.3.2.post1 sqlparse==0.4.2 tzdata==2022.2 urllib3==1.26.12 whitenoise==6.2.0 I've tried to change the venv locations but its not working. pip freeze still not listing the ones I've installed. -
Need help rewriting raw SQL containing select from subquery followed by join to Django ORM
I have the following Message model: class Message(models.Model): sender = models.ForeignKey( to=settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="outgoing_messages", verbose_name=_("sender"), ) recipient = models.ForeignKey( to=settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="incoming_messages", verbose_name=_("recipient"), ) text = NormalizedTextField(verbose_name=_("text"), max_length=4096) date = models.DateTimeField(verbose_name=_("date/time"), auto_now_add=True) I need to get all users with whom the current user has a chat, while displaying the text and date of the last message. Here is the SQL I need to rewrite to Django ORM (%s is the current user's id): SELECT message.id, message.text, message.date, message.interlocutor_id, users_user.username AS interlocutor_username, users_user.image AS interlocutor_image FROM ( SELECT DISTINCT ON (interlocutor_id) messenger_message.id, messenger_message.text, messenger_message.date, CASE WHEN messenger_message.sender_id = %s THEN messenger_message.recipient_id ELSE messenger_message.sender_id END AS interlocutor_id FROM messenger_message WHERE ( messenger_message.sender_id = %s OR messenger_message.recipient_id = %s ) ORDER BY interlocutor_id, messenger_message.id DESC ) message JOIN users_user ON users_user.id = message.interlocutor_id I managed to rewrite the subquery (which I aliased as "messages" in SQL above), but I don't know how to join it with another table and get the required data. messages = ( models.Message.objects.filter( Q(sender=request.user) | Q(recipient=request.user) ) .annotate( interlocutor_id=Case( When(sender=request.user, then=F("recipient")), default=F("sender"), ) ) .order_by("interlocutor_id", "-pk") .distinct("interlocutor_id") ) -
context must be a dict rather than module
When I am filtering for my search bar I am getting this error. I am not sure what I am doing wrong here Watching this tutorial: https://www.youtube.com/watch?v=llbtoQTt4qw&t=3399s views.py class pplList(LoginRequiredMixin,ListView): model = People context_object_name = 'people' def get_context_data(self, **kwargs): search_input = self.get.GET.get('search-area') or '' if search_input: context['people'] = context['people'].filter(name__icontains=search_input) return context people_list.html {%if request.user.is_authenticated %} <p>{{request.user}}</p> <a href="{% url 'logout' %}">Logout</a> {% else %} <a href="{% url 'login' %}">Login</a> {% endif %} <hr> <h1>Interviewee Dashboard {{color}}</h1> <a href="{% url 'pplCre' %}"> Add Candidates</a> <form method="get"> <input type = 'text' name = 'search-are'> <input type = 'submit' value = 'Search'> </form> <table> <tr> <th> Item</th> <th> </th> </tr> {% for people in people %} <tr> <td>{{people.name}}</td> <td><a href="{% url 'pplDet' people.id %}">View</a></td> <td><a href="{% url 'pplUpd' people.id %}">Edit</a></td> <td><a href="{% url 'pplDel' people.id %}">Delete</a></td> </tr> {% empty %} <h3>No items in list</h3> {% endfor %} </table> -
Additional queryset in DetailView (using self)
I am creating application to manage home budget. I've got a few models - Date, Expense, Category, Income. It looks like this class Date(models.Model): name = models.CharField(max_length = 15) user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='date') class Category(models.Model): name = models.CharField(max_length=100) budget = models.DecimalField(max_digits=8, decimal_places=2) user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='category') date = models.ForeignKey(Date, on_delete=models.CASCADE, related_name='date', default='Styczeń 2022') class Expense(models.Model): name = models.CharField(max_length=100) amount = models.DecimalField(max_digits=8, decimal_places=2) category = models.ForeignKey(Category, on_delete=models.CASCADE) account = models.ForeignKey(Account, on_delete=models.CASCADE, related_name="account") user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='expense') date = models.ForeignKey(Date, on_delete=models.CASCADE, default='Styczeń 2022') class Income(models.Model): name = models.CharField(max_length=100) amount = models.DecimalField(max_digits=8, decimal_places=2) account = models.ForeignKey(Account, on_delete=models.CASCADE, related_name="account_income") user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='income') First of all user should choose a "Date", next it goes to DateDetailView. And on this DetailView I want to display Expense only for this Date. I tried wit objects.filter, but I don't know how I should write it properly. I wrote something like this class DateDetailView(DetailView): model = Date template_name = 'expense/date_detail.html' context_object_name = 'date' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['expense'] = Expense.objects.filter(date=F('pk')) return context I also tried this class DateDetailView(DetailView): model = Date template_name = 'expense/date_detail.html' context_object_name = 'date' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['expense'] = Expense.objects.filter(date=self.date) return context Have you got any … -
How to filter highest amount for each single date in Django
Modles: #Customer Table class Customer(models.Model): name = models.CharField(max_length=100) email = models.CharField(max_length=30) phone = models.CharField(max_length=12) def __str__(self): return f"Customer : {self.name}" #Order Table class Orders(models.Model): customer = models.ForeignKey(Customer, on_delete=models.CASCADE) order_date = models.DateTimeField(auto_now_add=True) total_amount = models.PositiveIntegerField() def __str__(self): return f"Customer: {self.customer.name} | Total Amount: {self.total_amount}" Query I am using: order = Orders.objects.values('customer__id', 'customer__name', 'customer__email', 'customer__phone').annotate(Sum('total_amount')).order_by('order_date') This is the result that I am receiving from the whole record:result data Result that I needed should be One highest total amount from each date/day. Means it should return one highest total amount per date/day and each day may contain different number of records. For example if we need 5 days record and each day have 10 enteries(assume), then it should give us only five highest total amount order from five days(one record per day of highest total amount order). hope you got my question( i tried my best to explain). -
How to display list of products that were filtered and fetched in js in Django?
I am trying to make a filter on my website. So, I am getting the value of users choice and fetching it and sending to view. In my view funtion I filtered the products. I can see the result on the console, but I can not display it on the webpage. So, can someone help me to display filtered products on my webpage. html <div class="table__menu"> <div class="swiper table__filter-top-menu"> <!-- Additional required wrapper --> <div class="swiper-wrapper"> <!-- Slides --> {% for productT in product_types %} <div class="swiper-slide"> <a href="#" class="table__btn" data-type="ocean" data-product="{{productT.id}}" >{{productT}}</a><!--{% url 'category_detail' productT.slug %}--> </div> {% endfor %} </div> </div> <a id="filter-icon" href="#" class="table__filter-icon table__filter-icon--hidden"> <picture><source srcset="{% static 'img/Filter.svg'%}" type="image/webp"><img src="{% static 'img/Filter.svg'%}" alt=""></picture> </a> </div> <div id="filter-menu" class="table__filter"> <div class="table__col"> <span> Виды: </span> <ul class="table__filter-menu table__filter-menu--types"> {% for category in categories %} <li class="table__filter-item "><a href="#" data-product = "{{category.id}}" class="table__filter-btn vid-product">{{category.title}}</a></li> <li class="table__filter-item "><a href="#" data-product = "{{category.id}}" class="table__filter-btn vid-product">{{category.title}}</a></li> {% endfor %} </ul> </div> <div class="table__col"> <span> Пол: </span> <ul class="table__filter-menu"> {% for i in gender %} <li class="table__filter-item"><a href="#" class="table__filter-btn gender" data-product="{{i.id}}">{{i}}</a></li> {% endfor %} </ul> </div> </div> js function Filter(productTId,productVId,genderId){ var gender = document.querySelector('.table__filter-btn--active') console.log(gender) var productV = document.querySelector('.table__filter-btn--active-1') var productT = document.querySelector('.table__btn--active') … -
why I'm automatically redirected to url?
I'm trying to make a to-do list with django. Urls.py ` urlpatterns = [ path('', views.index, name='tasks'), path('add', views.add, name='add') ] views.py ` class NewForm(forms.Form): task=forms.CharField(label='Add new task') tasks = [] # Create your views here. def index(request): return render(request, "tasks.html", { 'tasks':tasks }) def add(request): if request.method == "POST": form = NewForm(request.POST) if form.is_valid(): task=form.cleaned_data["task"] tasks.append(task) else: return render(request, "add.html", { 'form': form }) return render(request, "add.html", { 'form': NewForm() }) tasks.html ` {% extends "layout.html" %} {% block body %} <body> <h1> TASKS </h1> <ul>{% for task in tasks %} <li> {{ task }}</li> {% endfor%}</ul> <a href="{% url 'add' %}"> go to add </a> </body> {% endblock %} `` add.html ` {% extends "layout.html" %} {% block body %} <body> <h1> add task </h1> <form action="{% url 'tasks' %}" method="post"> {% csrf_token %} {{ form }} <input type="submit"> </form> <a href="{% url 'tasks' %}"> go to tasks</a> </body> {%endblock%} I've created an empty list in which the task should be added. expectation - When user fills the form and click on submit it should be added to the list and now I should view the form by visiting that url. instead of above I'm redirected to tasks … -
Linking VueJS (using Vite) and Django backend in a CRUD project where Fetch API is used
I am creating a CRUD project. Using vite I have decided to have VueJS to deal with frontend. I will use Django for backend. I have a form inside a vue component. How do I use data entered into this form to produce a json file and consequently create an object in my sqllite3 default django database? -
How do i rewrite Django function based views code in a class based view?
i have the following code for a function based view: fav = bool if post.favourites.filter(id=request.user.id).exists(): fav=True but i want to put that in the below class based view: class PostDetailView(DetailView): model = Post def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['productobj'] = Post.objects.get(id = self.kwargs['pk']) return context i am fairly new to Django, so i don't know all that much about functions inside class based views and how to pass parameters from them. can anyone help to add the code to the above class based view?