Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 … -
how to keep checkbox checked during pagination in django
how to keep checkbox checked during pagination in django ??? I built an online store and had a problem when filtering products. When I select a brand, the products related to that brand are displayed to me, and if I go to the next page, it will still work without any problems. If I select two brands, the products related to these two brands will be displayed on the first page without any problems, but by going to the next page, only the products related to the second brand that I have selected will be displayed and the first brand check box will be checked Will be removed and only the second brand check box remains. How can I keep the status of the checkbox stable after going to the next page? (use djago-filter) my script : $(document).on('change','.filter-form',function(event){ event.preventDefault(); $.ajax({ type:'GET', url:'filter/', data : $(this).serialize(), dataType: 'json', success: function (data) { console.log("success"); $('#product-main').html(data['form']); }, error: function (data) { alert("error" + data); } }); }); my form : <form action="" class="filter-form"> <div class="d-flex justify-content-between mt-2"> <div class="form-check"> <label class="form-check-label"> {{filter.form.brand}} </label> </div> </div> </form> -
Django-celery task not firing after post-save signal for large image files (like > 10MB) but works for normal images
hey guys I am quite confused with what's happening with the code and doesn't seem to understand why large images are not getting processed with the celery task and the entire post object is not getting saved in the db while it works with normal images. This is the post-signal I have: @receiver(post_save, sender=PostImage) def save_image_after_processing(sender, instance, **kwargs): post_image = instance.image task_process_image_for_posts.delay(post_image.path) Sometimes it runs with large image files, most of the time it doesn't. Can anyone help with the issue? Thanks -
My models property filtering total sum and answer correct but gave me each row what i have db
Below def. given me correct answer, but when i added html total sum. written me in db how many rows i have, same as row result gave? def total_overtime(self): total = (Salary.objects .filter(currency='Tenge') .aggregate( total=Sum('overtime', field="overtime*overtime_hourly_rate") )['total']) return total -
I am not able to get a field in my Django ManyToMany Relation
I have a model called announcement in my Django Models, the way it works is that it has a message field which I can type the body of the message as well as the student_id which is the receiver of the message. I am using the many-to-many field on the student_id so that I am able to send the message to either some particular student and then filter the particular student message in on their frontend, but when I am trying the filter the particular student which I selected when sending the message, it doesn't display any information at all. models.py class Announcement_by_dean(models.Model): student_id = models.ManyToManyField(add_students_by_manager) message = models.TextField() sent_date = models.DateField(default=datetime.now(), blank=True) updated_date = models.DateField(auto_now=True, blank=True) def __str__(self): return "message sent on "+ str(self.sent_date) class add_students_by_manager(models.Model): manager_ID = models.ForeignKey(Manager_login_information, on_delete=models.CASCADE) student_ID = models.CharField(max_length=200) student_name = models.CharField(max_length=200) phone_number = models.CharField(max_length=200) address = models.CharField(max_length=200) dob = models.CharField(max_length=200) major = models.CharField(max_length=200) password = models.CharField(max_length=200) def __str__(self): return self.student_name views.py def dean_page(request): annoucement_list = Announcement_by_dean.objects.all().order_by('-id') return render(request, 'dean_page.html', context) dean_page.html <div class="tab-pane fade show" id="nav-announcement-list" role="tabpanel" aria-labelledby="nav-announcement-list-tab"> {% if annoucement_list %} {% for k in annoucement_list %} <div class="card container mt-4 mb-5"> <div class="card-body"> Messsage: {{k.message}}<br> Sent to: {{k.student_id.student_ID}}<br> </div> </div> {% endfor … -
Django Querysets adding additional information inside View
I'm currently working on a small django application for my school. I got two models involved in this problem: "category" and "device", which are connected in a one-to-many relationship category---<device(s) I added one page/template/view for the category overview, containing a large table with all the relevant information on every category created. Querying the categories like this: categories = Category.objects.filter(is_activ=True) And displaying them inside the template like this: {% for category in categories %} {{ category.title }} {{ category.otherField }} {% endfor %} is no Problem. The Issue: Now I need to add an extra field to the table containing the amount of devices in the category. Since the amount of devices is no field in my category model, but can rather be determined like this: amount_devices_in_c1 = Device.objects.filter(category=c1).count() it's not possible for me to access the amount in the template by just doing: {{ category.amount }} Solution? Since adding a field to the category model is not an option and makes the code even less agile, I am loooking for a way to join/merge the information to the categories Queryset. I guess it's a pretty basic question, but I think I am missing some basic knowledge on Querysets/Mege/Join. Thank you … -
Django chunked file upload continue after offline
I'm aware of django-chunked-upload but I'd like to understand how to receive and write file chunks with Django. From my Frontend (Dropzone) I'm getting following post data: {'dzuuid': ['42938e49-57cc-4cee-bf1d-9dd7a35dae29'], 'dzchunkindex': ['0'], 'dztotalfilesize': ['242129'], 'dzchunksize': ['1000000'], 'dztotalchunkcount': ['1'], 'dzchunkbyteoffset': ['0']} <MultiValueDict: {'file': [<TemporaryUploadedFile: MY_FILE.png (application/octet-stream)>]}> With a simple django view (code only for testing!) I can receive and write my chunks: class UploadView(View): def post(self, request, *args, **kwargs): # variables and post data file = request.FILES['file'] chunk_byte_offset = int(request.POST.get("dzchunkbyteoffset")) current_chunk = int(request.POST.get("dzchunkindex")) total_chunks = int(request.POST.get('dztotalchunkcount')) save_path = os.path.join(./media/, str(file)) #write chunks destination = open(save_path, 'a+b') for chunk in file.chunks(): destination.write(chunk) destination.close() # response if current_chunk + 1 == total_chunks: return HttpResponse(('Upload complete')) else: return HttpResponse(('Uploaded Chunk')) While this is working I'd like to implement the resumption of a paused or interrupted file upload. The idea is instead of just appending the chunks to a file, to seek the last offset and append it after. with open(save_path, 'a+b') as f: f.seek(chunk_byte_offset) f.write(file.stream.read()) Questions: f.seekthrows an error AttributeError: 'TemporaryUploadedFile' object has no attribute 'stream' what do I overlook here? What is the suggested way of knowing where to continue even after hours of downtime. My idea is either to write the history of … -
I am getting "This field is required." error on load of webpage when using the Django ModelForm
I made a model called Annoucement in my models.py file as well as the form for it in my forms.py file. I then made the simple create view for it in my my views.py and made it show on the frontend using the django-crispy-forms package but anytime i load the website, the border of the field appears red showing that there is an error. I have tried checking what the error could be but I am not getting any luck around it. models.py class Announcement_by_dean(models.Model): student_id = models.ManyToManyField(add_students_by_manager) message = models.TextField() sent_date = models.DateField(default=datetime.now(), blank=True) updated_date = models.DateField(auto_now=True, blank=True) def __str__(self): return "message sent on "+ str(self.sent_date) forms.py class Annoucement_form(ModelForm): class Meta: model = Announcement_by_dean fields = ['student_id', 'message'] views.py def dean_page(request): annoucement_list = Announcement_by_dean.objects.all() if request.method == 'POST': form = Annoucement_form(request.POST) if form.is_valid(): form.save() messages.success(request, _("Message Sent Successfully!!!")) return redirect('dean_page') else: messages.error(request, _("Message Not Sent, Something is Wrong!!!")) else: form = Annoucement_form() messages.error(request, _("Invalid Method!!!")) context = {"form":form, "annoucement_list":annoucement_list} return render(request, "dean_page.html", context) dean_page.html <!-- Send Announcement --> <div class="tab-pane fade show" id="nav-announcement" role="tabpanel" aria-labelledby="nav-announcement-tab"> <div class="container mt-4 p-3"> <form action="{% url 'dean_page' %}" method="POST" enctype="multipart/form-data"> {% csrf_token %} {{form|crispy}} <button type="submit" class="btn btn-success btn-sm">Submit</button> </form> </div> </div> -
Django, datatables doesn't render table in html template
I'm sending the data from the views function to the template as a table and trying to use datatables to turn the table into a more functional table, so I can order elements based on the different columns... The table by itself appears... But it's only html structured table, not dynamic table, where it could be ordered by the columns. I was following: https://datatables.net/manual/ So far I found advises: -- Check the integrity of the table (so it has head and body tags)- I have it --all tags must be closed - they are closed -- use the java function, like so: $(document).ready( function () { $('#table_id').DataTable(); } ); I have no idea what else could be wrong... I have to mention... I would like to avoid saving data to the database, just would like to take data from view and post it to the table in the template... That's why I choose datatables over django_tables2... Because it seems datatables have a way just render the tables from the data... My code: views.py: ... for Loop: ... data_list.append({'ref':ref[k], 'ref_num':ref_num[k], 'ref_pr':ref_pr[k]}) k=k+1 context={ data_list, } return render(request, 'objects.html', context=context) The page renders, so no faults in urls... html page: {% extends … -
Django union queries throwing database error.( ORDER BY not allowed in subqueries of compound statements.)
MY search bar is not working when I try to make union queries. My function looks like this def search(request): query=request.GET['query'] allPostsTitle= Post.objects.filter(title__icontains=query) allPostsAuthor= Post.objects.filter(author__icontains=query) allPostsContent =Post.objects.filter(content__icontains=query) allPosts= allPostsTitle.union(allPostsContent, allPostsAuthor) if allPosts.count()==0: messages.warning(request, "No search results found. Please refine your query.") params={'allPosts': allPosts, 'query': query} return render(request, 'home/search.html', params) Please help me out of this I am getting this error DatabaseError at /search ORDER BY not allowed in subqueries of compound statements. Request Method: GET Request URL: http://127.0.0.1:8000/search?query=continue Django Version: 3.1.5 Exception Type: DatabaseError Exception Value: ORDER BY not allowed in subqueries of compound statements. Exception Location:virtualenvs/myvirtualenv/lib/python3.6/site- packages/django/db/models/sql/compiler.py, line 444, in get_combinator_sql Python Executable: /usr/local/bin/uwsgi Python Version: 3.6.9 -
favicon icons not found , djabgo website with bootstrap at front , its a simple website
favicon icons not found , djabgo website with bootstrap at front , its a simple website . it was working a few minuts ago i tried chanding the whole boot strap code . the log i am getting when the django server is runing and i use the users profile: Not Found: /favicon.ico [06/Feb/2021 08:53:13] "GET /favicon.ico HTTP/1.1" 404 4502 Session data corrupted this is were the bootstrap static is coming though in the page: {% load static %} <!DOCTYPE html> <html> <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://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous"> <link rel="stylesheet" type="text/css" href="{% static 'blog/main.css' %}"> -
"Database is Locked" error while deploying django webapp on azure
I am trying to deploy an django webapp on azure, it shows on web totally functional, except one thing, It doesnt let me create superuser on webssh, Every time I try to run python manage.py createsuperuser and after giving all credentials it throws an error django.db.utils.OperationalError: database is locked I don't understand what to do I am using default database of django. -
Django template language logical issue
In this code line no. 4 if "user.number" is greater than "i", (add:'4') this will done. but if "i" is greater than "user.number", (add:'-4) this will done ...but i do not understand why ..? because if (i < users.number) is False then (i > users.number) this should not run please explain {% for i in users.paginator.page_range %} {% if users.number == i %} <li class="page-item active"><a class="page-link">{{ i }}</a></li> {% elif i < users.number|add:'4' and i > users.number|add:'-4' %} <li class="page-item"><a class="page-link" href="?page={{ i }}">{{ i }}</a></li> {% endif %} {% endfor %} -
Django3 : how to add an attribute from a foreign key filed
I have to migrate some code from python2.7/django1.11 to python3.7/django3.x I get an error and could not find why. The error is that i can access the foreign key value nom_ingredient. "Instance of 'ForeignKey' has no 'nom_ingredient' member". The problem is the same with mode_operatoire field class Ingredient(models.Model): id_ingredient = models.AutoField(primary_key=True) nom_ingredient = models.CharField(max_length=100) def __str__(self): return self.nom_ingredient class Meta: managed = True db_table = 'ingredient' class Recette(models.Model): id_recette = models.AutoField(primary_key=True) nom_recette = models.CharField(max_length=100, blank=True) mode_operatoire = models.CharField(max_length=1000, blank=True) class ComposerRecette(models.Model): id = models.AutoField(primary_key=True) id_ingredient = models.ForeignKey('Ingredient', db_column='id_ingredient', on_delete=models.DO_NOTHING) quantite_ing = models.FloatField() def mode_operatoire(self): return self.id_recette.mode_operatoire def __str__(self): return self.id_ingredient.nom_ingredient -
How to download a database from the postgresql in the format of zip with Filestore by using python(Django)
I am trying to implement a django project, in that project there is a postgresql database with filestore. I need to download the database along with filestore in the ZIP format and it can be restore to database as well. Thanks in advance -
Remove from cart button not appearing - django template language
So it is supposed to show remove from cart when user has that item in their cart and add to cart when they don't, I am trying to use django template language for this but remove from cart button is not appearing, home function handles the page i am talking about, It passes all the variables to home.html. home.html <h1>Here are products</h1> <h1>{{ error }}</h1> <h1>Your cart currently costs ${{ price }}</h1> {% for book in books %} <h3>{{ book.name }}</h3> <img src= "/media/{{ book.image }}" alt=""> <p>{{ book.description }}</p> {% if book in cart %} <form method="POST" action="/removefromcartforhome/"> {% csrf_token %} <button type="submit" name="removeid" value="{{ book.id }}">remove item from cart</button> </form> {% else %} <form method="POST" action="/addtocartforhome/"> {% csrf_token %} <button type="submit" name="bookid" value="{{ book.id }}">Add to cart</button> </form> {% endif %} {% endfor %} 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 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 … -
Exception in thread django-main-thread django
Whenever running the server the following exception is poping up. Exception in thread django-main-thread: Following are the respective Traceback. Traceback (most recent call last): File "C:\Users\sarathmahe024\AppData\Local\Programs\Python\Python39\lib\threading.py", line 954, in _bootstrap_inner self.run() File "C:\Users\sarathmahe024\AppData\Local\Programs\Python\Python39\lib\threading.py", line 892, in run self._target(*self._args, **self._kwargs) File "C:\Users\sarathmahe024\Downloads\website\venv\lib\site-packages\django\utils\autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "C:\Users\sarathmahe024\Downloads\website\venv\lib\site-packages\django\core\management\commands\runserver.py", line 118, in inner_run self.check(display_num_errors=True) File "C:\Users\sarathmahe024\Downloads\website\venv\lib\site-packages\django\core\management\base.py", line 442, in check raise SystemCheckError(msg) django.core.management.base.SystemCheckError: SystemCheckError: System check identified some issues: ERRORS: web.Profile.image: (fields.E210) Cannot use ImageField because Pillow is not installed. HINT: Get Pillow at https://pypi.org/project/Pillow/ or run command "python -m pip install Pillow". System check identified 1 issue (0 silenced). I had already installed the pillow but its showing error in importing ImageField. Please let me know if you have any idea regarding this. Thanking you in advance.