Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - Filtering queryset many times while using the same name?
in django docs I found this solution for filtering multiple time the same query in many lines: q1 = Entry.objects.filter(headline__startswith="What") q2 = q1.exclude(pub_date__gte=datetime.date.today()) q3 = q1.filter(pub_date__gte=datetime.date.today()) But I need to make it on one variable name. I created it like this thinking that it will work similar to python variables: q1 = Entry.objects.filter(headline__startswith="What") q1 = q1.exclude(pub_date__gte=datetime.date.today()) q1 = q1.filter(pub_date__gte=datetime.date.today()) But apparently it is not, I am doing something wrong. How can I achieve this while using one variable? -
unable to fide one specific template
when i got /contact in my website it shows this error i am created my models, views, forms.pyforms all root project which is website and I did not create any other application error views.py settings.py -
Django "if form.is_valid()" returns None
Im new to using Django and I am trying to have a file uploaded from a form, to then be handled after a POST request. However in my views function if form.is_valid() returns None and I am unable to retrieve the request.FILES['file']. Does anyone know what the issue is? Thanks views.py function: def success(request): if request.method == 'GET': return render(request, 'send_receive_files/success.html', {'form': UploadFileForm}) else: form = UploadFileForm(request.POST, request.FILES) if form.is_valid(): handle_uploaded_file(request.FILES['file']) return redirect('/') else: return HttpResponse('invalid') forms.py: from django import forms class UploadFileForm(forms.Form): title = forms.CharField(max_length=50) filer = forms.FileField() form template: {% block content %} {% load static %} <!DOCTYPE html> <html lang="en"> <head> <link rel="stylesheet" type="text/css" href="{% static 'css/dashboard.css' %}"> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link href="https://fonts.googleapis.com/css2?family=Roboto:ital,wght@0,300;1,100&display=swap" rel="stylesheet"> <title>Dashboard</title> </head> <header> <a id="header-link" href="/"> <h1 id="heading">File Share</h1> <div id="cont"> <a id ="login" class="header-buttons" href="/login">Logout</a> </div> </a> </header> <body> <center> <div id="send-container"> <form method="post" action="/dashboard/upload/"> {% csrf_token %} {% if error %} <p id="error">{{error}}</p> {% endif %} <input name="username-send" type="text" placeholder="Recipient's username" id="username" required> <input name="file-send" type="file" id="file" required> <p> <input type="submit" value="Send"> </p> </form> </div> </center> </body> </html> {% endblock %} -
Azure Django React Web App - Operational Error 1045
I deployed my django react web app on azure with a MySQL server being the database engine, but once I go to the django admin page to sign in, I'm getting this error I have 20.151.49.29 as one of my outbound IP addresses. Does anyone know why it's denying access? Also, my other web pages that are linked from the landing page are showing up as blank. -
comments in django not get stored in backend
I don't know why my comments are not get stored in backend .. it showing no error but I think it is logical error. Can somebody help me to find out the error ... it will be great help!! Thank you 1.Views.py from django.shortcuts import render, get_object_or_404, redirect from datasecurity.models import Post, BlogComment from django.urls import reverse from django.http import HttpResponseRedirect from django.contrib.auth.decorators import login_required from django.contrib import messages from django.contrib.auth.models import User # Create your views here. @login_required def likes(request, pk): post=get_object_or_404(Post, pk=pk) post.likes.add(request.user) return HttpResponseRedirect(reverse('datasecurity:datasecurity')) def datasecurity(request): allPosts= Post.objects.all() context={'allPosts': allPosts} return render(request, 'datasecurity/data.html',context=context) def blogHome(request, slug): post=Post.objects.filter(slug=slug).first() comments= BlogComment.objects.filter(post=post) context={'post':post, 'comments': comments, 'user': request.user} return render(request, "datasecurity/blogHome.html", context) def postComment(request): if request.method == "POST": comment=request.POST.get('comment') user=request.user postSno =request.POST.get('postSno') post= Post.objects.get(sno=postSno) comment=BlogComment(comment= comment, user=user, post=post) comment.save() return HttpResponseRedirect(reverse('datasecurity:blogHome')) 2.urls.py from django.conf.urls import url from . import views app_name = 'datasecurity' urlpatterns = [ url(r'^$', views.datasecurity, name="datasecurity"), url(r'^datasecurity/(?P<slug>[^/]+)', views.blogHome, name='blogHome'), url(r'^likes/(?P<pk>\d+)/', views.likes, name = "likes"), url(r'^datasecurity/postComment', views.postComment, name="postComment"), ] 3.models.py from django.db import models from ckeditor.fields import RichTextField from django.contrib.auth.models import User from django.utils.timezone import now # Create your models here. class Post(models.Model): sno=models.AutoField(primary_key=True) title=models.CharField(max_length=255) author=models.CharField(max_length=14) slug=models.CharField(max_length=130) timeStamp=models.DateTimeField(blank=True) content=RichTextField(blank=True, null=True) img = models.ImageField(blank=True, null=True, upload_to="dataimage/") likes = models.ManyToManyField(User) @property … -
Can I create a pool of token in DRF
Can I create a pool of token in Django RestFrame ? I want to create a pool of token, where I will have 'n' number of token. Later on I want to assign token to a user. How should I proceed ? -
How run django with pm2?
I have a django project on ubuntu 18.04 I wanna start and stop it with pm2. I've created a django_project.yml file with the following contents: apps: - cwd: 'directory_that_manage.py_exists_in_it' script: './manage.py runserver' args: 'server --binding 0.0.0.0' interpreter: 'python3' name : 'django_project' instances: 1 watch : false exec_mode: fork_mode then, I run it with the following command: pm2 start django_project.yml --interpreter ../.env/bin/python3 it starts, but after stop it and start it again, it gets the following errors. what is the problem? please help me. thanks -
Can we create Token in DRF without creating Superuser
Can we create Token in Django RestFramework without creating Superuser. I want to create a token pool, where I will have 'n' numbers of token, lateron on hitting a url a token from token pool will be assign to the user. Is this possible ? Is it possible to create a pool of DRF token ? And later on assign a token from pool to a user on hitting url? -
Why is my query not working for room.slug
Currently, I am trying there are 4 categories, each categories have 4 rooms. I am trying to write the view to enter that particular room but somehow even though I can render the page, what i query doesn't work.Why is this so? function-based views.py def room_view(request, category_slug, room_slug): context = {} category = get_object_or_404(Category, slug=category_slug) rooms = Room.objects.filter(typeofcategory=category) room = Room.objects.filter(slug=room_slug) context['room'] = room return render(request, "room.html", context) template {{ room_slug }} urls.py path('<slug:category_slug>/<slug:room_slug>/', room_view , name= "room"), models.py class Category(models.Model): type_of_category = models.CharField(max_length=80, null=False, blank=False, choices=type_of_category_CHOICES, default=True, unique=True) slug = models.SlugField(blank=True, unique=True) class Room(models.Model): typeofcategory = models.ForeignKey(Category, related_name='typeofcategory', on_delete=models.CASCADE) slug = models.SlugField(blank=True) -
Django IntegrityError when editing a value referenced by a foreign key
I have an app with two (relevant) models, in what is essentially a CRM: class StudentTutorRelationshipProfile(models.Model): pupil_name = models.CharField(max_length=100, unique=True) parent_name = models.CharField(max_length=100) ... class TimeSheet(models.Model): user = models.ForeignKey( User, on_delete=models.PROTECT, limit_choices_to={"is_tutor": True} ) student = models.ForeignKey( StudentTutorRelationshipProfile, on_delete=models.CASCADE, to_field="pupil_name" ) ... Now someone has misspelled a pupil's name and would like to change it pupil_name in StudentTutorRelationshipProfile but because there are already TimeSheet records with the Students misspelled name, Django raises an error (from psychog): ForeignKeyViolation: update or delete on table "invoicing_studenttutorrelationshipprofile" violates foreign key constraint "invoicing_timesheet_student_id_07889dc0_fk_invoicing" on table "invoicing_timesheet" DETAIL: Key (pupil_name)=(Student Name) is still referenced from table "invoicing_timesheet". File "django/db/backends/base/base.py", line 243, in _commit return self.connection.commit() IntegrityError: update or delete on table "invoicing_studenttutorrelationshipprofile" violates foreign key constraint "invoicing_timesheet_student_id_07889dc0_fk_invoicing" on table "invoicing_timesheet" DETAIL: Key (pupil_name)=(Student Name) is still referenced from table "invoicing_timesheet". What is a nice way of changing this data? I don't mind changing the historic timesheets too or leaving them as is (but can't delete them), what ever is easier / less likley to lead to problems. (And yes the fact that I rely on unique name and surname combinations is not ideal, but won't fix that for now unless the change for the IntegrityError also … -
why Django loss it's dependencies
I made a few django+react websites before. But, they work very fine for a while and later after I run few git commits and many other changes the Django backend start showing errors like " there is no module named Django" or "there is no module named django-allauth" despite I installed all of them before and the website was working very well. Could that be because of the environment? what if I used docker could it help to prevent such things? or it may be a problem with code only? -
How inject data from ('another') model in admin?
I have User model: class PublisherProfile(models.Model): publisher_id = models.AutoField(primary_key=True) user_profile = models.OneToOneField(Profile, on_delete=models.SET_NULL, null=True, verbose_name=_("user profile")) In admin I registered this model: @admin.register(PublisherProfile) class PublisherProfileAdmin(admin.ModelAdmin): list_display = ( "publisher_id", "user_profile", ) In another model I have: class PublisherOffer(models.Model): offer_owner = models.ForeignKey('user.PublisherProfile', on_delete=models.CASCADE, verbose_name=_("offer owner"), ) title = models.CharField(_('Offer title'), help_text=_('Title of the offer.'), max_length=250, blank=False, null=False) How can I inject all PublisherOffer to PublisherProfileAdmin? -
Things in a list dont show up Django
Im having a problem with my django project (again). Im trying to make a feature which adds an article and then displays all of articles as a list. What happens is that it just doesnt display it and i have no idea why. views: from django.shortcuts import render from django.http import HttpResponse from . import util import random created_articles = ["lol","pls"] def index(request): entries = util.list_entries() random_page = random.choice(entries) return render(request, "encyclopedia/index.html", { "entries": util.list_entries(), "random_page": random_page, }) def CSS(request): return render(request, "encyclopedia/css_tem.html", { "article_css": "css is slug and cat" }) def Python(request): return render(request, "encyclopedia/python_tem.html", { "article_python": "python says repost if scav" }) def HTML(request): return render(request, "encyclopedia/HTML_tem.html", { "article_HTML": "game theory: scavs are future humans" }) def Git(request): return render(request, "encyclopedia/Git_tem.html", { "article_Git": "github is git" }) def Django(request): return render(request, "encyclopedia/Django_tem.html", { "article_Django": "this is a framework" }) def new_article(request): return render(request, "encyclopedia/new_article_tem.html", { "article_Django": "this is a framework" }) new_article (here i can type what i want to be in article): {% extends "encyclopedia/layout.html" %} {% block title %} New Article {% endblock %} {% block body %} <h1>Create Article</h1> <form action = "http://127.0.0.1:8000"> <textarea class="new_article_title_css" type="text" name="new_article_title" placeholder="This will be the title of your article!"></textarea> … -
Django Oscar- Nested expandable categories
I'm having problem with expandable product categories in Django Oscar. Here is my template code: <ul> {% for tree_category in tree_categories %} {% if tree_category.pk == category.pk %} # If we are in current category: <li class="has-children expanded"><a href="{{ tree_category.url }}"><strong>{{ tree_category.name }}</strong> {% else %} # If not in current category: <li class="has-children"><a href="{{ tree_category.url }}">{{ tree_category.name }}</a> {% endif %} {% if tree_category.has_children %}<ul>{% else %}</li>{% endif %} {% for n in tree_category.num_to_close %}</ul></li>{% endfor %} {% endfor %} </ul> This works fine if you click on any top category...: Example: Categories But if you click on subcategory then whole thing closes This is what I'm trying to accomplish Some resources: Here is the link to original Oscar's template and related documentation I would really appreciate any help or suggestions... -
Django - How to delete an entry from model by user?
I am new in Django framework. And I am developing a web app. In this app I have a list of entries like (Title and description). I have add one more column that contains a delete button. I want when someone click on that button (delete button) it deletes entry. For front end I am using Bootstrap. my views.py from django.http import request from .models import Task from django.http.response import HttpResponse from django.shortcuts import render # Create your views here. def home(request): context = {"success": False} if request.method=='POST': title= request.POST['title'] desc = request.POST['desc'] print(title, desc) ins = Task(title=title, desc=desc) ins.save() context = {"success": True} return render(request, 'index.html', context) def tasks(request): alltasks = Task.objects.all() # print(alltasks) # for item in alltasks: # print(item.title) context = {'tasks': alltasks} return render(request, 'tasks.html', context) def delete_view(): object = Task.objects.get(id = part_id) object.delete return render(request, 'tasks.html') my urls.py from django.contrib import admin from django.urls import path from . import views urlpatterns = [ path('', views.home, name="home"), path('tasks', views.tasks, name="tasks"), path(r'^delete/(?P<part_id>[0-9]+)/$', views.delete_view, name='delete_view'), ] And my template <!doctype html> <html lang="en"> <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/css/bootstrap.min.css" integrity="sha384-TX8t27EcRE3e/ihU7zmQxVncDAy5uIKz4rEkgIXeMed4M0jlfIDPvg6uqKI2xXr2" crossorigin="anonymous"> <title>Tasks</title> </head> <body> … -
Django AttributeError 'CreateUserForm' object has no attribute 'username'
I am trying to create user registration page, to do so, I use default UserCreationForm. I want to register users through their phone numbers, so I changed this form like this: class CreateUserForm(UserCreationForm): restriction = RegexValidator(r'^[0-9]*$') username = forms.CharField(max_length=11, validators=[restriction]) class Meta: model = User fields = ['username', 'first_name', 'password1', 'password2'] There is part of registration view function: if form.is_valid(): #save form and redirect elif len(form.cleaned_data['password1']) < 8: messages.error(request, 'Password is too short') elif form.cleaned_data['username'].isnumeric() == False: messages.error(request, 'Enter valid phone number!') So if the form turns out to be invalid, it checks whether password or phone number is wrong but when it comes to checking phone, it returns "KeyError at /registration/" and "Exception Value: 'username'". If I change form.cleaned_data['username'] to form.username, it returns "Django AttributeError 'CreateUserForm' object has no attribute 'username'" I genuinely don't know what to do and why this error is even a thing. -
Django cannot render the template url?
I have 3 apps in django project, I created a new html file on dictionary app which is Refcode_Info.html. This page must render a simple form and linked a simple. When I click the button, form must show on screen. However when I click the button, I get 404 page and mixxed url, Likewise, I want to direct another url on this page, but seconda url already exits in this project and I have used on different stages on project but doesnt work on new html page(Refcode_Info.html). My new html may have a problems but my Accounts links is working on different stages. This is my Refcode_Info.html codes on below. <script> $(document).ready(function() { if ($(document).width() > 768) { $("#accordion_desktop").accordion({ header: '.header', collapsible: true, active: false, autoHeight: true, heightStyle: 'content', animate: 50 }); $("#desktop").show(); } else { $("#accordion_mobile").accordion({ header: '.header', collapsible: true, active: false, autoHeight: true, heightStyle: 'content', animate: 50 }); $("#mobile").show(); } $(window).resize(function() { if ($(document).width() > 768) { $("#accordion_desktop").accordion({ header: '.header', collapsible: true, active: false, autoHeight: true, heightStyle: 'content', animate: 50 }); $("#desktop").show(); $("#mobile").hide(); } else { $("#accordion_mobile").accordion({ header: '.header', collapsible: true, active: false, autoHeight: true, heightStyle: 'content', animate: 50 }); $("#mobile").show(); $("#desktop").hide(); } }); }); </script> <style> .ui-widget-content … -
What is the purpose of model Token in the admin section?
I am fairly new to the rest api. I am trying to use dj-rest-auth package with simple-jwt for auth handling. Everything works fine in my project. The registration/login etc. But in my django admin site there is a model registered Token which is every time empty. What is the purpose of this model Token? How tokens are managed with dj-rest-auth and simple jwt package ? settings.py installed_apps= [ .. 'rest_framework', 'rest_framework.authtoken', 'dj_rest_auth', 'django.contrib.sites', 'allauth', 'allauth.account', 'allauth.socialaccount', 'dj_rest_auth.registration', REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework_simplejwt.authentication.JWTAuthentication', ) } REST_USE_JWT = True SIMPLE_JWT = { 'ACCESS_TOKEN_LIFETIME': timedelta(minutes=5), 'REFRESH_TOKEN_LIFETIME': timedelta(days=7), } ACCOUNT_EMAIL_REQUIRED = True ACCOUNT_EMAIL_VERIFICATION = "mandatory" ACCOUNT_EMAIL_CONFIRMATION_EXPIRE_DAYS = 1 ACCOUNT_AUTHENTICATION_METHOD = "username" ACCOUNT_LOGIN_ATTEMPTS_LIMIT = None urls.py path('user/', include('dj_rest_auth.urls')), path('user/register/', include('dj_rest_auth.registration.urls')), path('confirm/email/', CustomVerifyEmailView.as_view(), name='account_email_verification_sent'), -
How can I extend expiry time of Knox-Token
I haven't changed the settings of Knox in my Django app. The default expiry time is 10hours, how can I change this that it won't expiry. -
Related Field got invalid lookup: icontains django
So I'm trying to make an search option where users can search via categories and name but only name worked, when i used icontains on category it just gave me an error but did not give me an error with name also categories just does not load in HTML. Categories are supposed to load in <select> tag but it is not working, searchall function handles the page I'm talking about and search.html is the page views.py from django.shortcuts import render, redirect from django.contrib.auth.forms import UserCreationForm, AuthenticationForm from django.contrib.auth.models import User from django.contrib.auth import login, logout, authenticate from django.db import IntegrityError from .models import Book, CartItem, OrderItem, Category from django.contrib.auth.decorators import login_required from .forms import BookForm from django.core.exceptions import ObjectDoesNotExist import random # Create your views here. removederror = '' def calculate(request): oof = CartItem.objects.filter(user=request.user) fianlprice = 0 for item in oof: fianlprice += item.book.price def signupuser(request): if request.user.is_authenticated: return render(request, 'main/alreadyloggedin.html') elif request.user != request.user.is_authenticated: if request.method == "GET": return render(request, 'main/signupuser.html', {'form':UserCreationForm()}) elif request.method == "POST": if request.POST['password1'] == request.POST['password2']: try: user = User.objects.create_user(request.POST['username'], password=request.POST['password1']) user.save() login(request, user) return render(request, 'main/UserCreated.html') except IntegrityError: return render(request, 'main/signupuser.html', {'form':UserCreationForm(), 'error':'That username has already been taken. Please choose a new username'}) else: … -
How to write unit test for child object?
I'm trying to write a test for my Recipe class. from django.contrib.auth.models import User class Recipe(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=100, null=True, blank=True) content = models.TextField() ingredientNumber = models.IntegerField(default=0) date_posted = models.DateTimeField(auto_now_add=True) What I have so far is this. from django.test import TestCase from .models import Recipe class BasicTest(TestCase): def test_recipe_fields(self): recipe = Recipe() recipe.title = "New recipy" recipe.content = "Cooking instructions" recipe.ingredientNumber = 4 recipe.save() record = Recipe.objects.get(pk=1) self.assertEqual(record, recipe) When I run this test, I get this error: NOT NULL constraint failed: recipes_recipe.user_id How can I create an User instance for this test? -
Dynamically creating groups and permissions in Django
Let's say I have an app on which a select number of users can create different and independent Blogs. Those users can choose to add "writers" to their blog, and specify custom permissions. I'd like for a blog admin to be able to add a user to a writers group for that specific blog, as well as choose their specific permissions such as can_add_post, can_edit_post, can_add_writers and so on. I couldn't find anything on this. I can't just statically create those permissions because of course they would be global and not blog-specific. Is there a way I can come up with a group writers_blog_1 and its relative set of permissions can_add_posts_blog_1, and so on, for each blog that is created on the site? -
'QueryDict' object is not callable................ django-python
Error [HTML code .html]views.py3 -
How show ForeignKey 'id' in admin?
I have model: class Offer(models.Model): offer_owner = models.ForeignKey('user.MentorProfile', on_delete=models.CASCADE) title = models.CharField(max_length=250) and second model in this same app class Contract(models.Model): offer = models.ForeignKey(Offer, on_delete=models.CASCADE) I registered this models in admin. Like this: @admin.register(Offer) class OfferAdmin(admin.ModelAdmin): list_display = ('id', 'offer_owner') search_fields = ('offer_owner__username', 'offer_owner__email') list_filter = ("created",) readonly_fields = ("created",) list_per_page = 10 @admin.register(Contract) class ContractAdmin(admin.ModelAdmin): list_display = ('id', 'offer',) !!!<--- Want show here OFFER ID (id from Offer model)!!! How can I show Offer id in ContractAdmin? -
Typeerror: userList.reverse() is not a function
I'm trying to build a chat app, When I click add new message button it opens a modal form, where I put the message number/name that I want to send to and a message inside a textbox. when I fill this up and hit send i get this error: Typeerror userList.reverse() is not a function and in the console i also get can't post error status 500 internal server error, i am unable to find the problem and solve it Plz, help me find the problem and solve it. Thank you. In the sidebar i also have a search input that searches the userList Here is the sidebar component where i'm getting this error. import React, { useState, useEffect } from 'react' import { createStyles, makeStyles, Theme, Button, TextField } from '@material-ui/core'; import CreateOutlinedIcon from '@material-ui/icons/CreateOutlined'; import SearchIcon from '@material-ui/icons/Search'; import Modal from '@material-ui/core/Modal'; import Backdrop from '@material-ui/core/Backdrop'; import Fade from '@material-ui/core/Fade'; import CloseIcon from '@material-ui/icons/Close'; import SendIcon from '@material-ui/icons/Send'; import './Sidebar.css' import SidebarChat from './SidebarChat/SidebarChat' import axios from 'axios' import useSWR, { trigger, mutate } from 'swr' import _ from "lodash" const Sidebar = () => { //style func material-ui const classes = useStyles() //all the states to handle …