Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Why are @property model definitions visible in list_display but not field_sets for Django Admin?
Why are @property definitions visible in list_display but not field_sets for Django Admin? Eg. in the example below my_prop displays perfectly in the admin as a list_display field but not as a field in a field_set models.py: class MyModel (models.Model): // code @property my_prop(self): // code admin.py: @admin.register(MyModel): class MyModelAdmin(AdminModel): list_display=('my_prop',) fieldsets = ( ('Summary',{ 'fields':('myprop',) })) -
Django rest framework: custom pagination next/previous links
In the backend as the DEFAULT_PAGINATION_CLASS I am using the built-in PageNumberPagination. Due to the reason that I use vue.js with fetch, I don't need to pass the whole url like provided by django-rest-framework: "count": 5, "next": "http://127.0.0.1:8000/api/something/?page=2", "previous": null but only the part after the base url, e.g.: /api/something/?page=2 or just the page number, so I could build my own endpoint e.g.: if (!pageNumber) { let endpoint = "/api/something/" } else { let endpoint = "/api/something/" + "?page=" + pageNumber; } What is the right way to do pagination with django and a JavaScript framework like vue using bootstraps pagination component? -
How to make the logic of the social media feed efficient?
I want to do something similar to Twitter in which the last posts of the people you follow in a feed come out. And this posts appear from django.db import models from django.contrib.auth.models import User class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) bio = models.TextField(max_length=300, blank=True) modified = models.DateTimeField(auto_now=True) class Post(models.Model): user = models.ForeignKey(User,related_name="posts", on_delete=models.CASCADE) content = models.TextField(max_length=300) created = models.DateTimeField(auto_now=True) class Follow(models.Model): follower = models.ForeignKey(User, related_name="following", on_delete=models.CASCADE) following = models.ForeignKey(User, related_name="followers", on_delete=models.CASCADE) def unicode(self): return "{} follows {}".format(self.follower, self.following) This are my relationships. I'm looking for a filter that would be efficient when handling large amounts of data. What would I need to do to get the posts from my followers, and then sorting them by most recent? -
When we should use db_index=True in Django?
When we should define db_index=True on model fields? I'm trying to optimize the application & wanted to learn more about db_index in which conditions we should use it? The documentation says that using db_index=True on model fields is to faster the lookups with slightly disadvantages with storage and memory. Should we use db_index=True only on those fields which has unique values like the primary field id? what happens if we enabled indexing for those fields which are not unique and contains repetitive data. -
Django Channels CustomAuthentication close_old_connections SynchronousOnlyOperation exception
I tried to implement the CustomAuthentication from the Django Channels documentation but i'm getting a SynchronousOnlyOperation exception every time i try to establish a websocket connection. What am i missing? I tried to use database_sync_to_async from channels.db but then i'm stuck with a coroutine object as a return value even if i'm using await. Maybe someone has an idea what i'm doing wrong? Package Versions: Python 3.6.9 Django 3.0.2 ASGI/Channels 2.4.0 Daphne 2.4.1 asgiref 3.2.3 channels-redis 2.4.1 settings.py [...] ASGI_APPLICATION = 'backend.routing.application' CHANNEL_LAYERS = { 'default': { 'BACKEND': 'channels_redis.core.RedisChannelLayer', 'CONFIG': { 'hosts': [('127.0.0.1', 6379)] }, }, } [...] routing.py (application) from channels.routing import ProtocolTypeRouter, URLRouter import backend.api.routing as route from backend.api.auth import TicketAuthMiddleware application = ProtocolTypeRouter({ 'websocket': TicketAuthMiddleware( URLRouter( route.websocket_urlpatterns ) ) }) routing.py (url) from django.urls import re_path from backend.api.consumers import OwnConsumer websocket_urlpatterns = [ re_path(r'<url>', OwnConsumer) ] consumers.py from channels.generic.websocket import WebsocketConsumer import json class OwnConsumer(WebsocketConsumer): def connect(self): self.accept() def disconnect(self, close_code): print("disconnected", close_code) auth.py from django.db import close_old_connections class TicketAuthMiddleware: def __init__(self, inner): self.inner = inner def __call__(self, scope): close_old_connections() # <--- raising SynchronousOnlyOperation exception return self.inner(dict(scope)) -
How to make model objects uneditable after first submission by users
I have a profile model all set up. I have also been able to render the data to the template, however, this is currently editable by logged in users. My plan, however, is to give users one-off access to fill their data themselves, and once they submit it, such data can not be edited by them except user with is_staff or superadmin privileges, even though they are going to see their data in their profile view. Is this possible? If yes, what strategy and/or example can I follow as I have no idea whatsoever on how to go about this. -
AttributeError: 'Overview' object has no attribute '__qualname__'
I am updating Django from 1.11.27 to 2.2.9 - python2.7 to python3.7 - made all the changes, but when I start server I have this error. AttributeError: 'Overview' object has no attribute '__qualname__' Traceback (most recent call last): File "/Users/user/Sites/project-folder/venv/lib/python3.7/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/Users/user/Sites/project-folder/venv/lib/python3.7/site-packages/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "/Users/user/Sites/project-folder/venv/lib/python3.7/site-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/usr/local/Cellar/python/3.7.4/Frameworks/Python.framework/Versions/3.7/lib/python3.7/contextlib.py", line 74, in inner return func(*args, **kwds) File "/Users/user/Sites/project-folder/venv/lib/python3.7/site-packages/django/contrib/admin/sites.py", line 241, in wrapper return self.admin_view(view, cacheable)(*args, **kwargs) File "/Users/user/Sites/project-folder/venv/lib/python3.7/site-packages/django/utils/decorators.py", line 142, in _wrapped_view response = view_func(request, *args, **kwargs) File "/Users/user/Sites/project-folder/venv/lib/python3.7/site-packages/django/views/decorators/cache.py", line 44, in _wrapped_view_func response = view_func(request, *args, **kwargs) File "/Users/user/Sites/project-folder/venv/lib/python3.7/site-packages/django/contrib/admin/sites.py", line 213, in inner if request.path == reverse('admin:logout', current_app=self.name): File "/Users/user/Sites/project-folder/venv/lib/python3.7/site-packages/django/urls/base.py", line 58, in reverse app_list = resolver.app_dict[ns] File "/Users/user/Sites/project-folder/venv/lib/python3.7/site-packages/django/urls/resolvers.py", line 513, in app_dict self._populate() File "/Users/user/Sites/project-folder/venv/lib/python3.7/site-packages/django/urls/resolvers.py", line 464, in _populate url_pattern._populate() File "/Users/user/Sites/project-folder/venv/lib/python3.7/site-packages/django/urls/resolvers.py", line 464, in _populate url_pattern._populate() File "/Users/user/Sites/project-folder/venv/lib/python3.7/site-packages/django/urls/resolvers.py", line 452, in _populate self._callback_strs.add(url_pattern.lookup_str) File "/Users/user/Sites/project-folder/venv/lib/python3.7/site-packages/django/utils/functional.py", line 80, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/Users/user/Sites/project-folder/venv/lib/python3.7/site-packages/django/urls/resolvers.py", line 362, in lookup_str return callback.__module__ + "." + callback.__qualname__ AttributeError: 'Overview' object has no attribute '__qualname__' -
why many to many field relationship menu are not showing the proper fields?
recently i am converting my project into DRF and the serializer.py is following: from rest_framework import serializers from .models import Menu,MenuCategory,MenuItem class MenuItemSerializer(serializers.ModelSerializer): class Meta: model = Menu fields = ['name', 'additional_text', 'order'] class MenuCategorySerializer(serializers.ModelSerializer): menuitem = serializers.StringRelatedField(many=True, read_only=True) class Meta: model = MenuCategory fields = ['order', 'name', 'description','menuitem'] def create(self, MenuCategory, MenuItem,validated_data): menucategory=MenuCategory.objects.create(**validated_data) item_data = validated_data.pop('menuitem') for it_data in item_data: MenuItem.objects.create(menucategory=menucategory, **item_data) return menucategory class MenuSerializer(serializers.ModelSerializer): menucategory = serializers.StringRelatedField(many=True, read_only=True) class Meta: model = Menu fields = ['name', 'additional_text', 'order','menucategory'] def create(self,MenuCategory, Menu, validated_data): category_data = validated_data.pop('menucategory') menu= Menu.objects.create(**validated_data) for cat_data in category_data: MenuCategory.objects.create(menu=menu, **category_data) return menu When i browse http://localhost:8000/api/, it shows: [ { "name": "Breakfast", "additional_text": "Served between 8:00am and11:00am", "order": 1, "menucategory": [ "MenuCategory object (3)", "MenuCategory object (4)" ] }, { "name": "Lunch", "additional_text": "Served between 12:00pm and 3:00pm", "order": 2, "menucategory": [ "MenuCategory object (1)", "MenuCategory object (5)", "MenuCategory object (7)" ] }, { "name": "Dinner", "additional_text": "Served between 6:00pm and 10:00pm", "order": 3, "menucategory": [ "MenuCategory object (2)", "MenuCategory object (6)", "MenuCategory object (8)" ] }, { "name": "Drinks", "additional_text": "Happy hour 3:00pm to 6:00 pm", "order": 4, "menucategory": [ "MenuCategory object (9)", "MenuCategory object (10)", "MenuCategory object (11)" ] } ] but … -
Django: Passing content of CSV file into the URL to upload data
In my Django web app (a person directory), I have a view/function by which I can directly enter rows in the database by requesting the URL with that string. Its like: example.herokuapp.com/enterdata?data=PersonName_PersonEmailID_PersonPhone&password=secretkey With this I can upload data in the database from outside scripts. I am running a python script in Google Colab which is scraping data for entering in this django app and by the URL above I can enter data into it. But this will result in too many requests being made by the same IP which can lead to crashing of the website. Is it possible to enter the whole text of CSV file (which can contain tens/hundreds/thousands of rows) into the URL so reduce the number of requests? If I do this, what kind of problems can arise? -
How to check for inactive users in Django in ModelBackEnd
How would I check for inactive custom users in ModelBackEnd without returning None (like what AllowAllUsersModelBackend does)? Here's what I have so far: from django.contrib.auth import backends, get_user_model from django.db.models import Q UserModel = get_user_model() class ModelBackend(backends.ModelBackend): def authenticate(self, request, username=None, password=None, **kwargs): if username is None: username = kwargs.get(UserModel.USERNAME_FIELD) try: # user = UserModel._default_manager.get_by_natural_key(username) # You can customise what the given username is checked against, here I compare to both username and email fields of the User model user = UserModel.objects.get(Q(username__iexact=username) | Q(email__iexact=username)) #print("what is going on") except UserModel.DoesNotExist: # Run the default password hasher once to reduce the timing # difference between an existing and a nonexistent user (#20760). UserModel().set_password(password) else: if user.check_password(password) and self.user_can_authenticate(user): return user return super().authenticate(request, username, password, **kwargs) -
Can not connect to admin page on django 3.0.7
I just installed django and when I go to log onto the admin page the runserver stops running and the only error that pops up is ERR_CONNECTION_REFUSED. The virtual environment is active and running, and I can not find any answers online. -
Creating dynamic database with relations in Django restframwork?
I want to create a dynamic form in the front end using Angular, this form will use the form array to achieve dynamic addition of fields. On the other hand, I want to connect this form with Django backend using the Django rest framework. I have made two Django models, the first one contains the fixed form controls, and the other model contains the dynamic part of the form. These two models are connected with a many-to-one relationship. I what I need to do to make the API dynamic to handle the post request. And thanks! -
can not install psycopg2 on macOS Catalina
when installing psycopg2 in my Django project pip install psycopg2==2.7.* I get this error : psycopg/psycopgmodule.c:689:18: error: incomplete definition of type 'struct _is' I tried the answer to the following question: Is there any problem installing psycopg2 in virtualenv on MacOS catalina with PostgreSQL 12.1 installed? but I still get the same error -
How to pass a filtered object variable from views.py to a HTML template
Code is as follows: views.py from django.http import HttpResponse from django.shortcuts import render from django.contrib.auth.decorators import login_required from tickets.models import Ticket @login_required(login_url="/accounts/login") def home(request): return render(request, "home.html") def ticket_status_count(request): open_count = Ticket.objects.filter(ticket_status='open').count() in_progress_count = Ticket.objects.filter(ticket_status='inProgress').count() pending_count = Ticket.objects.filter(ticket_status='pending').count() resolved_count = Ticket.objects.filter(ticket_status='resolved').count() closed_count = Ticket.objects.filter(ticket_status='closed').count() waiting_on_customer_count = Ticket.objects.filter(ticket_status='waitingOnCustomer').count() waiting_on_third_party_count = Ticket.objects.filter(ticket_status='waitingOnThirdParty').count() return render(request, 'home.html', {'open_count': open_count}) home.html {% extends "index.html" %} {% block content %} <!-- Today's Tasks Header --> <header id="header"> <div class="container"> <div class="row"> <div class="col-md-6"> <h2><svg class="bi bi-calendar" width="1em" height="1em" viewBox="0 0 20 20" fill="currentColor" xmlns="http://www.w3.org/2000/svg"> <path fill-rule="evenodd" d="M16 2H4a2 2 0 00-2 2v12a2 2 0 002 2h12a2 2 0 002-2V4a2 2 0 00-2-2zM3 5.857C3 5.384 3.448 5 4 5h12c.552 0 1 .384 1 .857v10.286c0 .473-.448.857-1 .857H4c-.552 0-1-.384-1-.857V5.857z" clip-rule="evenodd"/> <path fill-rule="evenodd" d="M8.5 9a1 1 0 100-2 1 1 0 000 2zm3 0a1 1 0 100-2 1 1 0 000 2zm3 0a1 1 0 100-2 1 1 0 000 2zm-9 3a1 1 0 100-2 1 1 0 000 2zm3 0a1 1 0 100-2 1 1 0 000 2zm3 0a1 1 0 100-2 1 1 0 000 2zm3 0a1 1 0 100-2 1 1 0 000 2zm-9 3a1 1 0 100-2 1 1 0 000 2zm3 0a1 1 0 100-2 … -
Django - how to get email links to work on mobile?
My Django site sends out an email confirmation link, and everything seems to work fine on desktop. On mobile devices, however, the link text is highlighted blue and underlined (i.e. it looks like a link) but nothing happens when the user clicks it. It should open a browser tab and say, "you have confirmed your email, etc" Thanks for any tips! views.py: def signup(request): if request.method == 'POST': #send signup form email_address = request.POST['email'] if request.POST['password1'] == request.POST['password2']: try: user = User.objects.get(email=email_address) return render(request, 'accounts/signup.html', {'error': "Email already in use."}) except User.DoesNotExist: user = User.objects.create_user(request.POST['email'], password=request.POST['password1']) #auth.login(request, user) #send email confirmation link then redirect: #user = User.objects.get(email=email_address) current_site = get_current_site(request) mail_subject = 'Welcome to My Site' plain_msg = 'Thank you for signing up to My Site! Click this link to activate your account:\n\n'+current_site.domain+'/accounts/activated/'+urlsafe_base64_encode(force_bytes(user.pk)).decode()+'/'+account_activation_token.make_token(user)+'/' msg = '<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><title>title</title></head><body>Confirm your email address to continue:<br/><a href="'+current_site.domain+'/accounts/activated/'+urlsafe_base64_encode(force_bytes(user.pk)).decode()+'/'+account_activation_token.make_token(user)+'/">Confirm my email address</a></body></html>' print(msg) send_mail(mail_subject, plain_msg, 'my_email@gmail.com', [email_address], html_message=msg) return render(request, 'accounts/activation-link-sent.html', {'email': email_address}) #truncated for Stack Overflow post -
How do I render all the objects of a child model belonging to a particular object of the parent model on click?
Suppose there are two models Lists and Tasks where 'Lists' have one-to-many relationship with 'Tasks'. All the objects of the Lists model are rendered on the page like this: HTML <div class="grid-container"> {% for list in lists %} <!--lists is context for Lists.objects.all() --> <div class="grid-item" id="{{ list.id }}" onclick="showTasks( {{ list.id }} )"> {{ list.name }} </div> {% endfor %} </div> <dialog id="tasks"> </dialog> JavaScript <script> function showTasks(listid){ document.getElementById("tasks").show(); } </script> Now I want to render all the tasks_set (all the objects of 'Tasks') related to a particular object of 'Lists' in that dialog with id="tasks". As it can be seen in the above snippet, I thought of doing it by passing list.id as a parameter to the JavaScript function but couldn't figure out beyond it. How can I achieve it? -
How to create an instance of an object with inherited from a parent fields?
I have two classes: Word and its child Verb: class Word(models.Model): original = models.CharField(max_length=40) translation = models.CharField(max_length=40) class Verb(Word): group = models.IntegerField(default=1) past_form= models.CharField(max_length=40) future_form = models.CharField(max_length=40) First, I created an instance of Word: new_word = Word() I did some processing with this instance, and now I need to create an instance of Verb, based on new_word. I tried to do it like this: new_verb = Verb(new_word) but looks like this is not the right way. Important remark: I cannot override __init__ method, because Word inherits from django model -
Python/Django - How to dynamically add scripts/classes to the code?
I have a Django project where users can register and add their XML/CSV feeds. What the project does is (everyday morning): download the feed parse the feed and store it to the model Product generate XML/CSV export from these products in a different format Now the problem is that users can register anytime during the project lifetime and many feeds have to be either downloaded, parsed or exported in a specific way. So I need to be able to react quickly when the feed is added and write custom functions/classes/scripts to download/parse or export these sources. Let's say it would be enough to add or extend some base classes like Downloader,Parser or Exporter I'm looking for the most common way to do this. I tried multiple approaches. For example, I've created a package parsers and there is a __init__.py with CHOICES attribute. When a user adds new feed, I create a parser__sourcename.py file which I add into parsers package which contains Parser class which extends BaseParser class with parse method where is the custom code. Then I add import into __init__.py file so it looks like this: from feeds_core.parsers.parser__source1 import Parser as ParserForSource1 from feeds_core.parsers.parser__source2 import Parser as ParserForSource2 from … -
Django - How do I add the user I created to my group?
I'm using django-groups-manager. I logged in as a user. When I register another user, how do I register another user under the group name I belong to? How do I add members to the group? forms.py class CalisanForm(forms.ModelForm): member = forms.CharField(max_length=100, label='Çalışan Adı') class Meta: model = User fields = [ 'member', ] views.py def calisan(request): form = CalisanForm(request.POST or None) if form.is_valid(): member = form.cleaned_data['member'] member = Member.objects.create(first_name=member) return redirect('home') return render(request, 'accounts/calisan/calisan.html', {'form': form}) -
Creating Django Forms from Querysets
I am working on a Django form that let's you order customs pizzas. When building the form to "Select Size" for instance, I want to pull from a database that has my menu item's available sizes in it, so that if the menu changes, the form will automatically know what sizes are available. Right now I am having an issue with how the query set is returned as it shows up. How should I alter the code such that queryset=query_list.values_list('size').distinct() shows up in the drop down as: Small, Medium and not: (Small,), (Medium,) Or is there maybe a way to pull directly from the SIZE_CHOICES tuple in the class? Thank you! Models.py: class Pizza(MenuItem): STYLE_CHOICES = ( ('Regular', 'Regular'), ('Sicilian', 'Sicilian'), ) SIZE_CHOICES = ( ('Small', 'Small'), ('Large', 'Large'), ) style = models.CharField(max_length=16, blank=False, choices=STYLE_CHOICES) size = models.CharField(max_length=16, blank=False, choices=SIZE_CHOICES) num_toppings = models.IntegerField() toppings = models.ManyToManyField(Topping, blank=True) is_special = models.BooleanField(default=False) def toppings_list(self): return "\n".join([p.name for p in self.toppings.all()]) def __str__(self): return f"{self.style} {self.size}" forms.py class PizzaForm(forms.Form): query_list = Pizza.objects.all() style = forms.ModelChoiceField( widget=forms.Select, queryset=query_list, empty_label="Select Size" ) size_choices = forms.ModelChoiceField( widget=forms.Select, queryset=query_list.values_list('size').distinct(), empty_label="Select Size" ) topping_choices = forms.ModelMultipleChoiceField( widget=forms.CheckboxSelectMultiple, queryset=Topping.objects.all(), required=False ) -
django-filter FilterSet on CharField through two foreign keys
I'm attempting to write a FilterSet class using the django-filter package. I have three models set up like this: class Location(models.Model): address_line1 = models.CharField(...) class Service(models.Model): location = models.ForeignKey('path.to.app.Location', on_delete=models.CASCADE) class Inventory(models.Model): assignment = models.ForeignKey('path.to.app.Service', on_delete=models.SET_NULL, null=True) I'm writing a FilterSet for the Inventory class that filters on the related value of address_line1; in short, I want to be able to search for inventory by address. I wrote the following FilterSet class: class InventoryFilter(django_filters.FilterSet): class Meta: model = Inventory fields = { 'assignment__location__address_line1': ['icontains'], } When I attempt to access the view with this field defined, I get this error: TypeError: 'Meta.fields' contains fields that are not defined on this FilterSet: assignment__location__address_line1 When I do something similar through only one foreign key (for example, if address_line1 was stored in the Service model instead of the Location model), this works just fine. How do I get this to work, or why is it not working through two foreign keys? -
'su' is not recognized as an internal or external command, operable program or batch file
I am trying to follow the book 'Django 2 by example' and when it comes to installing PostgreSql I am running into the following problem: 'su' is not recognized as an internal or external command, operable program or batch file. basically after installing PostgreSql it says to run in the python shell the following command, in order to create a user for the database. su postgres createuser -dP blog Obviously I can't even reach the second line. Does anyone have any idea of why this happens? I don't really know what else to post in order to help you to find a solution, so if any other info or piece of code is needed just let me know about it. Thanks -
Django crispy forms: Is it possible to have a remember me function in combination with crispy forms?
So, I'm currently working on a project in Django, and I would like to implement a remember me function alongside the login functionality. Yet, I've been trying for a few hours now, and I'm kinda stuck. I am using crispy_forms for validation & authentication. There were a lot of questions showing how to implement it (which was relatively easy to do), yet I could not find one that was in combination with crispy_forms. Could anyone help me out? -
Is Django Framework Good for developing microservices?
I have an experience with Django Rest Framework for developing Rest API for monolithic apps. But I was wondering if it's still a good framework for developing microservices. Especially in my case I'm working with a centralized NoSQL DB for all microservices (DynamoDB) in an AWS serverless architecture . I found this link for django-microservices but I couldn't find an example or more documentation about it. I did some researches and I found that the most popular Python framework for microservices is Flask. But I have no experience with it. So could anybody have a link for a document about building microservices with Django (if it's possible, of course)? -
How to submit dynamically generated forms by pressing Enter key using jquery
My website have a comment system. Website is built with django framework, and I am loading all post's comment with loop. I am able to add comment text in text box of first post, rest of the posts does not submitting comment, I know this is due to dynamically generated id's of every form and comment boxes. I am also able to submit dynamically generated comments boxes of all posts when I have submit button in form But I want to submit these comments when user press Enter button such as Facebook comment. Below is the comment form code for every post, I have discarded rest of the code that is related to showing posts. {% for i in posts %} ///Rest of the code for posts... <form method="POST" id= 'post-form'> {% csrf_token %} <div class="comment-block"> <img class="img-circle" src="{% static 'mysite/images/avatar.png' %}"> <input type="text" name="post_id" id="post_id" value="{{i.post_id}}" hidden> <input name="user_id" id="user_id" value="{{i.user_id}}" hidden> <span class="username"><a href="#">{{ i.user_name }}</a> <input type="text" name="comment_text" id="comment_text" class="comment-text form-control col-md-8" placeholder="Write a comment..."> <span></span> </div> </form> {% endfor %} Below is the jquery code that I am using to access dynamically generated forms $(this).find('#comment_text').keyup(function(e){ if(e.keyCode ==13){ comment_text = $(this).find('#comment_text').val(); user_id = $(this).find('#user_id').val(); post_id = $(this).find('#post_id').val(); …