Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Error creating merged queries with Q() and filter() in a viewset with djangoORM
I am trying to create a filter with multiple elements in a queryset for a view. I am overwriting the get_queryset method to fetch the results according to a user role. I am using Q() and works perfectly when i try to a single filter, for example: Cohort.objects.filter(Q(mode="p") ) or this: Cohort.objects.filter(Q(participant__user__id=self.request.user.id)) Both works perfectly filtering the queryset, but when i combine then as this... Cohort.objects.filter( Q(participant__user__id=self.request.user.id) | Q(mode="p") ) The queryset multiply the number of registries and bring to many results, repeated results, to the point that the request fails. This is the complete method: def get_queryset(self): user_role = self.request.user.rol if user_role == '0': base_qs=Cohort.objects.all() elif user_role == '1': base_qs=Cohort.objects.filter( Q(participant__user__id=user.id) ) elif user_role == '2': base_qs = Cohort.objects.filter( Q(participant__user__id=self.request.user.id) | Q(mode="p") ) scope = self.request.query_params.get('isNext', None) if scope is None: return base_qs elif scope: return base_qs.filter(fecha_final > datetime.date.today()) return base_qs.filter(fecha_final < datetime.date.today()) I don not recieve any error messages. checking the documentation this is the way to use Q but something is happening. What am i doing wrong? I am using Django==2.2.4 djangorestframework==3.10.2 -
sync Django urls with Nginx location matcher
As I'm adding new sever endpoints (Django) I need to manually update the server location matcher in the proxy server (Nginx) Is there an automatic way to sync nginx.conf with urls.py? -
ModuleNotFoundError: No module named 'django.contrib.auth.decoraters'
I am trying to create a login and logout page for my sample project and have coded all logic up. The tutorial I was following used the following code from django.shortcuts import render from basic_app.forms import UserForm from django.contrib.auth import authenticate,login,logout from django.http import HttpResponseRedirect,HttpResponse from django.urls import reverse from django.contrib.auth.decoraters import login_required # Create your views here. def index(request): return render(request,'basic_app/index.html') def register(request): registered = False if request.method == 'POST': user_form = UserForm(data=request.POST) if user_form.is_valid(): user = user_form.save() user.set_password(user.password) user.save() registered = True else: print(user_form.errors) else: user_form = UserForm() return render(request,'basic_app/registration.html', {'user_form':user_form, 'registered':registered }) @login_required def special(request): return HttpResponse("You are logged in!") @login_required def user_logout(request): logout(request) return HttpResponseRedirect(reverse('index')) def user_login(request): if request.method == 'POST': username = request.POST.get('username') password = request.POST.get('password') user = authenticate(username=username,password=password) if user: if user.is_active: login(request,user) return HttpResponseRedirect(reverse('index')) else: return HttpResponse("Account Not Active") else: print("Someone tried to login and failed") print("Username:{} and password: {}".format(username,password)) return HttpResponse("Invalid login details supplied") else: return render(request,'basic_app/login.html',{}) The error I am getting is this from django.contrib.auth.decoraters import login_required ModuleNotFoundError: No module named 'django.contrib.auth.decoraters' -
Django Image field doesn't update image
I recently got a problem that my django image field in my django app doesn't update the image after pressing "Post". In admin panel everything works fine. Maybe I missed something... Let me know. models.py from django.db import models from django.utils import timezone from django.contrib.auth.models import User from django.urls import reverse class Post(models.Model): title = models.CharField(max_length=200) content = models.TextField() date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) categories = models.ManyToManyField('Category', related_name='posts') image = models.ImageField(upload_to='images', default="images/None/no-img.jpg") def __str__(self): return self.title def get_absolute_url(self): return reverse('post-detail', kwargs={'pk': self.pk}) class Category(models.Model): name = models.CharField(max_length=20 ) views.py from django.shortcuts import render, get_object_or_404 from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin from .models import Post from django.contrib.auth.models import User from django.views.generic import ListView, DetailView, CreateView, UpdateView, DeleteView def home(request): content = { 'posts': Post.objects.all() } return render(request, 'blog/home.html', content) def blog_category(request, category): posts = Post.objects.filter(categories__name__contains=category).order_by('-date_posted') content = { 'category': category, 'posts': posts } return render(request, 'blog/blog_category.html', content) #<--(didn't add content block) bug found 05.11.19 def upload_pic(request): if request.method == 'POST': form = ImageUploadForm(request.POST, request.FILES) if form.is_valid(): m = ExampleModel.objects.get(pk=course_id) m.model_pic = form.cleaned_data['image'] m.save() return HttpResponse('image upload success') return HttpResponseForbidden('allowed only via POST') ... class PostCreateView(LoginRequiredMixin, CreateView): model = Post fields = ['title', 'content', 'categories', 'image'] def form_valid(self, form): form.instance.author = … -
How can I get into folders and out of them in cmd?
I have saw a question about activating V-Env in Django (Virtual Environment), I took action with the first answer. Here's the link: How to activate Virtual Environment in DJango The answer is for "Shariful Islam"... The first step was this: cd C:\Users\User\Desktop\UserDjangoProject> pip install virtualenv I wasn't able to operate this command in CMD (as he said at the answer's heading) Can anyone help me in that? -
Django model form field language is not changing
I am using django 2.2. and python 3.6. I have a template and crispy form inserted in template. This form is created from model. There is an imagefield field in model. photo = models.ImageField(upload_to="staff/", null=True, blank=True, verbose_name=_("Fotoğraf")) The crispyform is creating the field in the template but the language shown in the field is english. But i want to show turkish language. The Choose File and Browse should be turkish. So i changed settings.py as; LANGUAGE_CODE = 'tr-tur' But still it is written Choose File and Browse in the field in the page. You can see in the screenshot that everything is Turkish language except "Choose File" and "Browse". -
How to store mutiple time in django fields?
I have a situation like this where I have to store multiple values for a single row. For example, let us say I am creating a doctor's appointment model to store the doctor's name and available timing for that particular doctor. doctor_name | available_timing ABC | 7:00-11:00, 17:00-22:00 I am thinking about using JSON field like this from django.db import models from django.contrib.postgres.fields import JSONField class DoctorAppointment(models.Model): name = models.CharField(max_length=100) slug = models.SlugField(max_length=100) available_timing = models.JSONField() Is there any better approach to deal with a problem like this? -
how can i get redirect url using function based view?
I have 2 views: display_quote and quoteline_update After updating a quoteline, I want to redirect to "display_quote" (quote to which the quoteline updated belongs). I obtain the error:Reverse for 'display_quote' with no arguments not found. 1 pattern(s) tried: ['\^display_quote/\(\?P(?P[^/]+)\\d\+\)\$$'] Exception Type:NoReverseMatch Views: def display_quote(request, pk): items_quote = Quote.objects.filter(pk=pk) items_quote_line = LineQuote.objects.all().filter(num_quote_id=pk) form = QuoteLineForm(request.POST or None) if request.method == "POST": if form.is_valid(): form.save() total = 0 for item in items_quote_line: total = total + item.get_price() context = {'items_quote': items_quote, 'items_quote_line': items_quote_line, 'form': form, 'total':total } return render(request, 'quote/quote_display.html', context) def quoteline_update(request, pk): model = QuoteLine cls = LigneDevisForm item = get_object_or_404(model, id=pk) if request.method == "POST": form = cls(request.POST, instance=item) if form.is_valid(): form.save() return redirect('display_quote') else: form = cls(instance=item) return render(request, 'quote/quoteline_update.html', {'form': form}) -
how to make the Serialization of a Dict of models
I have to serialize a Dict of Models with django rest framework /Serializers.py : class MapFilterSerializer(serializers.Serializer): bedroom_1 = ProjectsSerializer(many=True) bedroom_2 = ProjectsSerializer(many=True) bedroom_3 = ProjectsSerializer(many=True) bedroom_4 = ProjectsSerializer(many=True) /views.py : class MapFilter(generics.ListAPIView): .... return selected_Projects where selected_projects have this struture: { bedroom_1 : ProjectModelQuerySet, bedroom_2 : ProjectModelQuerySet, bedroom_3 : ProjectModelQuerySet, bedroom_4 : ProjectModelQuerySet, } where ProjectModelQuerySet is a queryset of the model Project How I should achieve this using the Project model serializer -
Need Proper DJANGO ORM Filter for DATE in Single Quotes
Here I am passing 2 dates aandb from my browser. I need to filter data by those dates. a = request.GET.get('date1') b = request.GET.get('date2') TestDB.objects.filter(start_date__range=(a,b)).order_by('-name').query SELECT "TestFilter_testdb"."id", "TestFilter_testdb"."name", "TestFilter_testdb"."start_date", "TestFilter_testdb"."end_date" FROM "TestFilter_testdb" WHERE "TestFilter_testdb"."start_date" BETWEEN 2019-11-04 AND 2019-11-05 ORDER BY "TestFilter_testdb"."name" DESC Here the SQL Query is like this "start_date" BETWEEN 2019-11-04 AND 2019-11-05 but Actually I need the passing date in single quotes like this "start_date" BETWEEN '2019-11-04' AND '2019-11-05'" -
Django Templates: Use context variables inside `{% include ... with ... }` statement
I want to implement variables from context inside an include statement. Code: views.py historic_trends_parameters = {'kpi':'kpi_name', 'dimension':'dimension_name'} context = {'historic_trends_parameters':historic_trends_parameters} return render(request, 'homepage.html', context=context) The template i want to put in the include statement: myTemplate.html <div class='MyClass'> <object class='tableauViz' width='{{ width }}' height='{{ height }}' style='display:none;'> <param name='show_tabs' value='{{ show_tabs }}' /> <param name='filter' value='{{ filter_values }}' /> </object> </div> homepage.html // some code <div> {% include "myTemplate.html" with width='700' height='400' show_tabs='yes' filter='KPIParameter=historic_trends_parameters.kpi' %} </div> // some more code Results: When I activate django and go to the homepage this is what i see in the Page Source: <div class='MyClass'> <object class='tableauViz' width='700' height='400' style='display:none;'> <param name='show_tabs' value='yes' /> <param name='filter' value='KPI Parameter=historic_trends_parameters.kpi' /> </object> </div> I didn't find a way to pass the historic_trends_parameters.kpi value from the context correctly. My desired outcome should be: <div class='MyClass'> <object class='tableauViz' width='700' height='400' style='display:none;'> <param name='show_tabs' value='yes' /> <param name='filter' value='KPI Parameter=kpi_name' /> </object> </div> Meaning historic_trends_parameters.kpi turns to 'kpi_name' -
Uploading file to website with android - site cant be reached
I am trying to upload a file in a website using the django framework. When i use my laptop i have no problem at all, but when trying to upload the exact same file with my android device i get 'This site cant be reached' views.py from django.shortcuts import render from django.http import HttpResponse from django.core.files.storage import default_storage from .Uploaded_files import C_Convert as conv from django.utils.datastructures import MultiValueDictKeyError def main_view(request): return render(request, 'main.html') def get_file(request): if request.method == 'POST': print(1) try: uploaded_file = request.FILES['file'] except MultiValueDictKeyError: return HttpResponse('<h1>Error</h1>') default_storage.save('CSD_Project/Uploaded_files/'+uploaded_file.name, uploaded_file) result = conv.convert(uploaded_file.name) return HttpResponse('<h1>%s</h1>'%result) else: return HttpResponse('<h1>Error</h1>') urls.py from django.contrib import admin from django.urls import path from .views import get_file,main_view urlpatterns = [ path('admin/', admin.site.urls), path('', main_view), path('get_file/', get_file) ] main.html <!DOCTYPE html> <html lang="en" style = "background-color: darkslategrey"> <head> <meta charset="UTF-8"> <title>HY100 Tests</title> </head> <body> <div style="text-align: center;"> <form action="get_file/" method="POST" enctype=multipart/form-data> {% csrf_token %} <input type="file" name="file"> <button style="color: white; background-color: #222222; padding: 15px 32px; font-size: 15px;" class="button">Submit file</button> </form> </div> </body> </html> -
Keyerror from celery task delay
Following the celery getting started with Django instructions, I am able to run tasks, but not run the same task asynchronously using delay(). I added the following requirements to my Django project: celery==4.3.0 redis==3.3.11 django-celery-results==1.1.2 psycopg2==2.7.3.1 django-cors-headers~=3.1.0 Created this celery.py in the pop_model project directory: from __future__ import absolute_import, unicode_literals import os from celery import Celery # set the default Django settings module for the 'celery' program. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'pop_model.settings.local') app = Celery('pop_model') # namespace='CELERY' means all celery-related configuration keys # should have a `CELERY_` prefix. app.config_from_object('django.conf:settings', namespace='CELERY') # Load task modules from all registered Django app configs. app.autodiscover_tasks() @app.task(bind=True) def debug_task(self): print('Request: {0!r}'.format(self.request)) Inserted this code in the project init.py: from __future__ import absolute_import, unicode_literals # This will make sure the app is always imported when # Django starts so that shared_task will use this app. from .celery import app as celery_app __all__ = ('celery_app',) Configured cors in the project settings and added these settings: CELERY_BROKER_URL = 'redis://localhost:6379' CELERY_RESULT_BACKEND = 'django-db' # defined in django_celery_results CELERY_ACCEPT_CONTENT = ['json'] CELERY_RESULT_SERIALIZER = 'json' CELERY_TASK_SERIALIZER = 'json' I can start redis, then run celery using these commands: export DJANGO_SETTINGS_MODULE=pop_model.settings.local celery worker -A pop_model --loglevel=info In a python3 shell, I get these results: >>> … -
Image files are not accessable inside aws s3 bucket in browser
error: This XML file does not appear to have any style information associated with it. The document tree is shown below. <Error> <Code>AccessDenied</Code> <Message>Access Denied</Message> <RequestId>AEAD5281D0CECD9C</RequestId> <HostId> JAeTP/f1wVEh86IYn9709nJ6+CaVE+7/AB5GDwwkQimiubeMZW6mz6pZsfZs4hODpKeqkjJeb4Y= </HostId> </Error> Bucket Policy: <Error> <Code>AccessDenied</Code> <Message>Access Denied</Message> <RequestId>AEAD5281D0CECD9C</RequestId> <HostId> JAeTP/f1wVEh86IYn9709nJ6+CaVE+7/AB5GDwwkQimiubeMZW6mz6pZsfZs4hODpKeqkjJeb4Y= </HostId> </Error> CORS configuration: <?xml version="1.0" encoding="UTF-8"?> <CORSConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/"> <CORSRule> <AllowedOrigin>*</AllowedOrigin> <AllowedMethod>GET</AllowedMethod> <MaxAgeSeconds>3000</MaxAgeSeconds> <AllowedHeader>Authorization</AllowedHeader> </CORSRule> </CORSConfiguration> Here i am trying to upload image file to aws s3 bucket. As i can see i am getting my image urls in database. <QuerySet [{'bio': 'ddd', 'logo': 'https://maxfitness-storage.s3.amazonaws.com/media/newFile_hV4hFpU.jpeg', 'coach_id': 1, 'id': 22, 'banner': 'https://maxfitness-storage.s3.amazonaws.com/media/newFile_EPSIeyM.jpeg'}]> But when i am checking my s3 bucket it is showing bucket is empty. And when i am going to https://maxfitness-storage.s3.amazonaws.com/media/newFile_hV4hFpU.jpeg (getting from database) url it is showing above error shared on the top. Please have a look. -
Django proper way to save global API client instance variable
How to store some API client instance and make it available across the whole project. API client instance - is some AppApi() and I need to call it's methods in different views (and even apps) from whole django project. As for me, there are two ways: create a global variable in some core django app core/apps.py module; create singleton wrapper; What is the best and proper way to do in this case? -
Django Hostname in Testing
I am wondering if there is a way to obtain the hostname of a Django application when running tests. That is, I would like the tests to pass both locally and when run at the staging server. Hence a need to know http://localhost:<port> vs. http://staging.example.com is needed because some tests query particular URLs. I found answers on how to do it inside templates, but that does not help since there is no response object to check the hostname. How can one find out the hostname outside the views/templates? Is it stored in Django settings somewhere? -
Django related model field querying (mutual friends)
I have a friendship model: class Friendship(models.Model): user = models.ForeignKey( Account, on_delete=models.CASCADE, related_name="friend1", null=True, blank=True) other_user = models.ForeignKey( Account, on_delete=models.CASCADE, related_name="friend2", null=True, blank=True) date_created = models.DateTimeField(auto_now=True) objects = FriendshipManager() class Meta: verbose_name = "friendship" verbose_name_plural = "friendships" unique_together = ("user", "other_user") def __str__(self): return f'{self.user} is friends with {self.other_user}.' and this function to return all users who are mutual friends of two accounts def mutual_friends(self, account1, account2): mutual_friends = Account.objects.filter( Q(friend2__user=account1) & Q(friend2__user=account2)) return mutual_friends Based on my (limited) understanding of how the query api works, I would think this should return all users who have a "friend2" relationship with the Friendship table where the "friend1" user is either account1 or account2. I'm still getting used to querying with django, so if someone can let me know what I'm doing wrong that'd be great. Thanks! -
Django slow execution of python code (no ORM)
I am seeing massively degraded DRF performance for simple python code when running under an API vs. standalone. For e.g., running the python code standalone. I am loading a user file, converting it into a custom object and running some validations on it. xlsname = 'user_file.xlsx' dash = Dashboard(xlsname,logging.ERROR,create_copy=True) #loading user file Load time: 1.828125 dash.validate() #validate user file Validation time: 0.203125 Now when running the same code under a simple DRF function view: #views.py @api_view(['GET']) def load_and_validate(request): xlsname = 'user_file.xlsx' dash = Dashboard(xlsname, logging.DEBUG, create_copy=True) dash.validate() return Response({"message": "{} loaded".format(xlsname)}) My response times are: Load time: 1.96875 #this is in line with standalone execution **Validation time: 5.21875 # this is 2500x slower than standalone!** The validation time for my file is now 2500x slower than standalone! I am not even using any ORM yet so there are no queries. Everything is loaded into the memory and executed from there. What may be causing this and how can I diagnose it? -
Postgresql ArrayField vs ForeignKey? which one is performant?
I want to design a phone book application that each contact can have multiple numbers. There is two db designs: use contact foreign key in each number. store numbers in an ArrayField inside each contact. which solution is more performant in production and why? Thanks in advance. -
URL blocked: This redirect failed because the redirect URI is not white-listed in
I try to login with facebook using django but it shows that error.. enter image description here -
Where is the best course of Python with Django for free?
Can u send me someone good course to learn python with Django? I have good knowledge with Python, but Django is a bit hard, can help me?? -
How to use update_or_create with defaults argument
I have the model League class League(models.Model): league = models.IntegerField(primary_key=True) league_name = models.CharField(max_length=200) country_code = models.ForeignKey("Country",null=True, on_delete=models.SET_NULL) season = models.ForeignKey("Season", null=True,on_delete = models.SET_NULL, to_field = "season") season_start = models.DateField(null = True) season_end = models.DateField(null = True) league_logo = models.URLField(null = True) league_flag = models.URLField(null = True) standings = models.IntegerField(null=True) is_current = models.IntegerField(null=True) I created objects from this model. After it i needed to add some additional fields to League model after adding those fields League object became so class League(models.Model): league = models.IntegerField(primary_key=True) league_name = models.CharField(max_length=200) country_code = models.ForeignKey("Country",null=True, on_delete=models.SET_NULL) season = models.ForeignKey("Season", null=True,on_delete = models.SET_NULL, to_field = "season") season_start = models.DateField(null = True) season_end = models.DateField(null = True) league_logo = models.URLField(null = True) league_flag = models.URLField(null = True) standings = models.IntegerField(null=True) is_current = models.IntegerField(null=True) cover_standings = models.BooleanField(null=True) cover_fixtures_events = models.BooleanField(null=True) cover_fixtures_lineups = models.BooleanField(null=True) cover_fixtures_statistics = models.BooleanField(null=True) cover_fixtures_players_statistics = models.BooleanField(null=True) cover_players = models.BooleanField(null=True) cover_topScorers = models.BooleanField(null=True) cover_predictions = models.BooleanField(null=True) cover_odds = models.BooleanField(null=True) lastModified = models.DateTimeField(auto_now=True) I did migrations and added these fields to db schema. Now i want to add to these added fields values. I read about update_or_create method and tried to use it for updating League model objects leagues_json = json.load(leagues_all) data_json = leagues_json["api"]["leagues"] for item in data_json: … -
How do you allow input to be an object selection from model but also free text input in a django form?
I am trying to have a field in a form that allows users to select objects from a Model and also allows free text input. I am using django-autocomplete-light. Although it works great for selecting choices from the model, I can't get it to allow free text input without creating new objects before the form is submitted. Before someone marks this as duplicate, I did read this question but it did not guide me into a solution. Here's my models.py: class Person(models.Model): name = models.CharField(max_length=255, blank=True, null=True) My forms.py: class NameForm(forms.ModelForm): name = forms.ModelChoiceField( queryset=Person.objects.all(), widget=autocomplete.ModelSelect2(url='myapp:name-autocomplete') ) class Meta: model = Person fields = ['name',] My views.py: class PersonAutoComplete(autocomplete.Select2QuerySetView): def get_queryset(self): qs = Person.objects.all() if self.q: qs = qs.filter(name__icontains=self.q) return qs And my urls.py: path( 'name-autocomplete/', PersonAutoComplete.as_view(create_field='name'), name='name-autocomplete', ), -
post Blocks across views
I stuck on something in django 2.2 that I can not find an explanation on the forums or in the tutorial, is that I want to display the blocks of a basic template through the views in a single template, kind for validated a form the page does not refresh, and display another block content that will be displayed with another view, I hope my question was clear and thank you for your answers. -
How to write data to MongoDB using PyMongo as well as Django
I am new to Django and MongoDB. I used Djongo to connect to MongoDB from Django. I also updated models.py based on the model I wish to implement. Now, I need two ways to write/update data to MongoDB for my application. From front-end of the website using Django forms. From back-end using PyMongo. I was able to successfully execute the below two commands. python manage.py makemigrations python manage.py migrate This created the required collection in mongodb. The problem is when I push data from backend using PyMongo, I'm able to insert one document to this collection. But unable to add anymore document to this collection. It is giving me the below error. pymongo.errors.DuplicateKeyError: E11000 duplicate key error collection: FLASH.home_street index: __primary_key__ dup key: { : null } PyMongo is expected to generate unique _id for each document. I also don't understand where this __primary_key__ came from. I didn't define this key in my model though. Kindly help.