Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Retrieve data from models having reverse relationship in django rest
I have 3 models where model A has foreign key of another in reverse order like:- class Book(models.Model): name = models.CharField(max_length=100) img=models.CharField(blank=True) category=models.CharField(max_length=100,null=True) class Section(models.Model): book= models.ForeignKey(Book, related_name='books', on_delete=models.PROTECT) title= models.TextField(null=True) class SubSection(models.Model): section=models.ForeignKey(Section, related_name='sections', on_delete=models.PROTECT, null=True) sub_title= models.TextField(null=True) I am trying to fetch all sections and subsections on the basis of book id. Before I was using nested serializer but nested serializer slow down its response. i am trying to achieve it with select_related can anyone help me with view query and serializer class. I want response like: data=[ "section": "A", "title": "intro", "subsection": [ { "id": 1, "sub_title": "title" } ] ] -
Is there any way to forcibly resize an image to a given dimension in python?
I am using the pillow library. I have an image whose dimension is 1280x1920. When I upload the image, I want to resize the image to 800x600. But after uploading, the image resized to 475x350. Is there any way to forcibly resize the image into the given dimension? This is my code to resize the image in Django: img = Image.open(self.image.path) if img.width > 800 or img.height > 600: img.resize((800, 600), Image.ANTIALIAS) img.save(self.image.path) -
django blog like button error django.urls.exceptions.NoReverseMatch:
am making a django blog and trying to implement a Like button. Anyone got any help/ideas how to get this to work when am adding the code i get some errors. atm i got error: django.urls.exceptions.NoReverseMatch: Reverse for 'post_detail' not found. 'post_detail' is not a valid view function or pattern name. I would really appreciate if someone could help me to get this like button up and runing since i been trying to fix it forever it feels like newsapp folder views.py from django.shortcuts import render, get_object_or_404, redirect from django.views import generic from .models import Post, Like from .forms import CommentForm class PostList(generic.ListView): queryset = Post.objects.filter(status=1).order_by('-created_on') template_name = 'index.html' paginate_by = 6 def post_view(request): qs = Post.objects.all() user = request.user context = { 'qs': qs, 'user': user, } return render(request, 'newsapp/main.html', context) def like_post(request): user = request.user if request.method == 'POST': post_id = request.POST.get('post_id') post_obj = Post.objects.get(id=post_id) if user in post_obj.liked.all(): post_obj.liked.remove(user) else: post_obj.liked.add(user) like, created = Like.objects.get_or_create(user=user, post_id=post_id) if not created: if like.value == 'Like': like.value = 'Unlike' else: like.value = 'Like' like.save() return redirect('newsapp:post-list') def post_detail(request, slug): template_name = 'post_detail.html' post = get_object_or_404(Post, slug=slug) comments = post.comments.filter(active=True) new_comment = None # Comment posted if request.method == 'POST': comment_form … -
Django FileResponse Content-Disposition header not working for filename
I use the Content-Disposition header because the stored name of the files is different from the name they are served. But header not working in all files correctly, i'm directly passing filename to header. Filenames contains non-ASCII characters. Here is the download view i'm using: @api_view(['GET']) def download_streamer(request, **kwargs): dlo = DownloadLink.objects.get(token=kwargs['token']) if dlo.is_expired: return Response({'link_expired': 'Download link expired, try again'}, status=status.HTTP_410_GONE) else: mimetype, _ = mimetypes.guess_type(dlo.file_cache.stored_at) f_response = FileResponse(open(dlo.file_cache.stored_at, 'rb'), content_type=mimetype) f_response['Content-Disposition'] = f'attachment; filename={dlo.file_cache.origin.name}' f_response['Access-Control-Expose-Headers'] = 'Content-Disposition' FileActivity.objects.create(subject=dlo.file_cache.origin, action='GET', user=dlo.owner) return f_response Here is the valid response header which i want (file name not containing non-ASCII chars) content-disposition: attachment; filename=jinekolojik aciller.ppt But some files gives this headers (original filename: türkiyede sağlık politikaları.pdf) content-disposition: =?utf-8?q?attachment=3B_filename=3Dt=C3=BCrkiyede_sa=C4=9Fl=C4=B1k_politikalar=C4=B1=2Epdf?= -
Django makemigrations with docker-compose not working. Can't find module
I'm trying to run makemigrations using "docker-compose run makemigrations" after adding pillow to my project but it gives an error saying the "ModuleNotFoundError: No module named 'PIL'". I'm attempting to use pillow to compress uploaded images. Pillow has been added to settings.py and requirements.txt. I have also tried rebuilding the docker image. It also may be worth noting that the error doesn't appear when I run the server using "docker-compose up" Below are snippets of code: docker-compose.yml version: "3.9" services: db: image: postgres ports: - "5432" volumes: - ./data/db:/var/lib/postgresql/data web: build: . command: python manage.py runserver 0.0.0.0:8000 volumes: - .:/code ports: - "8000:8000" depends_on: - db createsuperuser: build: . profiles: ["createsuperuser"] command: python manage.py createsuperuser volumes: - .:/code ports: - "8001" depends_on: - db makemigrations: build: . profiles: ["makemigrations"] command: python manage.py makemigrations volumes: - .:/code ports: - "8002" depends_on: - db migrate: build: . profiles: ["migrate"] command: python manage.py migrate volumes: - .:/code ports: - "8003" depends_on: - db models.py from PIL import Image ... class PropertyPhoto(models.Model): property = models.ForeignKey(Property, on_delete=models.CASCADE, null=True, related_name="photos") photo = models.ImageField(upload_to=f"static/properties/{property}/photos/", null=True, default=None) def save(self, *args, **kwargs): instance = super(PropertyPhoto, self).save(*args, **kwargs) image = Image.open(instance.photo.path) image.save(instance.photo.path, quality=80, optimize=True) return instance Error when running makemigrations … -
How to build a API web server in Python
I hope you are well. I'm new to Python, I learned the language a while ago and was building mainly console applications. My goal in learning python was to build a web API server. Now that I have learned the language, I want to achieve my goal. But here is the problem, I did some research to know how to build a web API server but there are so many things I discovered like Django, Flask, FastAPI that I as a beginner am lost in the middle of it all and don't know which one to choose and learn. I come back from the JavaScript universe, and there is the Express package/framework which is known as the REFERENCE for building a web API server and I would like to know in the Python universe what is the REFERENCE for building a web API server in terms of functionality, community and other. Can you put me in order in all this? Thanks to you -
Django ratelimiter custom method
how can I put a custom function for the method in django-ratelimit? I want it to be like this: I filled out a form. Then check if the length of the name is less than 5. If the length of the name is less than 5 then as many times as we fill the form it will never block the user. But if the length is bigger every time and he fills the form 5 times then the limiter will block the user from accessing the page. -
django filter empty array in prefetch_related
I used prefetch_related and Prefetch to create a list of areas ( main category), needs (subcategory), and product categories (subsubcategory) for my products. filter_needs = Area.objects.filter(Exists(Need.objects.filter(category_need=OuterRef('pk')))) products = Area.objects.prefetch_related(Prefetch('need_area', queryset=filter_needs, to_attr='need_area__category_need__product')) .filter(need_area__category_need__product__isnull=False).distinct() Right now query renders all areas that contain the product but with all needs (even if there is no product in need). How can exclude all needs that are empty? -
Django Annotation Custom Value
I want to add a new col total_sum to every object of SomeModel. To calculate it I try to use my function calc_total_sum which requires id of the object and some external args. SomeModel.objects.all().annotate( total_sum=Value(calc_total_sum(F('pk'), start_date, end_date), DecimalField()) ) But this query seems to be wrong because then my function receives not value of each pk but just a function F How can I fix it? -
django debugger does not start in vscode
i'm trying to run a django debugger, but here's what happens. from .forms import RegisterUserForm, LoginUserForm, IndexPageForm, OrderTicketForm ImportError: attempted relative import with no known parent package launch.json "version": "0.2.0", "configurations": [ { "name": "Django", "type": "python", "request": "launch", "stopOnEntry": false, "python": "${config.python.pythonPath}", "program": "${workspaceRoot}/manage.py", "args": [ "runserver", "--no-color", "--noreload" ], "debugOptions": [ "WaitOnAbnormalExit", "WaitOnNormalExit", "RedirectOutput", "DjangoDebugging" ] } ] location venv and django project - F:train/venv/ -
<QuerySet []> is returning empty in django
I am trying to create a queryset for getting the values of a DateTimeField which is DATETIME in the DB. The class in models.py: class Message(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) room = models.ForeignKey(Room, on_delete=models.CASCADE) body = models.TextField() updated = models.DateTimeField(auto_now=True) created = models.DateTimeField(auto_now_add=True) class Meta: ordering = ['-created', '-updated'] The class in models.py: class Room(models.Model): host = models.ForeignKey(User, on_delete=models.SET_NULL, null=True) topic = models.ForeignKey(Topic, on_delete=models.SET_NULL, null=True) name = models.CharField(max_length=200) description = models.TextField(null=True, blank=True) updated = models.DateTimeField(auto_now=True) created = models.DateTimeField(auto_now_add=True) def __str__(self): return self.name in views.py def room(request, pk): room = Room.objects.get(id=pk) room_messages = room.message_set.all() print(room_messages) context = {'room': room, 'room_messages': room_messages} return render(request, 'base/room.html', context) when i would render room_messages in "room.html" {% block content %} <h1>{{ room.name }}</h1> <p>{{ room.description }}</p> <div class="comment-wrapper"> <h3>Conversation</h3> <hr/> {% for room_message in room_messages %} <small> {{ room_message.user }} {{ room_message.created }} </small> {% endfor %} </div> {% endblock %} i cant see room_messages like that : the messages's page -
django pre_save signals not updating
The last line of the test at the bottom fails. I tried to reduce the code to the essential pieces. The explanation is in the comments for the code. class Concept(model.Model): is_deprecated= Boolean(default=False) ... class Tag(model.Model): concept_tags = ManyToManyField(Concepts, ...) is_deprecated= Boolean(default=False) ... class StatusInfo(model.Model): """the important thing is the pre_save signal""" status = '' affected_tag = ForeignKey(Tag, ...) ... @receiver(pre_save, sender=StatusInfo) def status_change_modification(sender, instance, *args, **kwargs): if instance.status == "d": # d for deprecated instance.affected_tag.is_deprecated = True # works c_tags = instance.affected_tag.concept_tags.all() print(f"{c_tags = }") # when I run the test below this shows that I have included self.concept_with_deprecated_tag c_tags.update(is_deprecated=True) # doesn't seem to work but I don't want to trigger a save() on concepts (referenced through concept_tags) because concepts has it's own signals that will trigger. ##### in the tests/status_info.py ####### def test_status_set_tag_info_deprecated(self): """ if you add the statusInfo to a tag it will set the tag and related concepts to is_deprecated == True """ self.concept_with_deprecated_tag.is_deprecated = False # set temporarily for the test self.assertFalse(self.deprecated_tag.is_deprecated) self.main_status_info = StatusInfoFactory( affected_tag=self.deprecated_tag, status="d", by=self.new_replacement_tag) self.assertTrue(self.deprecated_tag.is_deprecated) self.assertTrue(self.concept_with_deprecated_tag.is_deprecated) # this is one concept from the list and it fails to be changed. -
'AuthenticationForm' object has no attribute 'cleaned_data'
I override a custom django login by importing the AuthenticationForm and using the code below in my views.py but the only problem Im getting is that when i try to clean the form it always gives an error: 'AuthenticationForm' object has no attribute 'cleaned_data'. What should I do to resolve this problem? Here is my views.py for overriding custom django login from django.contrib.auth.forms import AuthenticationForm def auth_login(request): if request.user.is_authenticated: return redirect('/') else: if request.method == 'POST': form = AuthenticationForm(request.POST) username = request.POST['username'] password = request.POST['password'] username = form.cleaned_data['username'] user = authenticate(username=username,password=password) if user: if user.is_superuser: login(request,user) return redirect('/dashboard') else: login(request,user) return redirect('/') else: messages.error(request,'Username or password not correct') return redirect('/accounts/login') return render(request,'registration/login.html',{'form':form}) -
Check if an image contains a face then add to an image folder
I am working with Django Rest Framework to create a Face Recognition API. I have created a standalone application for Face Recognition using 'face_recognition' library in Python and OpenCV. Now I need to convert this standalone project to an API. In model.py I have created a class named Person Which contains some fields for registering a person like name, email, password, and also an image. The person uploads an image and it gets saved to the media directory. I want to check whether the uploaded image contains a face or not. It should be saved in the media directory if and only if it contains only one face. Otherwise, there should be a message saying "The uploaded image does not contain a face or contains more than one face". I am new to the Django Framework and APIs in general. Any help is greatly appreciated. The codes are as follows: models.py # Create your models here. from django.db import models # lets us explicitly set upload path and filename def upload_to(instance, filename): return 'images/{filename}'.format(filename=filename) class Person(models.Model): name = models.CharField(max_length=60, blank=False, null=False) image_url = models.ImageField(upload_to=upload_to, blank=True, null=True) def __str__(self): return self.name serializers.py from rest_framework import serializers from .models import Person class … -
Django testing view with pytest
Could you please helpe me debugging this test? I got this error (I don't know whay since, I have no pk in view): django.contrib.auth.models.User.DoesNotExist: User matching query does not exist.I think the error is due to pk=request.user.id passed as argument in User objects in the view function. class TestViews(TestCase): def setUp(self): self.client = Client() self.create_campaign_naming_tool_url = reverse('create_campaign_naming_tool') self.user = User.objects.create_user( username = 'admin', email = 'admin@sigma.fr', password = '1234' ) def test_create_campaign_naming_tool(self): response = self.client.get(self.create_campaign_naming_tool_url) self.assertEqual(response.status_code, 200) self.assertTemplateUsed(response, 'form.html') Here is my view def create_campaign_naming_tool(request): current_user = User.objects.get(pk=request.user.id) form = CampaignNamingToolForm(initial={'user': current_user}) context = { 'form': form, } if request.method == 'POST': campaign = CampaignNamingTool(user=current_user) form = CampaignNamingToolForm(request.POST, instance=campaign) if form.is_valid(): form.save() messages.success(request, "Your campaign haven ben\ success fully created.") return render(request, 'form.html', context) return render(request, 'form.html', context) -
How to add files in Django session?
I want to get some files from the user and after getting the files, I want the user should make a payment after payment is done, an order should be created and the files should be stored against that order in the Database. I know how to create an order and store the files in a database. I have used Django's sessions to store the string data. But want to store files also. I have used the following code : In HTML: <form method="POST" enctype="multipart/form-data"> <input type="file" name="filename"> </form> In views.py : if request.method == "POST": request.session['filename'] = request.FILES['filename'] It throws errors as : Object of type InMemoryUploadedFile is not JSON serializable -
Django ratelimit custom function
how can I put a custom function for the method in django-ratelimit. I want for example if a user fills a form then check example if the name of the form already exists and if exists then doesn't count for the rate limiter. I want it to be like: I filled a form. Then check if the name already exists. If the name exists as many times as we do it will never block the user. But if the name is different every time then the limiter will block the user. -
Heroku deployment for React + Django app not working
I am trying to deploy my application in Heroku that uses React as frontend and Django as backend but I am stuck. When I run git push heroku master it says the project is successfully deployed but I got error whe opening the project: Failed to load resource: the server responded with a status of 404 (Not Found) texstore.herokuapp.com/:1 Refused to apply style from 'https://texstore.herokuapp.com/static/css/main.0286b08d.css' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled. manifest.json:1 Failed to load resource: the server responded with a status of 404 (Not Found) manifest.json:2 Manifest: Line: 2, column: 1, Syntax error. manifest.json:1 Failed to load resource: the server responded with a status of 404 (Not Found) texstore.herokuapp.com/:1 Refused to apply style from 'https://texstore.herokuapp.com/static/css/main.0286b08d.css' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled. -
How to limit included page's links to the included page in Django
I have a page in which I have a few links to CSS and JS. When this page is included in another, the links affect the entire page instead of just the bit in the original page. I have a page, featured.html, which has these links in <head>: <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.2.1/dist/css/bootstrap.min.css" integrity="sha384-GJzZqFGwb1QTTN6wy59ffF1BuGJpLSa9DkKMp0DgiMDm4iYMj70gZWKYbI706tWS" crossorigin="anonymous"> <script src="https://cdn.jsdelivr.net/npm/bootstrap@4.2.1/dist/js/bootstrap.min.js" integrity="sha384-B0UglyR+jN6CkvvICOB2joaf5I4l3gm9GU6Hc1og6Ls7i6U/mkkaduKaBhlAXv9k" crossorigin="anonymous"></script> <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/popper.js@1.14.6/dist/umd/popper.min.js" integrity="sha384-wHAiFfRlMFy6i5SRaxvfOCifBUQy1xHdJ/yoi7FRNXMRBu5WHdZYu1hA6ZOblgut" crossorigin="anonymous"></script> I'm calling featured.html into another page: {% include "main/featured.html" %} The reason I'm doing this is because the links in featured.html clash with my code, and I don't want to refactor my code to stop Bootstrap affecting everything except that one div I have in featured.html -
Django validate email in Registration Form
Is there a way to validate email format in registration of account in Django? Like I would like to allow users to only use gsfe accounts as their email when they are going to register in the app Thanks in advanced. -
How can I solve problem when I want to use ogr in django?
I'm writing code with Django code. When I want to call spatial data using gdal, it suddenly encounters the following error. It should be noted that gdal is installed on the system and works properly. ImportError: DLL load failed while importing _gdal: The specified procedure could not be found. -
How to get_queryset() in mixin - DRF
I have two viewsets in different views.py files, one of them is related to model A and another is related to model B class AViewSet(ModelViewSet,CustomMixin): a_qs = self.filter_queryset(self.get_queryset()) lst = [] def get_lst: for a in a_qs: lst.append(a) return lst class BViewSet(ModelViewSet,CustomMixin): b_qs = self.filter_queryset(self.get_queryset()) lst = [] def get_lst: for b in b_qs: lst.append(b) return lst class CustomMixin: @action(detail=False, methods=['get']) def do_smth(self): result_list = self.get_list() As long as self.filter_queryset(self.get_queryset()) part is generic for both viewsets, can I put it in mixin? How will it work? -
Should Django Querysets Be Called in the Templates or Passed Into The Template Context?
I may get blowback from asking this question but it's something I've wondered about for a while so here goes. In a Django template, you can use .all to get the queryset of things, like so: {% for prerequisite in object.prerequisites.all %} <li class="list-group-item">{{ prerequisite.text }}</li> {% endfor %} The model in this case looks like this, but the only relevant piece of information is that object above has a relation to the Prerequisite model through the ForeignKey. class Prerequisite(models.Model): content = models.ForeignKey(Content, on_delete=models.CASCADE, related_name='prerequisites') text = models.CharField(max_length=100) def __str__(self): return str(self.text) My question is Is it best-practice to call Django querysets in the template, (ie: object.prerequisites.all) or should one pass it in the view through the context? def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['prerequisites'] = self.object.prerequisites.all() return context It's really convenient to do querysets in the template, but it seems like it should be business logic located in the view. Does Django have a specific stance on this? -
Django + sqlite error on annotate: Expression contains mixed types: DurationField, IntegerField. You must set output_field
I am building a ranking algorithm built as an expression in Django with a Sqlite database. It is as follows: posts = ( Post.objects.annotate( upvote_count=Count("upvote"), score=ExpressionWrapper( ( (Count("upvote") - 1) / ((Seconds(Now() - F("published_date"))) + 4) ** gravity ) * 100000, output_field=FloatField(), ), ) .filter( publish=True, blog__reviewed=True, blog__blocked=False, show_in_feed=True, published_date__lte=timezone.now(), ) .order_by("-score", "-published_date") .select_related("blog") .prefetch_related("upvote_set")[posts_from:posts_to] ) However I get the following error from the score ExpressionWrapper: Expression contains mixed types: DurationField, IntegerField. You must set output_field. I have specified the output_field and I'm quite certain it should be a float. Any suggestions as to what could be happening here? -
Can't get Django forms to save to User and Profile model
I am trying to extend the Django User model by creating a user Profile model. I am able to create the models successfully, but I can't get the information entered into the custom UserCreationForm to save the data. I can't get the new forms on the same page and get the information related to the User to save. When I try i get the error of 'Anonymous User has to data _meta' models.py class Profile(models.Model): ''' periods = [ ('-','-'), ('1','1'), ('2','2'), ('3','3'), ('4','4'), ('6','6'), ('7','7'), ] ''' user = models.OneToOneField(User,on_delete=models.CASCADE) period = models.IntegerField(default=1) first_name = models.CharField(max_length=100,default='Home') last_name = models.CharField(max_length=100,default='Simpson') def __str__(self): return f'{self.user.username}' forms.py class UserRegisterForm(UserCreationForm): email = forms.EmailField() class Meta: model = User fields = ['username','email','password1','password2'] class UserProfileForm(forms.ModelForm): periods = [ (1,1), (2,2), (3,3), (4,4), (6,6), (7,7), ] period = forms.ChoiceField(choices=periods) first_name = forms.CharField(max_length=100) last_name = forms.CharField(max_length=100) class Meta: model = Profile fields = ['first_name','last_name','period'] signals.py @receiver(post_save,sender=User) def create_profile(sender,instance,created,**kwargs): if created: Profile.objects.create(user=instance) @receiver(post_save,sender=User) def save_profile(sender,instance,**kwargs): instance.profile.save() views.py def login(request): context = { 'title':'Login', } return render(request,'users/login.html',context) def register(request): if request.method == "POST": form = UserRegisterForm(request.POST) if form.is_valid(): email = form.cleaned_data.get('email') email_domain = re.search("@[\w.]+", email) if email_domain.group() == EMAIL_DOMAIN: form.save() username = form.cleaned_data.get('username') messages.success(request,f'Account created for {username}! You are …