Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to find relationship between two objects Django in large codebase
I'm working on a new large codebase. There are a ton of models with foreign key relationships and I'm having a hard time keeping them all in my head as I click through the different foreign key relationships. I'm using PyCharm so it's nice to be able to click through the different relationships. The problem is if I have two objects that I'm are connected, i'm basically reduced to clicking down seemly endless relationship paths, which is time consuming and confusing. A lot of times I'll find my self many levels deep from the object I started at and run into a dead end, then I'll have to chase back up the tree and try another path. I tried to use this tool in an attempt to auto draw a uml, but the uml has so many lines between the different objects, I can't tell which ones are connected and it also outputs a png, so I can't search for a model. Does anyone have a recommendation on how I can do this more easily? -
Django rest framework ajax form submit error 403 (forbidden)
When i try to submit my ajaxified form that's working with the DRF API i get in the browser console POST http://localhost:8000/api/texts/ 403 (Forbidden) here is my html file : <form id="text-form" method="POST" action=""> <input type="text" name="title" placeholder="Title" class="form-control mb-3 pb-2" maxlength="200" required id="title"> <input type="date" name="deadline" placeholder="Deadline" autocomplete="off" class="form-control mb-3" id="myflatpickr"> <textarea name="requirements" cols="40" rows="4" placeholder="requirements" class="form-control col mt-3" maxlength="200" required id="requirements"></textarea> <textarea name="document" cols="40" rows="10" placeholder="document" id="editor" class="form-control" required></textarea> <button type="submit">Submit</button> </form> here is my javascript file $("#text-form").submit(function (event) { event.preventDefault(); $textData = $("#text-form").serialize() $.ajax({ url: "http://localhost:8000/api/texts/", method: "POST", data: $textData, success: function() { console.log($textData) }, error: function() { console.log("there is an error") } }) }); in serializers.py: from django.contrib.auth import get_user_model from django.contrib.auth.password_validation import validate_password from rest_framework import serializers from .models import * class TextSerializer(serializers.ModelSerializer): author = serializers.HiddenField( default=serializers.CurrentUserDefault() ) class Meta: model = Text fields = '__all__' in my views.py file: class ApiTextList(generics.ListCreateAPIView): queryset = Text.objects.all() serializer_class = TextSerializer permission_classes = [ permissions.AllowAny ] class ApiTextDetail(mixins.RetrieveModelMixin, mixins.UpdateModelMixin, mixins.DestroyModelMixin, generics.GenericAPIView): http_method_names = ['get', 'head'] queryset = Text.objects.all() serializer_class = TextSerializer permission_classes = [ permissions.AllowAny ] def get(self, request, *args, **kwargs): return self.retrieve(request, *args, **kwargs) def put(self, request, *args, **kwargs): return self.update(request, *args, **kwargs) def delete(self, request, *args, … -
Python send_email() results in "socket.gaierror: [Errno -3] Temporary failure in name resolution"
Introduction I'm hosting a Django application with Nginx and Gunicorn on a Digital Ocean droplet (Ubuntu 20.04) with a domain name and mail bought at NameCheap. I will use the following example values in my code snippets: domain = example.com email = info@example.com droplet ip address = digital_ocean_droplet_ip When sending out a confirmation mail I get the following error: gunicorn[97049]: self.connection = self.connection_class(self.host, self.port, **connection_params) gunicorn[97049]: File "/usr/lib/python3.8/smtplib.py", line 1043, in __init__ gunicorn[97049]: SMTP.__init__(self, host, port, local_hostname, timeout, gunicorn[97049]: File "/usr/lib/python3.8/smtplib.py", line 255, in __init__ gunicorn[97049]: (code, msg) = self.connect(host, port) gunicorn[97049]: File "/usr/lib/python3.8/smtplib.py", line 339, in connect gunicorn[97049]: self.sock = self._get_socket(host, port, self.timeout) gunicorn[97049]: new_socket = socket.create_connection((host, port), timeout, gunicorn[97049]: File "/usr/lib/python3.8/smtplib.py", line 1049, in _get_socket gunicorn[97049]: File "/usr/lib/python3.8/socket.py", line 787, in create_connection gunicorn[97049]: for res in getaddrinfo(host, port, 0, SOCK_STREAM): gunicorn[97049]: File "/usr/lib/python3.8/socket.py", line 918, in getaddrinfo gunicorn[97049]: for res in _socket.getaddrinfo(host, port, family, type, proto, flags): gunicorn[97049]: socket.gaierror: [Errno -3] Temporary failure in name resolution socket.gaierror: [Errno -3] Temporary failure in name resolution Django settings.py ALLOWED_HOSTS = os.environ.get('example.com,www.example.com,digital-ocean-droplet-ip') EMAIL_BACKEND="django.core.mail.backends.smtp.EmailBackend" EMAIL_USE_SSL=False EMAIL_USE_TLS=True EMAIL_PORT=587 EMAIL_HOST="mail.privateemail.com" EMAIL_HOST_USER="info@example.com" EMAIL_HOST_PASSWORD="***" DEFAULT_FROM_EMAIL="info@example.com" Django views.py from django.core.mail import send_mail # Send confirmation email send_mail( # Subject 'Subject', # Message 'Message', # Sender 'info@example.com', # … -
How to cache iframe in django
I am building a django app and one of my templates has a mapstore iframe on it. That iframe is kind of heavy. Is there any way to cahce that iframe, or all the template, i dont have to wait so long every time the page is loaded. this is the iframe <iframe src="http://tedcap.denebinc.com/mapstore/#/viewer/openlayers/1" frameborder="0" width="100%" height="400" allowtransparency ></iframe> -
How to get all form field data in Django UpdateView when working with many-to-many model field?
For some reason my UpdateView is not displaying the selected associated. The form is pre-populated with only the first form field data results, username, and none of the other field data. I suspect this is due to the ManytoMany field being queried. I've searched for and tried possible solutions but nothing has worked. Any ideas? Models.py class Company(models.Model): """All company specific details. For each main manager, a company is created. The main manager can then add company members, creating for them their user accounts.""" members = models.ManyToManyField( settings.AUTH_USER_MODEL, related_name='teams', through='CompanyMembership' ) ... class CompanyMembership(models.Model): """Acts as a gateway between User model and Company model""" STAFF = "STAFF", "Staff" MANAGERS = "MANAGERS", "Managers" my_company = models.ForeignKey(Company, on_delete=models.CASCADE) my_identity = models.ForeignKey(User, on_delete=models.CASCADE) my_role = models.CharField(max_length=100, choices=MemberTypes.choices, default=None) class User(models.Model): """Users can be main managers or staff. Each main manager has their own Company. Many staff can belong to a single Company associated with a main manager.""" username = models.CharField(_("Login Name"), blank=True, null=True, max_length=155, unique=True) ... Views.py class TeamMembersView(LoginRequiredMixin, CompanyMembershipCheckMixin, UserPassesTestMixin, ListView): """Lists all the company team members for the specific company""" model = Company template_name = 'users/dashboard/team.html' def test_func(self): user_obj = User.objects.get(id=self.request.user.id) return user_obj.groups.filter(name='Company_Main_Manager').exists() def get_context_data(self, **kwargs): context = super(TeamMembers, self).get_context_data(**kwargs) user_obj … -
Django Rest Framework - test uploading image for nested serializer
Serializers class PostImageSerializer(serializers.ModelSerializer): class Meta: model = PostImage fields = ('image', ) class PostSerializer(serializers.ModelSerializer): images = PostImageSerializer(many=True) flat_info = FlatPostSerializer(read_only=True) class Meta: model = Post fields = '__all__' Test @override_settings(MEDIA_ROOT=tempfile.gettempdir()) def test_crud_operations_for_post(self): *_, flat = self.init_house_structure() url_create = reverse('main:posts-list') with open(self.temp_media_image_path, 'rb') as file: response_create = self.client.post(url_create, data={'flat': flat.pk, 'price': 100000, 'payment_options': 'PAYMENT', 'images': [ {'image': file} ]}, format='json',) self.assertEqual(response_create.status_code, 201) View is just a regular ModelViewSet This test returns error with: UnicodeDecodeError: 'utf-8' codec can't decode byte 0x89 in position 0: invalid start byte I tried to user 'SimpleUploadedFile' and got error: The submitted data was not a file. The same error if i try to generate new temporary file using 'Pillow' and 'temporary' package. I think the problem with "format='json'", because if remove it - the problem disappears. Also, i have lots of another test with images(but without json format) .but i cant remove it. Nested serializer requires json format to be serialized in right way. So, i really don`t understand how can i test it. 'self.temp_media_image_path' is a path to local image. This is real image which i store in project`s folder P.S. Not a native, sorry -
Django 'AnonymousUser' object is not iterable after passing user context in context processor
I need to show few user info in my nav bar such as number of notification, user name etc. So I am passing context in my context processor. My nav bar located in my base.htm and I am extending my base.html in my all html page. I am getting this error if user isn't login 'AnonymousUser' object is not iterable.here is my code: settings.py 'context_processors': 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', 'notifications.views.Count_Notifications', #passing context from notifications app views.py def Count_Notifications(request): count_notifications_comment = 0 count_notifications_author = 0 blog_author = Blog.objects.filter(author=request.user) if request.user.is_authenticated: count_notifications_comment = Notifications.objects.filter(sender=request.user,is_seen=False).count() count_notifications_author = Notifications.objects.filter(user=request.user,is_seen_author_noti=False).count() return {'count_notifications_comment':count_notifications_comment,'count_notifications_author':count_notifications_author,'blog_author':blog_author} -
Useage of CSV for Django Rest Framework
I've been trying to build a website with a backend via Django and a frontend via React. I would like to make it so users can see the contents of a CSV file. The Django rest framework site recommends using the following: https://github.com/mjumbewu/django-rest-framework-csv#readme I was wondering if anyone had any examples of how to use this to turn into an api that can then be used on the frontend with react. I can't seem to find any examples of how to do this. -
Django admin inline module is not rendering form's widget
I tried to use a custom widget of the library django-ace and pretty-json, but I don't know why it's not rendering these widgets when I put it into the inline module and it's rendering a texarea by default. I think it's an issue of django inline module, but I don't know if someone has recommendation to solve this. from django_ace import AceWidget from django import forms from django.forms import formset_factory, BaseInlineFormSet from prettyjson import PrettyJSONWidget from django.contrib import admin class StatementForm(forms.ModelForm): class Meta: model = Statements fields = ['query', 'executed', 'logs'] widgets = { 'logs': PrettyJSONWidget(attrs={'initial': 'parsed'}), 'query': AceWidget(mode='sql') } StatementFormSet = formset_factory(StatementForm, formset=BaseInlineFormSet, can_order=True) class StatementTabularInline(admin.StackedInline): model = Statements formset = StatementFormSet readonly_fields = ['executed', 'logs', ] @admin.register(Ticket) class TicketAdmin(admin.ModelAdmin): inlines = [StatementTabularInline] links: Django ace: https://pypi.org/project/django-ace/ Pretty json: https://pypi.org/project/django-prettyjson/ result: result of the render of the form -
Value Error: ModelForm has no model class specified
I am getting this error message: Value Error: ModelForm has no model class specified. and have spent a few hours trying to fix it with no progress, i started getting the error and after i added my forms.py part . I will show my forms.py then my views.py from django.forms import ModelForm from .models import Found class FoundForm(ModelForm): class Meta: model: Found fields = ['date', 'type'] ```from django.shortcuts import render ```from .models import Rock #main app.models, models attribute. even photo models ```from .forms import FoundForm ```# Create your views here.views send data to our context dictionary ```def home(request): return render(request, 'home.html') ```def about(request): return render(request, 'about.html') ```def rocks_index(request): rocks = Rock.objects.all() return render(request, 'rocks/index.html', {'rocks': rocks}) ```def rocks_detail(request, rock_id): rock = Rock.objects.get(id=rock_id) found_form = FoundForm() return render(request,'rocks/detail.html', { 'rock': rock, 'found_form': found_form }) ```class RockCreate(CreateView): model = Rock fields = '__all__' #class based view generate html5 forms -
return random models in json format - django
I need to return random data from models in json format but when I try random.choice I got the error 'Joke' object is not iterable . views.py def random_page(request): random_joke = random.choice(Joke.objects.all()) jokes_list = serializers.serialize('json', random_joke) return HttpResponse(jokes_list, content_type="text/json-comment-filtered") models.py from django.db import models class Joke(models.Model): joke = models.TextField(max_length=1000) author = models.CharField(max_length=100, null=True) def __str__(self): return str(self.joke) -
Count likes with graphene django
I am trying to make a field with graphene django to be able to count the total number of likes that I have per post, how could I do it, what I have tried to do is the following class PostType(DjangoObjectType): class Meta: model = Post likes = graphene.List() def resolve_count_like(self, info, id): post_id = Post.objects.filter(id=id) n = Likes.objects.filter(post_id=post_id) return len(n) -
uwsgi fails to serve Django from a .ini file
Steps to reproduce: mkdir django-uwsgi cd django-uwsgi python -m venv venv source venv/bin/activate pip install Django uwsgi django-admin startproject mysite cd mysite python manage.py migrate Try to serve django locally with uwsgi via command line: uwsgi --module mysite.wsgi --http :8000 Result: it works! YES! Now, create a uwsgi.ini file with the following content: [uwsgi] module = mysite.wsgi http = :8000 then use uwsgi --ini uwsgi.ini Result ModuleNotFoundError: No module named 'mysite.wsgi # define the django module to use' OK... So we need something else... Try adding the current directory... chdir = {WORKSPACE}/django-uwsgi/mysite YES? Result: ModuleNotFoundError: No module named 'mysite.wsgi # define the django module to use' Try specifying the virtualenv. Result: virtualenv = {WORKSPACE}/django-uwsgi/venv # or, or both home = {WORKSPACE}/django-uwsgi/venv YES? Result: ModuleNotFoundError: No module named 'mysite.wsgi # define the django module to use' Here is a full tracebakc: $ uwsgi --ini uwsgi.ini [uWSGI] getting INI configuration from uwsgi.ini *** Starting uWSGI 2.0.19.1 (64bit) on [Fri Jul 16 14:44:03 2021] *** compiled with version: 9.3.0 on 16 July 2021 18:42:33 os: Linux-5.11.0-7614-generic #15~1622578982~20.04~383c0a9-Ubuntu SMP Wed Jun 2 00:57:14 UTC 2 nodename: pop-os machine: x86_64 clock source: unix pcre jit disabled detected number of CPU cores: 8 current working directory: … -
Building a uwsgi plugin for python 3.9 failed for older version it works. Are there any other options?
i downloaded the latest source code uwsgi-2.0.19.1 and tried to build a uwsgi plugin for python 3.9 but it failed every time. For other Versions like python3.6 or python3.8 it works and i used them in other Django Projects. For Example... Here it works: Command: [user@me /uwsgi-2.0.19.1] $ make PROFILE=nolang [user@me /uwsgi-2.0.19.1] $ PYTHON=python3.6 ./uwsgi --build-plugin "plugins/python python36" Output: *** uWSGI building and linking plugin from plugins/python *** [gcc -pthread] python36_plugin.so build time: 5 seconds *** python36 plugin built and available in python36_plugin.so *** Command: [user@me /uwsgi-2.0.19.1] $ PYTHON=python3.8 ./uwsgi --build-plugin "plugins/python python38" Output: *** uWSGI building and linking plugin from plugins/python *** [gcc -pthread] python38_plugin.so build time: 5 seconds *** python38 plugin built and available in python38_plugin.so *** Here it fails: "Datei oder Verzeichnis nicht gefunden" is german and means "File or directory not found". command: [user@me /uwsgi-2.0.19.1] $ PYTHON=python3.9 ./uwsgi --build-plugin "plugins/python python39" outpu: *** uWSGI building and linking plugin from plugins/python *** [gcc -pthread] python39_plugin.so In file included from plugins/python/python_plugin.c:1: plugins/python/uwsgi_python.h:2:10: fatal error: Python.h: Datei oder Verzeichnis nicht gefunden 2 | #include <Python.h> | ^~~~~~~~~~ compilation terminated. In file included from plugins/python/pyutils.c:1: plugins/python/uwsgi_python.h:2:10: fatal error: Python.h: Datei oder Verzeichnis nicht gefunden 2 | #include <Python.h> | ^~~~~~~~~~ … -
Dropdown isn't showing everything in CSS
So I am trying to make a basic nav menu with a drop down from my Django app. My menu is fine, but the dropdown doesn't want to show all the links. How to fix this? HTML <nav role="navigation"> <ul> <li><a href="">Chat Home</a></li> <li><a href="" aria-haspopup="true">Go To <i class="fa fa-caret-down"></i></a> <ul class="dropdown" aria-label="submenu"> <li><a href="" target="_blank">Calendar</a></li> <li><a href=" " target="_blank">Big Blue</a></li> </ul> </li> <li><a href="" style="float: right">Logout</a></li> </ul> </nav> CSS ul { list-style-type: none; margin: 0; padding: 0; background-color: #333; position: sticky; position: -webkit-sticky; width: 100%; height: 1.5rem; } li { float: left; font-size: 1rem; padding: 0.25rem 1rem; letter-spacing: 1.5px; cursor: pointer; display: block; position: relative; } li a { color: white; text-decoration: none; text-align: center; } ul li ul li { display: block; padding: 0.25rem 1rem; } li:hover, li:focus-within { background-color: black; } li:focus-within a { outline: none; } ul li ul { display: none; background-color: #333; position: absolute; visibility: hidden; left: 0; margin-top: 2px; } ul li:hover > ul, ul li:focus-within > ul, ul li ul:hover, ul li ul:focus { display: block; visibility: visible; } You can see what I mean here: https://jsfiddle.net/rj269hsf/ But essentially, when I hover over the "Go To" item it will drop the first … -
Django Channels TokenAuthMiddleware Unable to find Token in Database
I'm so confused why my middleware isn't correctly getting a user based token query by key. First I checked in my consumer, however the user in self.scope was an AnonymousUser (seen below in the code). This is reiterated when I set a foreign key in my receiver function, which raises the error: ValueError: Cannot assign "<django.contrib.auth.models.AnonymousUser object at 0x10943cc10>": "ChatMessage.user" must be a "User" instance. Hence, I'm assuming the error is my middleware. I experimented with putting a print statement in middleware.TokenAuthMiddleware.__call__ after the get_user function is awaited and called, however, unexpectedly, the function returns an AnonymousUser. Both the user and the associated Token are created in the testcase's setUp and it's that token's key which is passed to the function. Is the token string becoming malformed in format_querystring? The function is tested and passed, so I do not believe the token is becoming malformed there. One thought is because the user and the token are being created in setUp, which is not async, it somehow is not aligned with the processes of the database look up in get_user. However changing that to async and wrapping the database calls in database_sync_to_async did not fix it, so I don't believe it's … -
Pass arguments to websocket in Django
When working with websockets, how do I pass arguments to the server side from the browser? I want to return Hello, from the server when the browser makes a WS request. The shall be passed from the client. JavaScript run in the browser. var socket = new WebSocket('ws://<IP>:80/ws/hello/'); socket.onmessage = function(event){ var data = JSON.parse(event.data); console.log(data); } The routing.py from django.urls import path from .consumers import * ws_urlpatterns = [ path('ws/hello/', Hello.as_asgi()) ] The consumers.py from channels.generic.websocket import WebsocketConsumer class Hello(WebsocketConsumer): def connect(self): self.accept() clear_output_file() self.send(json.dumps({'message':"Hello, <NAME>!"})) How do I get the NAME to be replaced with the client's name? Can I in the JavaScript code use var socket = new WebSocket('ws://<IP>:80/ws/hello/?<NAME>'); When I do that, how do I pass the name to the Hello class in consumers.py and shall I add something special in routing.py? -
Authorized requests with OAuth2 access_token from react to django
I have a react frontend in which I am successfully logging into my google account with react-google-login. I then save this access_token to local storage and it is also saved to the django-allauth social application token table. I then try to make a simple GET request to django, attaching the access_token to the Authorization header, but I am receiving 401 (Unauthorized). This is the get request I am making: axios.get('http://localhost:8000/api/test/', { headers: { Authorization: 'Bearer ' + localStorage.getItem('access_token'), 'Content-Type': 'application/json', accept: 'application/json', } }) .then(res => console.log(res)) Here are a few settings in settings.py AUTHENTICATION_BACKENDS = [ 'django.contrib.auth.backends.ModelBackend', 'allauth.account.auth_backends.AuthenticationBackend', ] REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework.authentication.TokenAuthentication', ], 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.IsAuthenticated', ], } CORS_ORIGIN_ALLOW_ALL = True -
How to apply nulls_last ordering to an extra select field in Django?
I'm trying to apply order_by() with nulls_last=True to a queryset: MyModel.obects.all().order_by(*[models.F('field').desc(nulls_last=True)]) This works fine for regular fields, but it throws an error when I try to order by an extra field in the same manner: queryset = MyModel.obects.extra(**{'select': {'extra_field': 'custom_sql'}}).all() queryset = queryset.order_by(*[models.F('extra_field').desc(nulls_last=True)]) The problem is it is unable to find extra_field column when using models.F(). If I simply use order_by('extra_field') as a string it works because Django is doing some extra preprocessing and handles extra fields differently. After digging through the sources I was able to make it work as: queryset = MyModel.obects.extra(**{'select': {'extra_field': 'custom_sql'}}).all() queryset = queryset.order_by(*[models.expressions.Ref('extra_field', models.expressions.RawSQL('custom_sql', [])).desc(nulls_last=True)]) The downside of this solution is that I have to treat regular fields and extra fields differently, and I have to repeat the custom_query inside order_by. I am trying to build a universal function that would simply take a list of fields as stings (how Django would take) and wrap them with nulls_last. The question is: Given only a field name as a string and a queryset, is there a universal way to apply nulls_last to it without specifying if this is a native field or an extra, and without passing a custom query for an extra field? I … -
How to create MultipleChoiceField in django-filter?
I have a model Color: class Color(models.Model): color = models.CharField(max_length=32) def __str__(self): return self.color And my Product model: class Product(models.Model): ... color = models.ForeignKey('Color', on_delete=CASCADE) ... So i need to create a filter that i'll able to get for example all red, blue or yellow products How can i do that? -
Is it necessary to activate Django Virtual Environment every time i restart my vscode Django
Is it necessary to activate the virtual environment? How can we re-enter/re-activate the already existing environment in Django? I shut down my computer and when I reopen the vs code the the '(venv)' mark is not there in the terminal before the locationenter image description here Also is this the reason why I am getting the error ImportError: cannot import name 'static' from 'django.conf' -
How to define a string method for a many to many relation in Django?
It is possible to define a __str__ method on a model: class Person(models.Model): name = models.CharField(max_length=40) hobbies = models.ManyToManyField(Hobby) def __str__(self): return self.name But how to define something like this for an automatically generated table through a ManyToManyField? Objects that represent a relationship between a person and a hobby are written like this: Person_hobbies object (1) Note that I am not talking about the Hobby object itself, but the object that represents the relation between a Person and a Hobby. -
Django Rest API - Get & Verify User ID by token
How to obtain User ID from Django API having authentication token? Basically, I want to send an authentication token and get back the User id. Basically I want to verify the company id that must be call by Django rest API! -
Django Question. How to I change default django-filter "---------" option to custom string?
This is kind of insignificant, but does anyone know how to change the default choice in a django-filter FilterSet from "---------" to any given string? I'd like to change it to "All" because all the options are displayed if "---------" is selected. Do I override init maybe? Thanks in advance. -
Git bash color formats are not working. Instead it prints the color code in terminal
When I was using git bash for flask development, it worked fine. But now I am learning Django and when I use git bash instead of show status in color it shows the color code around the status. Someone help me with this. here is the image of my terminal