Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 -
Creating custom 404 page in django is causing problems loading javascript files
I am handling 404 error using a custom "not found page". But doing that is causing that from that moment the templates are nou loading all the javascripts files and plugins. This is my code in urls.py handler404 = 'riesgo.views.views.error_404' in views/views.py def error_404(request, exception): data = {} return render(request, '404.html', data) I check the log and loading all js files is causing a 404 error -
Django: Why is my view not displaying to HTML
I'm new to django and trying to get my machine learning model to display recommendations for a logged in user. The current view is this: def my_view(request): username = None if request.User.is_authenticated(): username = request.User.username result3 = get_recommendation(username, n=10) return render(request,'test.html', {'result3':result3}) else: pass It searches for the currently logged in user, and passes their user id (their username) into the function to get a recommendation for that user, and attempts to impute the result onto a html test page (the user is already logged in to be accessing this test page). The test page itself looks like this: {% if user.is_authenticated %} {{ result3 }} {% endif %} Does anyone know what I'm doing wrong? -
How To Add Multiple Forms In CreateView
I'm making a restaurant project where an order can be filled with order items. I want to create more than one order item at a time but I haven't done that before, so I have no idea how to do it.There are examples of Formsets and Inline Formsets but only for function based views.So any help would be appreciated. Here Is my Forms.py class AddOrderItemForm(forms.ModelForm): total_cost = forms.FloatField(widget = forms.HiddenInput(), required=False) class Meta: model = Order_Items fields = ['order', 'food', 'food_size', 'quantity', 'total_cost',] widgets = { 'order' : forms.Select(attrs={'class':'form-select select2-hidden-accessible'}), 'food' : forms.Select(attrs={'class':'form-select select2-hidden-accessible'}), 'food_size' : forms.Select(attrs={'class':'form-select select2-hidden-accessible'}), 'quantity': forms.NumberInput(attrs={'class': 'form-control form-control-lg'}), } def clean(self): food_t = self.cleaned_data.get('food') food_size_t = self.cleaned_data.get('food_size') quantity = self.cleaned_data.get('quantity') food = Food.objects.get(turkmen = food_t) food_size = Food_Size.objects.get(turkmen = food_size_t,food = food) self.cleaned_data['total_cost'] = calculations.order_item_add(food,food_size,quantity) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['food_size'].queryset = Food_Size.objects.none() if 'food' in self.data: try: food = int(self.data.get('food')) self.fields['food_size'].queryset = Food_Size.objects.filter(food=food).order_by('turkmen') except (ValueError, TypeError): pass # invalid input from the client; ignore and fallback to empty City queryset elif self.instance.pk: self.fields['food_size'].queryset = self.instance.food.food_size_set.order_by('turkmen') And my CreateView: class AddOrderItemView(CreateView): model = Order_Items form_class = AddOrderItemForm template_name = 'order/add-order_item.html' success_url = '/menu/orders' def form_valid(self, form): form.instance.order = Order.objects.get(pk=self.kwargs['pk']) return super(AddOrderItemView, self).form_valid(form) -
How do I determine what "key path" arguments to provide to `prefetch_related` in Django?
Note: below, I am going to refer to the arguments supplied to prefetch_related as "key paths". I don't know if that's the best/correct term - so let me know if there's a better term to use and I will update the question. I created an advanced search page in django that searches any of a number of fields from 6 different tables (not all of which are single a direct foreign key path) and displays selected fields from all those tables in a results table. The "key paths" included are: msrun__sample msrun__sample__tissue msrun__sample__animal msrun__sample__animal__tracer_compound msrun__sample__animal__studies (Note: no fields are included in the search or display from the msrun model. That specific model class in this particular view only serves as a connection between the model classes involved in the view.) It makes a huge difference in the run time when I include a prefetch like: .prefetch_related("msrun__sample__animal__studies"), but I see no discernible difference when I include any additional prefetch "key paths". So I have a couple questions: Are there any downsides to including all of the "key paths"? (I only ask so that I can construct more views programmatically without having to store a single "prefetch path" - because I already … -
How to upload multiple images using django rest framework
I am new to django and django rest framework. I want want users to be able to post something on my web, similar to twitter. See the below model: class Post(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) content = models.CharField(max_length=255) upload_date = models.DateField(auto_now_add=True) def __str__(self): return self.content class PostImage(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name="images") image = models.ImageField(upload_to="images/") Now, as you can see user should be able to upload either text content, or images (single or multiple) or both. What I want: I want to receive data from the client side in the following format: data = { content: "Some text goes here", media: [images] } I have created the following serializer: class PostSerializer(serializers.ModelSerializer): media = serializers.ImageField() class Meta: model = Post fields = ('content', 'media') Please help me, I am unsure how to save those imgaes into database and refer to the post id. I am getting images as "bytes". -
How to Track View As YouTube Does?
Hi Everyone I Am Coding in Python & Would Like To Find Out How Does Someone Track Views Of A Video In A Post, In Python. As Youtube And TikTok Does? Any Feedback With Code Examples Would Be Greatly Appreciated. Preferably Coding In Python To Use In My Django Project -
why whene I run makemessages the locale repertoir still empty
I have some problems using the command django-admin makemessages -l es I'm running it but the locale repertory still empty and and there is not .po files generated on my locale repertory . I add this following code on my setting.py file: LOCALE_PATHS = [ os.path.join(BASE_DIR, 'locale') ] And: MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.locale.LocaleMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] I have gettext installed and I have created a repertory named locale on root of the project, I don't realy get the problem -
One Django app in a separate python package
Django==3.2.5 Please, have a look at the picture: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'clients', 'general', 'images', 'themes', 'omnibus', 'staticassets', 'categories', 'tags', 'articles', ] When I run this, I get: ModuleNotFoundError: No module named 'articles' It is predictable as Django doesn't know where to find the app. Then I tried like this: INSTALLED_APPS = [ 'dependencies.articles', ] No success. Here 'articles' is just an ordinary Django app like categouries or clients. But I'd like to move it to 'depencencies' package. Why? I'd like to organize the code structure like this for as personal preferences. If it is technically possible, please, help me cope with this problem. -
Using One Model inside another model in Django
I am Developing a E-commerce Application with Django So what I was thinking is getting the category of the Product in a separate Model and list them down in another using choice field in CharField. So Here is the code for this This is the model for getting the Categories from the user class ProjektCat(models.Model): id = models.AutoField(primary_key=True) Option_Name = models.CharField(max_length=50) Option_Number = models.IntegerField() Number_Visits = models.IntegerField(default=0) def __str__(self): return f'{self.Option_Name}' and here is the code to list those categories as a dropdown in the CharField class Software_And_Service(models.Model): id = models.AutoField(primary_key=True) Product_Name = models.CharField(max_length=100, default='') projectKats = ProjektCat.objects.all() choice = [] for i in projectKats: option = (i.Option_Number, i.Option_Name) choice.append(option) Cateogary = models.CharField( max_length=256, choices=choice) Price = models.IntegerField(default=0) Description = models.TextField(default='', max_length=5000) pub_date = models.DateField(auto_now_add=True, blank=True, null=True) image = models.URLField(default='') linkToDownload = models.URLField(default='') def __str__(self): return f'Projekt : {self.Product_Name}' But it's Showing me an Error that there is no such table in app_name.projektcat Is there is any solution for this?? -
Django Rest Framework CSRF protection not working
I am developing an Angular application with Django Rest Framework and I want to configure CSRF protection. However, I can not seem to trigger CSRF violations when doing any POST request to the backend (for testing purposes). I currently do not use CSRF protection. My settings.py: MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware' ] I configured my CORS headers such that: CORS_ALLOW_ALL_ORIGINS = True I do not use CSRF_TRUSTED_ORIGINS anywhere. Why is the CSRF protection not invoked?