Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: Filter queryset by property of Element
I have two models, Chat and DeletedChat. Now i want to get all chats of a user, removing those which from_date-fields, in DeletedChat, are bigger then the last_updated ones of the chat itself. How do i do that? class Chat(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) last_updated = models.DateTimeField(auto_now=True) class DeletedChat(models.Model): chat = models.ForeignKey(Chat, on_delete=models.CASCADE) from_date = models.DateTimeField(default=timezone.now) And in my views.py I tried: chat_ids = request.user.deletedchat_set.exclude(from_date__lt='chat__last_updated').values_list('chat', flat=True) which gives me the following error: ['“chat__message__set__last” value has an invalid format. It must be in YYYY-MM-DD HH:MM[:ss[.uuuuuu]][TZ] format.'] Thanks for your Help! -
Why does field.errors display duplicate error messages from clean() method in Django form?
Whether I use clean() or clean_initial_ph() I get duplicate error messages. Also if I iterate over form fields: {% for field in form %} {{ field|as_crispy_field }} {% if form.errors %} {% for error in field.errors %} <div class="alert alert-danger"> <strong>{{ error|escape }}</strong> </div> {% endfor %} {% endif%} {% endfor %} or list the fields and errors manually: ... {{ form.initial_ph|as_crispy_field }} {{ form.initial_ph.errors }} ... I still get the duplicate error messages (albeit different styling for the larger one). I followed the validation guidelines. For example in clean_initial_ph() my validation looks like this: def clean_initial_ph(self): initial_ph = self.cleaned_data['initial_ph'] if initial_ph: if initial_ph < 0: raise forms.ValidationError(_("PH must be above 0."), code = 'negative_intial_ph') return initial_ph I have another validation on some time fields in clean() which does not display duplicate error messages: # Assuming clean_initial_ph is commented out def clean(self): cleaned_data = super().clean() pump_time = cleaned_data.get("pump_time") disposal_time = cleaned_data.get("disposal_time") incorptime = cleaned_data.get("incorptime") initial_ph = cleaned_data.get("initial_ph") disposal_ph = cleaned_data.get("disposal_ph") if pump_time and disposal_time: # DOES NOT DISPLAY DUPLICATE ERROR MESSAGES if pump_time >= disposal_time: self.add_error('pump_time','Pump time must be prior to disposal time.') self.add_error('disposal_time','Disposal time must be after to pump time.') if incorptime: if incorptime <= disposal_time: self.add_error('incorptime','Incorp time must … -
Python multiprocessing pool.close and pool.join TypeError: 'NoneType' object is not callable
I'm getting the error TypeError: 'NoneType' object is not callable in self.pool.join called by the __del__ method of a module containing the following code. In particular, the error occurs when running database migrations or the test suite in a Django application. I've tried implementing import atexit and registering the methods inside __init__ via: atexit.register(self.pool.close) atexit.register(self.pool.join) ...but this hasn't worked. Why is this TypeError occuring in the code below's __del__ method, and how can I avoid it? import datetime import json import mimetypes from multiprocessing.pool import ThreadPool import os import re import tempfile # python 2 and python 3 compatibility library import six from six.moves.urllib.parse import quote from paapi5_python_sdk.configuration import Configuration import paapi5_python_sdk from paapi5_python_sdk import rest from paapi5_python_sdk.auth.sig_v4 import AWSV4Auth class ApiClient(object): PRIMITIVE_TYPES = (float, bool, bytes, six.text_type) + six.integer_types NATIVE_TYPES_MAPPING = { 'int': int, 'long': int if six.PY3 else long, # noqa: F821 'float': float, 'str': str, 'bool': bool, 'date': datetime.date, 'datetime': datetime.datetime, 'object': object, } def __init__(self, access_key, secret_key, host, region, configuration=None, header_name=None, header_value=None, cookie=None): if configuration is None: configuration = Configuration() self.configuration = configuration self.pool = ThreadPool() self.rest_client = rest.RESTClientObject(configuration) self.default_headers = {} if header_name is not None: self.default_headers[header_name] = header_value self.cookie = cookie # Set default … -
i am getting one of my program accessed by every IDE of python
i want to work with visual studio for django. but whenever i try to open a terminal and start any command it always run one of my program that i created on spyder. even in cmd prompt i am getting same thing. how can i disconnect that program to run. i am not able to work on any IDE of python . below id the input command i used in that program to have input from uses. mkvirtualenv denvx Enter a sentence you like: -
Django ORM: filter by multiple properties of related object
I have the following objects: class Image: user models.ForeignKey(User) corrupted = models.BooleanField() final = models.BooleanField() class ImageRevision: image = models.ForeignKey(Image, related_name="revisions") corrupted = models.BooleanField() final = models.BooleanField() In English: images can have many revisions images might become corrupted, as well as revisions only one object will be final, i.e. either the image or one of its revisions (an image without revision counts as final) I would like to get all images from a user that are corrupted. An image counts as corrupted if any of the following is true: the image itself is corrupted and final the revision marked as final is corrupted In the following cases, the image does not count as corrupted: the image is final and is not corrupted the image has a final revision that is not corrupted Can this be queried using Django ORM? -
Django Template - Cannot iterate throught this list and get menu item
i have one project andromeda where is 2 apps. 1 is blog and seccond one is blogmenu but when I want to get information from the blog app there is no problem and i can get all information. but when I want to get a menu item from blogmenu I'm getting now error but there is empty navigation bar. blogmenu urls.py from django.contrib import admin from django.urls import path,include from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), path('', include('blog.urls')), path('', include('blogmenu.urls')), ] if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) blogmenu views.py from django.shortcuts import render def Blog_Menu(request): Menu_items = Menu.objects.all() template_name = 'front/index.html' return render(request, template_name, {"Menu_items":Menu_items}) blogmenu models.py from django.db import models class Menu(models.Model): Menu_name = models.CharField(max_length=100,blank=True) Menu_slug = models.SlugField(name="სლაგი",blank=True) Menu_image = models.ImageField(upload_to="menuimages") Menu_url = models.CharField(name="url",max_length=100,blank=True,null=True) class Meta: verbose_name = "მენიუ" def __str__(self): return self.Menu_name sample html template code {% for menu in Menu_items %} <li class="main-menu-item"> <a href="#" class="main-menu-item-link">just text</a> </li> {% endfor %} -
How to create registration page for users on own website?
I am currently working on a GST portal for software project. I am learning and implementing Django for backend. Currently, I know that the users in django are for the admin page. How to I create my own separate users for my website. To be specific, I have 2 types of users- Taxpayer and tax-official who can register on my website. How do I do that? Desperate help needed. -
Django :Aafter submitiing form, browse button disappear
I am working on pdf data extraction project.there i am browse pdf file using django-forms filefield and then displaying extracted data on same page.everything works fine but the problem is after submitting browsed file, extracted data appear on same page but browse button get disappear. forms.py class browse(forms.Form): file = forms.FileField() views.py def index(request): if request.method == 'POST': user = browse(request.POST, request.FILES) if user.is_valid(): handle_uploaded_file(request.FILES['file'])#store file in upload folder path = "pdfextractor/static/upload/"+ str(request.FILES['file'])#path of selected file result = extract_data(path)#extract data from file context = {'result':result} return (render(request,'pdfextractor/index.html',context)) else: user = browse() return render(request,"pdfextractor/index.html",{'form':user}) index.html <body> <form method="POST" class="post-form" enctype="multipart/form-data"> {% csrf_token %} {{ form.as_p }} <input type="Submit" name="submit" value="Submit"/> </form> {% for key, value in result.items %} <h1>{{key}} : {{value}}</h1> {% endfor %} </body> output here you can see browse button disappear.now here i want that browse button so that user can browse new file directly from here -
Best way to handle a centralized MySQL database that connect multiple microservices (NoSQL/MySQL)
I have a core service that connects to many other microservices. This core service have several tablse that can have an "FK" with these microservices, and they can be either SQL or NoSQL, example: CREATE TABLE `users_usergameinfo` ( `id` int(11) NOT NULL AUTO_INCREMENT, `nameOnGame` varchar(255) COLLATE utf8mb4_bin NOT NULL, `idOnGame` int(11), PRIMARY KEY (`id`), ) ENGINE=InnoDB AUTO_INCREMENT=25103 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin; The idOnGame field point to the microservice database, and, as far it was connected to SQL databases, was ok to use an integer value. We also have other tables that do JOIN between each other. Now we will start to connect with NoSQL (mongodb) databases, and we are trying to figure out how to handle the ObjectID without creating new fields. Converting it to VarChar(32) or Binary(16), what is the best (and optimized) way to do this? -
Django NoReverseMatch at /classes/1/1 Error
I am linking trying to retrieve the URL to the Html page using {% for lesson in playlist.lesson_set.all %} <a href="{% url 'lessons' classes.id list.id lesson.id %}">World1</a> {% endfor %} but when I am running the webpage I am getting the error NoReverseMatch at /classes/1/1 Reverse for 'lessons' with arguments '('', '', 1)' not found. 1 pattern(s) tried: ['classes/(?P<classes_id>[0-9]+)/(?P<list_id>[0-9]+)/(?P<lesson_id>[0-9]+)$'] From where this error?? How to solve this Error?? MY CODE: Views.py from django.shortcuts import render, get_object_or_404 from .models import Class, Material, Lesson, Playlist def home(request): Classes= Class.objects return render(request, 'classes/index.html', {"class":Classes}) def classes(request): Classes= Class.objects return render(request, 'classes/Classes.html', {"class":Classes}) def materials(request, classes_id): theclass= get_object_or_404(Class, pk=classes_id) Materials = Material.objects.all() context = { 'classes': theclass, 'material': Materials } return render(request, 'classes/Materials.html', context) def playlist(request, classes_id, list_id): theMaterial=get_object_or_404(Material, pk=list_id) classid=get_object_or_404(Class, pk=classes_id) theList=Playlist.objects.all() context={ 'Material': theMaterial, 'playlist':theList, 'class':classid } return render(request, 'classes/list.html', context) def lesson(request, classes_id, list_id, lesson_id): thePlaylist=get_object_or_404(Playlist, pk=lesson_id) theMaterial=get_object_or_404(Material, pk=list_id) theClass=get_object_or_404(Class, pk=classes_id) lesson=Lesson.objects.all() context={ 'material':theMaterial, 'list':thePlaylist, 'class':theClass, 'lesson':lesson } return render(request, 'classes/lesson.html', context) URLs.py: from django.contrib import admin from django.urls import path import classrooms.views import users.views from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), path('', classrooms.views.home), path('classes', classrooms.views.classes), path('classes/<int:classes_id>', classrooms.views.materials, name="material"), path('signup', users.views.signup, name="signup"), path('login', users.views.login, name="login"), … -
So i'm using Django and React and in the build/static folder django wont run json data or display the images on the browser
the images and json data does not appear on browser this is my django setting.py this here is django on port http://127.0.0.1:8000/ but everything works fine in react Please i dont know what i am doing wrong. please help -
Django - Confirmation popup
I'm trying to write a code for deleting an item. But before deleting it i want to popup a message to the user like "are you sure you want to delete?". I want to delete the item by its ID. I wrote this code, but i pretty sure its not how it should be. Please guide me what to do. HTML FILE <div id="film_box"> {% if films %} {% for film in films %} <div class="card" style="width: 18rem;"> {% if film.image%} <img src="{{ film.image.url }}" class="card-img-top" alt="..."> {% endif %} <div class="card-body"> <h5 class="card-title">{{ film.title}}</h5> <p class="card-text">{{ film.category_name }}</p> <p class="card-text">{{ film.country_name }}</p> <p class="card-text">{{ film.director }}</p> <p class="card-text">{{ film.release_date }}</p> </div> <div class="card-body"> {% if request.user.is_superuser %} <ul style="list-style:none;"> <li><a href="{% url 'update_director' film.director_id %}" class="card-link">Modify the director</a> </li> <li><a href="{% url 'update_film' film.id %}" class="card-link">Modify the film</a></li> <li><button onclick="document.getElementById('btn_delete').style.display='block'" name="{{ film.id }}" class="btn btn-danger">DELETE</button></li> </ul> {% endif %} <!--popup message--> <div id="btn_delete" class="modal"> <span onclick="document.getElementById('btn_delete').style.display='none'" class="close" title="Close Modal">×</span> <form class="modal-content" action="/delete/{{film.id}}"> <div class="container"> <h1>Delete film</h1> <p>Are you sure you want to delete the film?</p> <div class="clearfix"> <button type="button" onclick="document.getElementById('btn_delete').style.display='none'" class="cancelbtn">Cancel</button> <button href="{% url 'delete_film' film.id %}" onclick="document.getElementById('btn_delete').style.display='none'" class="deletebtn">Delete</button> </div> </div> </form> </div> {% endfor%} {% endif %} JAVASCRIPT … -
How to make search more accurate in Django?
so on the way of learning process, I am making my first side-project on django. I want to make my search more accurate, for example: when post body contains text with 3 words "I love stackoverflow" and someone searches for "I stackoverflow" (without word LOVE), result is not shown on the search page. What could be the best approach in this case to get the result, even if the post body does not contain words in that order as a search query? views.py def search(request): posts = Post.objects.all().order_by('title') query = request.GET.get('q') print(query) if query: posts = Post.objects.filter( Q(title__icontains=query)| Q(body__icontains=query) ) context = { "posts": posts, } return render(request, "search.html", context) -
How do I create a Friend model with accept field?
I want to create a social networking app, where we can add friends and see their posts. In this I want to create a friend model like this: class Friend(models.Model): from = models.ForeignKey(User) to = models.ForeignKey(User) accepted = models.NullBooleanField(null=True) class Meta: unique_together = ('from', 'to') I am just confused about reverse relation between from and to. For example, if A is friend of B, then B is also friend of A. I am having problem in getting all friends of a user, because the user can exist in from as well as in to. -
How to only allow logged in users connect to websocket in Django Channels?
I have a chat app and I want only users that are logged in to be able to connect to the websocket. How can you achieve that? Is there something like the @login_required decorator for Django channels? I know from the documentation that that's how you can access the user: class ChatConsumer(WebsocketConsumer): def connect(self, event): self.user = self.scope["user"] But how do you deny the connection if the user isn't logged in? -
Chart.js first row bar not showing in django
my chart work properly but as first starting point 1st bar not showing here is the code: $(function () { var $populationChart = $("#population-chart"); var res = ['20','20','30'] $.ajax({ url: $populationChart.data("url"), success: function (data) { var ctx = $populationChart[0].getContext("2d"); new Chart(ctx, { type: 'bar', data: { labels: data.label, datasets: [{ label: 'Price', backgroundColor: 'blue', data: res, }] }, options: { responsive: true, legend: { position: 'top', }, title: { display: true, text: 'Rating Analysis' } } }); } }); }); Screenshot: Is there any way to show minimum value first bar properly? -
Django __init__() takes 1 positional argument but 2 were given (added .as_view())
After i run the server and go to the .../article/ url it return an error File "/home/anhhao/Documents/Data/LuanVan/realestate/project/user/views.py", line 21, in get return Response(serializer.data) TypeError: __init__() takes 1 positional argument but 2 were given Attention line 21: in get return Response(serializer.data) models.py class User(models.Model): name = models.CharField(max_length=100) address = models.CharField(max_length=300) def __str__(self): return self.name views.py class UserInfo(APIView): def get(self, request, format=None): user = User.objects.all() serializer = UserSerializer(user, many=True) return Response(serializer.data) user/urls.py urlpatterns = [ path('user/', UserInfo.as_view(), name='list_user') ] urls.py urlpatterns = [ path('admin/', admin.site.urls), path('api/', include('user.urls')) ] urlpatterns = format_suffix_patterns(urlpatterns) I had added .as_view() Please help me -
how to save python Dynamic code to database with proper indentation(formatted style)
Consider Following code result = [] for i in range(1,11): if i%2 == 0: result.append("Even") else: result.append("Odd") print(result) I want to save it in (Sqlite3)database as it is and fetch it and display on web pages using html and css. but when i am saving it into sqlite all indentation not saving properly I have Tried pygements still no success Any other way to save and retrieve python code with formatted python code -
The best way for doing something in background Django
I need my django app processing some functions in background periodically. What is the best way for making such functions? And how can I call some functions when server starts? For example, functions of pre-init. -
Check whether value in dict with for loop in Django's template
I have the following data in my views. months = [1,2,3,4,5,6,7,8,9,10,11,12] mydict = {3:'a',4:'b'} The key means month,if this month exists value,then render the value,else leave blank. Here's my template. {% for j in months %} {% if mydict.j %} <th class="align-middle">{{ mydict.j }}</th> {% else %} <th class="align-middle"></th> {% endif %} {% endfor %} But the result always is blank. I can access the value by mydict.3,but i can't get the value by mydict.j with a forloop. -
in django using foreign key, if there is only one row(data) then it is possible to retrieve data but i am not able to fetch multiple row(data)
def yourtrip(request): cstid = request.session['uid'] a = Cabbooking.objects.all().filter(customerID=cstid) counta=a.count() # cid = a[0].cabID # cd = Cabdriver.objects.all().filter(cabID=cid) # did = cd[0].driverID arrays=[] for i in range(counta): cid = a[i].cabID did = Cabdriver.objects.all().filter(cabID=cid) dids = did[0].driverID arrays.append(dids) for x in arrays: print(x) return render(request, "yourtrip.html",{"a":a}) here cabboking is a table from where i retrieve appropriate customer id. here #(commented) code is for single row(data) fetch. i used loop for multiple data fething but its not working -
Django queryset filtering with Taggit app
I am using Django 2.2. I am using the taggit app to provide tagging functionality. However, I also want to use tagging to create functionality for retrieving 'related' items. I have an object Foo which can have one or more tags associated with it. I want to be able to retrieve all Foo objects that have a specified tag. This is the code I have so far: from djando.db import models from taggit.managers import TaggableManager class FooManager(models.Manager) def get_related_foos(self, tag): qs = super(FooManager,self).get_queryset().filter(tag__name) class Foo(models.Model): title = models.CharField(max_length=32) tags = TaggableManager() objects = FooManager() My question is, how do I implement the function get_related_foos ? -
Django: How to exclude a View from session creation?
My Django Project heavily relies on sessions, and the Framework does a very good job with this. It manages Session Cookies, the Session Database and so on, mostly done through the SessionMiddleware. But there a some Views that explicitly do not require a session. And those Views often appear as an entry to the page. Can I exclude these Views from the SessionMiddleware creating new sessions? If a user visits such a View and leaves, there is no need for setting a Cookie or creating a database record in the sessions table. -
Cannot view the image uploaded on the admin panel
Picture gets uploaded on the django admin panel but when i click on the image on the panel it shows the page not found error. forms.py class ApproveImgForm(forms.Form): class Meta: model = ApprovImg fields = "__all__" urls.py path('w_p.html', views.WProduct_list, name='WProduct_list'), views.py def WProduct_list(request, category_slug=None): category = None categories = Category.objects.all() wproducts = Product.objects.filter() if category_slug: category = get_object_or_404(Category, slug=category_slug) wproducts = Product.objects.filter() if(request.method=='POST'): form = ApproveImgForm(request.POST) f = form.data['fileToUpload'] ph = ApprovImg(photo=f) ph.save() context = { 'category': category, 'categories': categories, 'wproducts': wproducts, } return render(request, 'shop/w_p.html', context) models.py class ApprovImg(models.Model): photo=models.ImageField(upload_to='products/%Y/%m/%d') def __str__(self): return str(self.photo) Can someone please help? -
The system cannot find the path specified: 'app_pickfeel/images/
I'm trying to load a random image from a directory. I get this error when I run the code: The system cannot find the path specified: 'app_pickfeel/images/' random_image.py import os import random from django import template from django.conf import settings # module-level variable register = template.Library() @register.simple_tag def random_image(image_dir): try: valid_extensions = settings.RANDOM_IMAGE_EXTENSIONS except AttributeError: valid_extensions = ['.jpg', '.jpeg', '.png', '.gif', ] if image_dir: rel_dir = image_dir else: rel_dir = settings.RANDOM_IMAGE_DIR rand_dir = os.path.join(settings.MEDIA_ROOT, rel_dir) files = [f for f in os.listdir(rand_dir) if os.path.splitext(f)[1] in valid_extensions] return os.path.join(rel_dir, random.choice(files)) pickfeel.html snippet <img src="{{ MEDIA_URL }}{% random_image "app_pickfeel/images/" %}"> Location of images are in the following directory: 'PickFeel/app_pickfeel/images/' images directory