Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How do I join two models in Django by id?
I have two models as shown below with just a few fields: class Query(models.Model): query_text = models.TextField(blank=True, null=True) variable = models.CharField(max_length=250, blank=True, null=True) class Statistic(models.Model): query = models.ForeignKey(Query, models.DO_NOTHING, blank=True, null=True) processing_time = models.DateTimeField(blank=True, null=True) module = models.CharField(max_length=500, blank=True, null=True) My target is to perform a JOIN using the id of the two models. The SQL query equivalent to it would be : SELECT * FROM statistic S JOIN query Q ON S.query_id = Q.id I understand select_related or prefetch_related could do the trick? I don't know which one to use to perform the join. I'd appreciate some help on that. Thanks. :) -
Where to retrieve used API key in a HTTP request
I'm trying to develop an Endpoint for uploading files that is only accessible using an API key. I use the Django REST Framework API Key and my code in viewsets.py is as follows: class UploadFileViewset(viewsets.ModelViewSet): model = File queryset = File.objects.all() serializer_class = FileSerializer parser_classes = [MultiPartParser] # not sure whether required permission_classes = [HasAPIKey] def create(self, request): serializer = FileSerializer(data=request.data) # converts to JSON if serializer.is_valid(True): # validating the data model_instance = serializer.save() # saving the data into database I'd like to be able to pick out various attributes from request, for example, its source (in this case the API Key). When I debug I can't find the API key in the request. Is it because it's actually not present in the request, but is already "eaten up" beforehand in Django's middleware? I'm a bit confused why I can't retrieve it, and if I can actually get a source from the http request at all. -
Django filter after using select_related query
Going through a troble to filter that i used for select_related This is my model for Purchase: class Purchase(models.Model): amount = models.FloatField(default=1) entry_by = models.ForeignKey( User, on_delete=models.SET_NULL, related_name='ledger_entry_by', ) is_cash = models.BooleanField(default=False) and this is my model of Consume: class Consume(models.Model): amount = models.FloatField(default=1) consumed_by = models.ForeignKey( User, on_delete=models.SET_NULL, related_name='consume_entry_for', ) This is my query user_wise_cost = User.objects.annotate( difference=ExpressionWrapper( Coalesce(Sum('ledger_entry_by__amount'), Value(0)) - Coalesce(Sum('consume_entry_for__amount'), Value(0)), output_field=FloatField() ) ) The above query is working great following my requirement. I want to calculate only the amount that cash paid, i mean, if a entry is_cash=True, it will be calculated My requirement was: for example, A user Purchased 500 USD and he consumed 550 USD, that is mean, he needs to pay another 50 USD another user purchased 440 USD but he consumed 400 USD, that is mean, he will get refund 40 USD. another user example can be: a user didn't purchase anything but he consumed 300 USD, so he needs to pay 300 USD. also if a user didnt purchase anything or consumed anything, yet his data needs to show like 0. Above all the requirement was successfully achieved by that query, there is no issue at all but currently, it's calculating … -
Django Template is saying the user is not authenticated even when it says it is in the views
As the title states I have a Django template that is not authenticating. In my html I have a basic if that says: {% if request.user.is_authenticated %} But that is being evaluated to false when I login, but if I refresh the page it lets me in. Also in my part of my login views I have: if User.object.filter(username=username).exists(): user = User.objects.get(username=username) authenticate(request, username=username) print(request.user.is_authneticated) login(request, user) print(request.user.is_authenticated) return redirect(next_url) And When I check the out puts they print out as: False True Yet in the html it evaluates to False, but when I refresh the page it says it's true. (Also I know I'm authenticating with only username that's fine for the context I'm working in). Also the main issue I'm having is that it failes to login depending on the url. Ex: If I hit the website with base_url I can login as normal no problem If I hit the website with base_url/welcome I login as normal, but then I encounter the problem I described. Hopefully there is enogh info/context to give me a direction of what to do. Sorry I can't give more code -
How can I change the workflow of Django Admin
I am a beginner of Django.I want to use Django Admin to do the following things: 1-upload a excel file 2-read the header of the excel file 3-choose a part of the header to save to the database.(a list of the header with checkbox and submit button) 4-show the result to the user How can I finish the job by Django Admin?I think I should change the default workflow of the Django Admin,but how to do so? -
Django - What does objects.get return
Sorry if this seems like a really stupid question. I am building an app using Django, and at some point I am accessing the db using db.objects.get(var = val) But my question is what type object does this method return? And hw can I access the data in it? Like as a dict, list or sth else? I apologize if it is a duplicate. -
Does django cache files in MEDIA_ROOT by default?
I am using a clean install of Django 3 on a Docker container development server. I have the following settings.py: MEDIA_ROOT = '/vol/web/media/' MEDIA_URL = '/media/' And in urls.py: urlpattens = [ ... ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) When I upload a file using models.FileField() it displays fine via 127.0.0.1:8000/media/myfile.txt. However, when I shell into the server to find it /vol/web/media is empty. I would expect the file I upload to be in this directory, per the docs, but it is not. I have confirmed the following: 127.0.0.1:8000/media/myfile.txt returns myfile.txt even when browser cache is cleared. 127.0.0.1:8000/media/notmyfile.txt returns /vol/web/media/notmyfile.txt does not exist, so the server appears to be configured correctly I have no CACHE settings set explicitly in settings.py. What could be going on here? Does Django cache MEDIA_ROOT somehow by default? -
Dynamically Change Django Form's Fields
In the django custom registration form I have ChoiceField see in the code below but what I want is to change the fields according to the ChoiceField options. for an example if the ChoiceField is selected as Student then I want to hide the "email field" or might add extra field. I know i can do this with JavaScript but i want to change from the form. class Signup_Form(UserCreationForm): def __init__(self, *args, **kwargs): super(Signup_Form, self).__init__(*args, **kwargs) # below changing on the fields of this form. self.fields['first_name'].label = "First Name" self.fields['last_name'].label = "Last Name" self.fields['email'].label = "Email" SIGNUP_USERS_TYPES = ( ('Student', 'Student',), ('Admin', 'Admin',),) user_type = forms.ChoiceField(choices = SIGNUP_USERS_TYPES, required=True, label="Sign-up as :",) class Meta: model = User fields = ['user_type', 'first_name', 'last_name','email', 'username', 'password1', 'password2' ] -
Is there a way to take JSON from swagger 2.0 in views and convert it into HTML and send it to the template in Django?
I want to use some JSON that coming from a Swagger 2.0 generated website and parse it to send it back to a template page in my Django project. I'm asking if there is a simple way to do it, like an import (I searched but without result), thanks. def swagger_documentation(request): reply = requests.get("http://example.com:5005/swagger.json") content = reply.json() <!-- Transform content into HTML here --> data = ? return render(request, 'features/documentation/doc.html', data) (doc.html) {% extends 'layout/master.html' %} {% load static %} {% block content %} I want to show it here {% endblock %} -
Django model queries; how to join tables on foriegnkey
models.py class Person(models.Model): email = models.CharField(max_length=30) pwd = models.CharField(max_length=30) type = models.CharField(max_length=30) class user_details(models.Model): name = models.CharField(max_length=30) gender = models.CharField(max_length=30) phoneno = models.CharField(max_length=13) u_id = models.ForeignKey('Person', on_delete=models.CASCADE) class User_locations(models.Model): country = models.CharField(max_length=30) state = models.CharField(max_length=30) district = models.CharField(max_length=30) locality = models.CharField(max_length=30) u_id = models.ForeignKey('Person', on_delete=models.CASCADE) i want to query a Person with Person.type='A' and User_locations.locality='B'. i aslo want access name of a person with Person.name in the template. i now use this code in views.py person = Person.objects.filter(type='A', user_locations__location='B') what should a add to this code to access name of the person with person.name in the html template? -
Django-Rest-Framework: No Attribute HelloViewSet
I am trying to build a simple REST API. I tried adding a viewset, somehow I get an error that there is no such attribute. If I remove the viewset and just run using the APIView, it loads just fine. I am stuck. What could be the problem? What should I do to make it work? Here's the rest_profiles.views.py FILE: from django.shortcuts import render from rest_framework import viewsets from rest_framework.views import APIView from rest_framework.response import Response from rest_framework import status from .serializers import HelloSerializer # Create your views here. class HelloApiView(APIView): '''Test API View''' serializer_class = HelloSerializer def get(self, request, format=None): '''Returns a list of API features''' an_apiview = [ 'Uses HTTP methods as functions (get, psot, put, patch, delete)', 'Similar to Django View', 'Mapped manually to URLs' ] return Response({'message': 'Hello from HelloAPIVIew', 'an_apiview': an_apiview}) def post(self, request): '''Create Hello Message''' serializer = HelloSerializer(data=request.data) if serializer.is_valid(): name = serializer.data.get('name') message = 'Hello {0}'.format(name) return Response({'message': message}) else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) def put(self, request): '''Handles Updates''' serializer = HelloSerializer(data=request.data) return Response({'message': 'put'}) def patch(self, request, pk=None): '''Handles partial Updates''' serializer = HelloSerializer(data=request.data) return Response({'message': 'patch'}) def delete(self, request, pk=None): '''Handles deleting items''' serializer = HelloSerializer(data=request.data) return Response({'message': 'delete'}) class HelloViewSet(viewsets.ViewSet): … -
how to assign pointfield to current user location using geolocation API
i'm new to geodjango i want to make real world gis project with geodjango to find locations i tried this class Place(models.Model): user= models.ForeignKey(Account,on_delete=models.CASCADE) address = models.CharField(max_length=100) slug = models.SlugField(unique=True,blank=True,null=True) description = models.TextField() location = models.PointField(srid=4326) views.py class PalceCreateView(CreateView): queryset = Place.objects.all() def form_valid(self,form): lat = self.request.POST['lat'] lon = self.request.POST['long'] coords = Point(lat,lon) form.instance.location = coords form.save() return super(PalceCreateView,self).form_valid(form) my forms.py class PlaceForm(forms.ModelForm): class Meta: model = Place fields = [ 'name','description','location','city','tags' ] read_only_fields = ['location'] my template <form enctype="multipart/form-data" method="post"> {% csrf_token %} <input type="hidden" name="lat" id="lat"> <input type="hidden" name="long" id="long"> {{form}} <input type='submit' value='submit'> </form> <script> navigator.geolocation.getCurrentPosition(function(location) { lat = location.coords.latitude; long = location.coords.longitude; document.getElementById('lat').val = lat document.getElementById('long').val = long }); </script> but when i submit the form it will raise this error Invalid parameters given for Point initialization. how to assign to location field thanks i'm new to geodjango if someone can recommend me an open source project i appreciate it -
How to display with javascript django project's image without static path?
js code on Windows: f_name = '06-55.jpg'; imga = '<img src="static/img/'+f_name+'" >'; $('#loaded').append(imga2); image is located at: /static/img/06-55.jpg On Windows machine it works. On linux I have same paths, but js can't find image. I'm missing something or It's just stupid mistake somewhere? -
pass if code in django, if something in data -> pass
my code is take reques.body and into data var. and if data dic in username or email or telephone then checking password. and if password collect i return token. but my code is just pass all if. i think if @ in dic it is can check key in dic i used httpie and send password and telephone or email or username. but all pass. i dont know what i mistake. plz help me! class UserLoginView(View): def post(self, request): data = json.loads(request.body) check_password = int(data['password']) check_username = 'username' if check_username in data: login_username = data['username'] login_user = User.objects.filter(username=login_username) if login_user is None: return JsonResponse({'message':'have not this ussername User'}, status = 400) elif login_user is login_username: get_user = User.objects.get(username=login_username) if check_password is not get_user.password: return JsonResponse({'message':'Not collect password'}, status = 400) else: encoded_token = jwt.encode({'user': login_user}, 'wecode', algorithm='HS256') return JsonResponse({'token':encoded_token}, status = 200) elif 'email' in data: login_email = data['email'] login_user = User.objects.filter(email=login_email) if login_user is None: return JsonResponse({'message':'have not this emain User'}, status = 400) elif login_user is login_email: get_user = User.objects.get(email=login_email) if check_password is not get_user.password: return JsonResponse({'message':'Not collect password'}, status = 400) else: encoded_token = jwt.encode({'user': login_user}, 'wecode', algorithm='HS256') return JsonResponse({'token':encoded_token}, status = 200) elif 'telephone' in data: … -
When I run `./manage.py runserver`, it starts two processes. How to enable interprocess data sharing and interprocess calls?
I also use apscheduler lib inside the Django webserver handler. I want to create a single instance of apscheduler and communicate all calls to it. Is the best solution to create a different process specifically designated for apscheduler instance? A similar questions are [1] and [2]. [1] How to enforce only one running instance of a process in python Django framework? [2] Make sure only one worker launches the apscheduler event in a pyramid web app running multiple workers -
How to iterate iterate over a list a filter it according to a second list
I have a list of videos that belong to courses. I want to display those videos in a template grouped by courses: first all videos from a course, then a separator and all the videos of the next course. I already have a query_set grouped by course but I cannot find out how to display them separated in my html file. Any hints? Ideas? -
how to include template with context in navbar?
In base.html I have included navbar {% include 'partials/navbar.html' %}, now I need to do context for navbar.html. I trying to make context for navbar.html in this way: view.py def unread_conversation(request): if request.user.is_authenticated: conversations_all = Conversation.objects.filter(Q(starter=request.user) | Q(receiver=request.user)) for conversation in conversations_all: unread = Message.objects.filter(Q(conversation_id=conversation.pk) & Q(seen=False) & ~Q(user=request.user)) context = { 'unread': unread } return render(request, 'conversations/unread_message.html', context) else: messages.error(request, 'register please') return redirect('register') unread_message.html {% if unread %} <span>You have new message</span> {% endif %} navbar.html {% include 'conversations/unread_message.html' with unread=unread %} but it does not work for me, can you correct my way or offer me a better way of this? -
How to ensure idempotency in a Django REST API?
Say, I'm building a REST API based on Django/DRF and PostgreSQL. I want all GET, PUT, DELETE endpoints to follow the best practices and be idempotent. How can I ensure/verify that this is true? -
How to set Django model default value equal to result of a query
I'm quite new at Django, and trying to create a model where det default value for Foreign Keys user and department are set to the correct values for the logged in user. Normally I use the request object and queries the database, but in the model definition I don't know how to do this. I suppose a path forward is to make default value a function and make the query in the function, but I am stuck. Any help are greatly appreciated . Here is an example of my code: from django.contrib.auth import get_user_model from django.db import models from another_app.models import Department, DepartmentPermissions class Article(models.Model): header = models.CharField(max_length=200) text = models.CharField(max_length=800) owner = models(get_user_model(), related_name='owner_article', on_delete=models.PROTECT) department = models.ForeignKey(Department, on_delete=models.CASCADE) #here I want it defaulted to DepartmentPermissions.objets.get(user= <logged in user>)[0].department -
How to design a model and its child django
How to design a model in django for storing below JSON values in a single model class Bus(models.Model): source = models.CharField(max_length=200) destination = models.CharField(max_length=200) type= models.CharField(max_length=200) price=models.FloatField() I need to accept below json to accept and store in same table if i can use ListField , then how it will be for connections { "source": "delhi", "destination": "pune", "type": "Economy", "price":300.0, "Connections": [ { "source": "lon", "destination": "liverpool", "type": "luxury", }, { "source": "banglur", "destination": "cochin", "type": "luxury", } ], } -
How to have Django templates display slugs
Hi guys i am new to django...i been watching youtube videos and reading books on Django but am still struggling with templates. I am working on a ecommerce project and i would love a bit of help with templates. So i want my template to display a list of categories as links on a sidebar. I have defined a slug field in my category models and i have managed to map a url...but i am still not getting a list of categories on my index page sidebar. This is my url pattern and this is working perfect. When i click 127.0.0.1.000/food it's working (food is a category) path('<slug:category_slug>/', views.category, name='category'), the view function def category(request, category_slug): """Defines category views""" categories= get_object_or_404(Category, slug= category_slug) context = {'categories': categories} return render(request, "categories_list.html", context) This is the categories_list.html template that i need help with <h3> Shop by Category </h3> {% if category in categories %} <li> <a href ="{{category.slug}}"> {{category.name}}</a> </li> {% endif %} My wish is to have the categories displayed on the sidebar of my index page as links. I have used {% include 'category_list.html' %} on my index page template, and its only displaying the Shop by Category heading instead … -
Get List of Categories on the basis of foreign model in django
I've two models as below. class Category(models.Model): title = models.CharField(max_length=55) class Meta: verbose_name = 'Food Category' verbose_name_plural = 'Food Categories' def __str__(self): return self.title class FoodItem(TimeStampWithCreator): CATEGORY_CHOICES = ( ('takeway', 'Takeaway'), ('dine_in', 'Dine In'), ('function', 'Function'), ) type_menu_select = models.CharField(max_length=20, choices=CATEGORY_CHOICES, default='takeway') category = models.ForeignKey(FoodCategory, on_delete=models.CASCADE) i want to filter all the categories containing takeaway, I've no idea how to achieve this -
DJango user not logging out
I'm new to DJango and I'm trying to make a user auth. My login is working fine but my user isn't logging out. My Logout view is: from django.contrib.auth import logout from django.contrib.auth.models import User class LogoutView(generic.View): @staticmethod def get(request): if User.is_authenticated: # Debug statement print('if') logout(request) return redirect('login') else: print('ekse') return redirect('index') My url is working fine because when i go to /logout/, My debug statement executes but if User.is_authenticated: always returns an object(true). How can I resolve this issue. Thanks -
Same query set, different result in django
I get a different result when I filter another time with the same filters. This code is part of the get_queryset() of a class that inherits ListAPIView. validity_filters = Q( ( ( Q(display_publisher_group__publishers__id__exact=98) | Q(display_publisher_group__isnull=True) ) & ( ~Q(blacklist_publisher_group__publishers__id__exact=98) ) ) ) campaigns = Campaign.objects.filter(validity_filters) print(1, campaigns.distinct().count()) campaigns = campaigns.filter(validity_filters) print(2, campaigns.distinct().count()) The output is: 1 33276 2 33275 -
App 'category' doesn't provide model 'category'
Django==3.0.6 class Category(CommentMixin, TitleMixin, SlugMixin, models.Model): pass from category.models import Category class Post(TitleMixin, SlugMixin, DescriptionMixin, models.Model): ... category = models.ForeignKey(Category, on_delete=models.PROTECT, related_name='blog_posts') The database has been dropped and recreated. All migrations have been deleted. In settings.py 'post' and 'category' are added. When making migrations: ValueError: The field post.Post.category was declared with a lazy reference to 'category.category', but app 'category' doesn't provide model 'category'. Could you help me understand what is going on here?