Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to join querysets and do some calculation on some of them
I need advice how should I implement view function which for now works but I think there is an easier way to do it. Lets say that user can add a meal for specific day it might be 1 meal or 2 or whatever he choose, in specific meal an author can set how many portions are in that meal and user can choose how many portions he would like to add from that specific meal. Each meal contains some ingredients each ingredient contain information about calories etc. For example: User Foo created Meal Scrambled Eggs with Ingredients 200g Eggs(100kcal 10g proteins etc) and 100g Onions(20kcal 2g proteins etc) and Portions 2 User Bar created Meal Spaghetti with Ingredients 200g Pasta(300kcal 5g proteins etc) 400g Tomatoes Sauce(80kcal 8g proteins etc) 300g Meat(350kcal 45g proteins etc), Portions 3 User C want to add those meals to his day but only choose 1 portion from each meal. And there is a question how I can get Ingredients and nutritional values depended of chosen portions for each meal ? I tried to do this in a way which is showed in my views but I am sure that there is an easier way … -
The problem is that the user profile change form is always valid in Django
I have two different forms of a model in a template I change the user's photo with one form and edit the user's text profile with another form The model (profile) is a one-to-one relationship with the main Django user But I have a problem with the user photo change form When clicking on the user profile edit form which is the profile model (for text changes) The photo change form is also called and is always valid My forms are from the Django form model Definitely the main problem is the image change form, but I do not know which part of the code has a problem. I send the values to the server with Ajax. Below I will display the codes and output to convey the concept easier If you do not understand my problem, I can explain more to you, just give me your email address so that I can contact you. Thank you. Output View def edit_user_view(request, pk): user = get_object_or_404(User, pk=pk) c_default_user_edit_form = default_user_edit_form( request.POST or None, initial=vars(user), instance=user ) c_user_image_editing_form = user_image_editing_form( request.POST or None, request.FILES or None, instance=user.profile ) c_user_information_editing_form = user_information_editing_form( request.POST or None, initial=vars(user.profile), instance=user.profile, ) if c_default_user_edit_form.is_valid(): print("default user") c_default_user_edit_form.save() … -
Django query possibly at the views.py
I am getting the following error: TypeError: Choice() got an unexpected keyword argument 'skill' Here is my code below: def create_choice(request): if request.is_ajax(): skill = request.POST.get('skill') print(skill) skill_obj = Skill.objects.get(name=skill) price = request.POST.get('price') print(price) price_obj = Price.objects.get(name=price, skill__name=skill_obj.name) Choice.objects.create(skill=skill_obj, price=price_obj) return JsonResponse({'created':True}) return JsonResponse({'created':False}, safe=False) -
Blog on Django, querysets for fetch logged in user's posts
I'm building a blog on Django and know i have to make a personal page for see all the posts published by the user we're logged in now. I'm using some querysets so. Her my code my models.py from django.db import models from django.conf import settings from django.utils import timezone class Post(models.Model): author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) title = models.CharField(max_length=200) text = models.TextField() created_date = models.DateTimeField(default=timezone.now) published_date = models.DateTimeField(blank=True, null=True) def publish(self): self.published_date = timezone.now() self.save() def __str__(self): return self.title Here my forms.py from django.contrib.auth.forms import UserCreationForm from django import forms from django.contrib.auth.models import User from .models import Post class CreateUserForm(UserCreationForm): class Meta: model = User fields = ['username','email','password1','password2','user_permissions','is_staff','date_joined'] class PostForm(forms.ModelForm): class Meta: model = Post fields = ['title', 'text', 'author'] And that's the view which is gonna filter the posts in base of the logged user from django.contrib.auth.models import User from django.contrib import messages from django.contrib.auth import authenticate,login,logout from django.contrib.auth.decorators import login_required from django.utils import timezone from .forms import CreateUserForm from .models import Post from .forms import PostForm def user_data(request, pk): user_data = User.objects.get(pk=pk) posts = user_data.post_set.filter(author=user_data) context = {'user_data':user_data, 'posts':posts} return render(request, 'account/user_data.html', context) #So it returns me just the user data like name, email or date_joined but not … -
django_elasticsearch_dsl_drf search in text field with space returns null
I have the following index in my Elasticsearch: "mappings": { "properties": { "content": { "type": "text" }, . . . When I use kibana console searching in content field by a value such This is, It return all documents with phrase This is in the content, but using django_elasticsearch_dsl_drf (and django rest framework) it returns nothing and the search only works by values with no spaces, I mean If i search for the word This it returns the results as wished. My document: @INDEX.doc_type class PostDocument(Document): content = fields.TextField() ... my serializer: class PostDocumentSerializer(DocumentSerializer): """Serializer for the Post document.""" content = serializers.CharField() ... my viewset: class PostDocumentView(DocumentViewSet): document = PostDocument serializer_class = PostDocumentSerializer pagination_class = PageNumberPagination filter_backends = [ FilteringFilterBackend, IdsFilterBackend, OrderingFilterBackend, DefaultOrderingFilterBackend, SearchFilterBackend, SuggesterFilterBackend, ] # Define search fields search_fields = ( 'content', ... ) filter_fields = { 'content': { 'field': 'content', 'lookups': [ LOOKUP_QUERY_CONTAINS, LOOKUP_QUERY_IN ] }, } and the URL to test is: http://127.0.0.1:8000/social_networks/posts_search/?format=json&page=1=&content=This is -
CRITICAL WORKER TIMEOUT in Gunicorn
I have written a Flask application and run the python code from terminal. python xxx.py Then I enter a curl command into another terminal and print outs of my code appear in the Flask terminal. After that, I created a wsgi.py file for Gunicorn in the same folder and run it from terminal. gunicorn --bind localhost:5101 wsgi:xxx Then I enter the same curl command from another terminal to access the functions in Flask app using Gunicorn. However, the Gunicorn terminal prints [2021-02-16 13:57:04 +0100] [1043] [CRITICAL] WORKER TIMEOUT (pid:1224) [2021-02-16 13:57:04 +0100] [1224] [INFO] Worker exiting (pid: 1224) and I cannot get the results from my desired function in Flask. Can someone guide me what am I doing wrong? Thanks. -
My Css is not being rendered for the django rest framework access page but works fine for the other pages in my site when using apache server
The css gets rendered properly when I use the django development server I checked the static files and the required css files have been collected in the folder as well Below is the apache server .conf file me_buildout_xmeme is the repo name memev2 is the project name <VirtualHost *:80 *:8080> ServerAdmin webmaster@example.com DocumentRoot /home/ubuntu/django/me_buildout_xmeme ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined Alias /static /home/ubuntu/django/me_buildout_xmeme/static <Directory /home/ubuntu/django/me_buildout_xmeme/static> Require all granted </Directory> <Directory /home/ubuntu/django/me_buildout_xmeme/memev2> <Files wsgi.py> Require all granted </Files> </Directory> WSGIDaemonProcess memev2 python-path=/home/ubuntu/django/me_buildout_xmeme python-home=/home/ubuntu/django/myprojectenv WSGIProcessGroup memev2 WSGIScriptAlias / /home/ubuntu/django/me_buildout_xmeme/memev2/wsgi.py </VirtualHost> This refers to the settings.py settings STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static_collected') # STATIC_ROOT='static' STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static'), ) -
Django behaving strangely on updating a JsonField using Model objects
Since my code is pretty big, I have not copied it entirely. Instead added whatever i feel is required. I have a Model class class SomeModel(models.Model): id = models.BigAutoField(primary_key=True) policy = JSONField(null=True) Initially the value in policy is in format like this: [ { "type": "Bed", "policy": { "details": [ { "from": "2021-04-17T00:00:00", "currency": "INR", "flat_fee": 3000 }, { "from": "2021-04-18T00:00:00", "currency": "INR", "flat_fee": 4000 } ], "under_flag": false } } ] Then I'm updating the data within details field of the object using following function: def _update_policy(some_model_object): policy_list = some_model_object.policy if policy_list: for index, policy_data in enumerate(policy_list): policy = policy_data.get('policy') details = policy.pop('details') final_details = [] for i, detail in enumerate(details): detail['new_fee'] = #some computation detail['id'] = i + 1 final_details.append(detail) policy['details'] = final_details print('policy', policy) print('policy_list', policy_list) some_model_object.policy = policy_list self.itinerary_booking_details.save() Now both the print statements show the update dictionary with the new_fee field added. But the same is not reflected in DB after save(). Question Summary: I'm updating a JSONField in django, and saving the model object. The print statement before save function is called, shows that the variable is updated. But after assigning and saving the same, it doesn't reflect in DB. I'm using Django 3.0.5, … -
How do I dynamically set value to Many2Many field?
Is it possible to use a variable to get the instance of the m2m model-field and then use .set()? I know that this how we can use setattr to use a variable to set a value to a class: myfield = "fieldname" mylist = ["data"] setattr(model, myfield, mylist) And that we set value to a ManyToManyField by doing: mylist = ["data"] model.fieldname.set(mylist) Question: Is it possible to use a variable to get the instance of the m2m model-field and then use .set()? Something like (this doesn't work): myfield = "fieldname" mylist = ["data"] getattr(model, myfield).set(mylist) # throws AttributeError: 'list' object has no attribute 'set' TYIA! -
Django rest framework websockets auto update
I am using django rest framework for my API,and vue for frontend, and, it is possible to auto update my frontend state when I changed something ?Its totally basic vue and django code, just for example Vue <template> <div> <div class="numbers">{{ state.numbers }}</div> Number pk <input type="text" v-model="state.pk" /> Number value <input type="text" v-model="state.inputValue" /> <button v-on:click="changeNumber">change !</button> </div> </template> <script> import axios from "axios"; import { reactive, onMounted } from "vue"; export default { name: "HelloWorld", setup() { const state = reactive({ numbers: [], inputValue: 1, pk: 1, }); function changeNumber() { const data = { number: state.inputValue, }; console.log(data); axios.patch(`http://127.0.0.1:8000/api/number-update/${state.pk}/`, data); } onMounted(() => { axios .get("http://127.0.0.1:8000/api/numbers-list/") .then((res) => (state.numbers = res.data)); }); return { changeNumber, state, }; }, }; </script> How it is in browser and I want to, when I click change button, auto update backend data,without refreshing. Backend Serializers.py from rest_framework import serializers from .models import Number class NumberSerializer(serializers.ModelSerializer): class Meta: model = Number fields = '__all__' Views.py from django.shortcuts import render from .serializers import NumberSerializer from rest_framework import generics from .models import Number class NumbersList(generics.ListAPIView): queryset = Number.objects.all() serializer_class = NumberSerializer class NumberUpdate(generics.UpdateAPIView): queryset = Number.objects.all() serializer_class = NumberSerializer Urls.py from django.urls import path … -
Ajax request cannot access the URL in Django. I have a problem with an integer( the id)
Hello everyone! I'm working on an app for patients using Django. I tried to get all the details about a patient and display them on a new panel. When the user presses a button I use the patient's id. When I try to put this id in ajax's URL I receive an error "NoReverseMatch". I don't know how to solve it. Any help is welcome. Sorry for the indentation, but this is Atom :)) I have two ajax requests. The first one is functional( here I display all patients' names in a table, for every patient I attach a button named "Details". When the user clicks the "Details" button for a patient I want to display all data about this person on a new panel using a href to the second ajax). I have a "Delete" button too, but it's functional, the "Details" is the problem here. views.py def getPatientDetails(request, id): currentPatient = Patient.objects.get(id=id) return JsonResponse({"patient":currentPatient}) urls.py for this function path('getPatientDetails/<int:id>', getPatientDetails, name='getPatientDetails'), Here is the html template This is the first ajax, which is functional <script> $(document).ready(function(){ $.ajax({ type:'GET', url: "{% url 'getPatients' %}", success: function(response){ $("#displayPatients").empty(); for(var key in response.patients) { var temp = "<tr><td>"+response.patients[key].firstName+"</td><td>"+response.patients[key].lastName+"</td><td>"+response.patients[key].phone+"</td><td><a href='getPatientDetails/"+response.patients[key].id+"'><button class='detailsButton outline-text'>Details</button></a><a … -
SQLite 3.8.3 or later is required (found 3.7.17). in centos
run : python manage.py runserver raise ImproperlyConfigured('SQLite 3.8.3 or later is required (found %s).' % Database.sqlite_version) django.core.exceptions.ImproperlyConfigured: SQLite 3.8.3 or later is required (found 3.7.17). -
Python Negative time difference
I am new to django. I want to calculate the total time. My model counts the time difference - and stores, the view counts the time sum. It works. But if the time difference is negative(01:00 - 21:00), then I get an error(time data '-1 day, 4:00:00' does not match format '%H:%M:%S'). according to the idea it should be 4:00 o'clock I suppose that you need to save time not explicitly, but I do not understand how to do it. Or do you need to use something else? Models.py class Trip(models.Model): ... start_work = models.TimeField(verbose_name='Начало работы') finish_work = models.TimeField(verbose_name='Окончание работы') hours_worked = models.CharField(verbose_name='Отработано часов', max_length=50, blank=True) ... @property def hours_work(self): result = datetime.combine(date.today(), self.finish_work) - datetime.combine(date.today(), self.start_work) hours_work1 = str(result).rsplit(':', 1)[0] hours_worked = hours_work1 return hours_worked def save(self, *args, **kwargs, ): self.hours_worked = self.hours_work super(Trip, self).save(*args, **kwargs) wiews.py total_time = timedelta(hours=0, minutes=0) me = trip.values_list('hours_worked') sum_hour = 0 for el in me: for i in el: time = datetime.strptime(i, "%H:%M:%S") t1 = timedelta(hours=time.hour, minutes=time.minute) total_time = total_time + t1 sum_hour = str(total_time).rsplit(':', 1)[0] -
How to write OR condition in Django ORM for same values in two different columns
for the below class I need to write a django query in such way that value "John" should be passed for both Ename and HOD with an OR condition I need a DJANGO query to display the records with condition (Ename="John" or HOD="John") AND Country="UK" class Employee(models.Model): Ename=models.CharField(max_length=30) HOD = models.CharField(max_length=30) Dep = models.FloatField() Email = models.CharField(max_length=35) -
How to find a clicked element in django?
Onn my Django webpage I have multiple list items which all have onclick listener. I need python code to find the element that was clicked. -
Sorting content to reverse during implementation of infinity scroll in Django
I'm an introducer of Django. Like Instagram, I'm trying to make pictures or videos come out when they go down. I implemented pagination through infinite scrolling, but there was a problem that the posts that were previously reprinted and displayed in the latest order were not sorted in the latest order. There are 10 posts (the higher the number, the more recent), and paginated_by is set to 4. originally, it was 10 9 8 7 6 5 4 3 2 1, but when I applied the infinite scroll, I could find the phenomenon that was reverted in the order of 4 3 2 1 8 7 6 5 10 9. I'd like to apply the infinite scoll in order of 109 8 7 6 5 4 3 2 1. Please help me, thank you here are my codes. models.py class Video(models.Model): status_choices = { ('before eating', '먹기전'), ('eating', '먹는중'), } restaurant = models.CharField(max_length = 128, verbose_name = '가게이름') foodname = models.CharField(max_length= 128, verbose_name= '음식이름') file = models.FileField() price = models.PositiveIntegerField(default=0) status = models.CharField(max_length=80, choices= status_choices, null=True) distance = models.PositiveIntegerField(default=0, verbose_name='거리') title = models.CharField(max_length= 128, verbose_name= '제목', default= '모르겠어요') author = models.ForeignKey('user.meokda_user', on_delete = models.CASCADE, verbose_name = '작성자', null = True … -
Kali linux cant import modules that i created
thanks for your time. i've started to work on kali linux and don't know why i'm not beeing able to import files. By using python manage.py every thing works fine, although when trying to run a file by it self i get or : from .models import Player ImportError: attempted relative import with no known parent package``` or from winners.models import Player ``` ModuleNotFoundError: No module named 'winners' I've tried to reset the ambient variable DJANGO_SETTINGS_MODULE DJANGO_SETTINGS_MODULE=olympic.settings tryed to add the path manually trough sys.path, tryed every possible way of import. i guess is something i configured wrong. thats my sys.path output: ['/home/kali/.virtualenvs/celero/olympic/winners', '/usr/lib/python39.zip', '/usr/lib/python3.9', '/usr/lib/python3.9/lib-dynload', '/home/kali/.virtualenvs/celero/lib/python3.9/site-packages'] -
Deploy Django Channels with multiple processes
When deploying a django app to production using gunicorn you're able to specify the number of worker processes by simply appending --workers 4 or defining this in the config file. How would I go about doing this when deploying using Daphne for a project that uses Django Channels? Daphne doesn't appear to support settings and config changes to the extent that gunicorn does. I haven't been able to find much in this regard. FYI, I am using docker-compose with the following services: api: This is the django channels app along with daphne redis: This is used for the channel layer caddy: This is the proxy I am using (Caddy Server) I presume not being able to set the number of processes is by design in daphne but I'm not sure why that is or what I should be doing instead? Is this simply not needed for some reason? -
Replicating Folder Structure inside the existing folder when updating the model Django
I have a model with image compression enabled class Course(models.Model): def upload_location(instance,filename): return "course_images/%s/%s"%(instance.course_name,filename) subject = models.ForeignKey(Subject,on_delete=models.CASCADE,null=True,default=None) course_name = models.CharField(max_length=300,default=None) author = models.ForeignKey(TeacherProfile,on_delete=models.CASCADE,null=True,default=None) course_description = models.TextField(null=True) course_cover = models.ImageField(null=True,blank=True,upload_to=upload_location,default="course_images/default.png") created_at = models.DateTimeField(default=now) price = models.IntegerField(default=0,null=True,blank=True) duration = models.CharField(max_length=20, null=True, blank=True) is_enrolled = models.BooleanField(default=False) def save(self, *args, **kwargs): new_image = compress(self.course_cover) self.course_cover = new_image super().save(*args, **kwargs) def __str__(self): return self.course_name When I update this model without sending an image from the frontend folder structure gets replicated inside the existing folder. ex:- Course_images/Science/science.jpg is the initial folder structure when creating an object with this model. But after updating the model without the image I can see another Course_images/Science/science.jpg inside Course_images. This starts to happen after adding the compression method. Without overriding the save method this works fine. Also if I change the image folder replication is not happening. View of the updatecourse class UpdateCourse(RetrieveUpdateAPIView): queryset = Course.objects.all() serializer_class = CourseCreateSerializer permission_classes = [IsAuthenticated] Can anyone state a reason for this scenario. Thank you! -
OpenID Connect + Django DRF + React: How to use?
I have a web application made up of two parts: back-end which is implemented using Django + Django Rest Framework (DRF), and front-end which is a React App project. For authentication and authorization, I use Keycloak. For authentication first, the front-end app redirects the user to the Keycloak login page, and after Keycloak receives the correct combination of username and password, redirects the user back to the front-end app and provides the front-end app with an access key and a refresh key pair. Now when the user wants to call any API to the back-end it has the required access key. I decided to put the front-end app in charge of refreshing the access token, too; but I am looking forward to any better solution. Since I need to use authorization in my application, its "Access Type" in Keycloak should be set as "confidential"; thus when my front-end app wants to authenticate, it should provide "client secret". This has no problem when I am in the development stage since I can easily change the client secret in the code. But when I want to build the front-end application for production, I hard-code the client secret from my Keycloak instance in … -
Django-App with Nginx and Gunicorn - Requests get lost?
in our company we use a timetracking system built with django. It is deployed with Nginx as reverse proxy and Gunicorn to run the python code. It is basically a simple system with a button to start the attendance and another button to stop. Sometimes users claim that they pressed start or stop, but the system did not process it. We are now determing if our Gunicorn configuration is not suitable for our use case and requests get lost. So, my question is: Is it possible, that requests get lost when Nginx/Gunicorn is not able to handle the amount of requests? Facts: Worst case amount of about 150 requests at the same time (150 active users of our application, everyone wants to register its stop at the same time. This does acually never happen) Gunicorn runs with the default configuration but 3 workers Any help in this case is appreciated, if you need further information, let me know! -
How to send email with attachment from form?
I've been trying different ways to send an attachment from a submitted form but I'm not able to get it right. my model: from django.db import models class Document(models.Model): description = models.CharField(max_length=255, blank=True) document = models.FileField() uploaded_at = models.DateTimeField(auto_now_add=True) views.py from django.shortcuts import render, redirect from django.core.mail import EmailMessage from decouple import config from .forms import ContactForm def contact(request): contact_form = ContactForm() if request.method == "POST": contact_form = ContactForm(request.POST, request.FILES) if contact_form.is_valid(): name = request.POST.get("name") email = request.POST.get("email") subject = request.POST.get("subject") message = request.POST.get("message") upload = request.POST.get("upload") email_content= EmailMessage("Message from django-structure project", f"The user with name {name}, with the email {email}," f" write the following: \n Subject: {subject} \n File{upload} \n\n Message: {message}", "", [config('EMAIL_TO')], reply_to=[email]) try: email_content.send() return redirect("/contact/?valid") except: return redirect("/contact/?invalid") return render(request, "contact.html", {"form": contact_form}) contact.html <div class="row"> <div class="col"> <div class="form-group"> {% if "valid" in request.GET %} <p style="color: blue;">Information sent successfully </p> {% endif %} <form action="" method="POST" enctype="multipart/form-data" style="text-align: center;"> {% csrf_token %} <table style="color: dark; margin:20px auto;">{{form.as_table}}</table> <input type="submit" value="Send" style="width: 150px;"> </form> </div> When I submit the form, I receive the message but in the content of the File, just the following string: "FleNone". (I have attached a pdf) -
Link to an id in html django view with url ```view/<int:id>/<slug:slug>/```
I have a view in django that views product details. In my urlpatterns list it's like the following. urlpatterns = [ ... path('view/<int:id>/<slug:slug>/', views.product_detail, name='product_detail'), ... ] Now I want to create a link of the following form mysite.com/view/1/drone/#reviews. I tried this and it doesn't bring me to the reviews section. But for a normal url like the following it works with no problem. urlpatterns = [ ... path('home/', views.home, name='home'), ... ] Can someone help me what's the difference here? Because when it's like this I can access mysite.com/#some_element -
kali linux, python. not beeing able to import
thanks for your time. i've started to work on kali linux and don't know why i'm not beeing able to import files. By using python manage.py every thing works fine, although when trying to run a file by it self i get or : from .models import Player ImportError: attempted relative import with no known parent package``` or from winners.models import Player ``` ModuleNotFoundError: No module named 'winners' I've tried to reset the ambient variable DJANGO_SETTINGS_MODULE DJANGO_SETTINGS_MODULE=olympic.settings tryed to add the path manually trough sys.path, tryed every possible way of import. i guess is something i configured wrong. -
Parsing bytestring into Python dictionary
I have a bytestring like this: b'{\r\n "hello": "world"\r\n}', retrieved from a request in JSON format. I would like to parse it into a Python dictionary so it looks like this: {"hello": "world"}. I have tried with ast.literal_eval() but that throws an error. How would you go about doing it?