Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
DJango Post csrf_token invalid and /favicon.ico not found
I got a problem with DJango. Im trying to send data to a SQL Database in DJango. So I need my token, which I get with {{ csrf_token }}. But when I send the data on the HTML Website, it tells me POST 403 Forbidden and the DJango Terminal says NotFound: /favicon.ico, as well as Forbidden (CSRF token from POST has incorrect length.): /ausgeben/ Does anyone have a solution for this. Down below is the code I`m using for the token request. Thanks! let formData = new FormData(); formData.append("name", name); formData.append("gewinde", gewinde); formData.append("laenge", laenge); formData.append("durchmesser", durchmesser); //formData.append("containerNR", containerNR); formData.append('csrfmiddlewaretoken', token); fetch('/ausgeben/',{ method: 'POST', body: formData }); -
"Got KeyError when attempting to get a value for field `pet_name` on serializer `PatientSerializer`
I am trying to get the most popular pet type with viewsets in django, but when i write this code class PopularPetTypeViewSet(viewsets.ModelViewSet): queryset = models.Patient.objects.all() serializer_class = serializers.PatientSerializer def get_queryset(self): try: return models.Patient.objects.values('pet_type').annotate(count=Count('pet_type')).order_by('-count') except Exception as e: return Response({'error':str(e)}) i get this error "Got KeyError when attempting to get a value for field `pet_name` on serializer `PatientSerializer`.\nThe serializer field might be named incorrectly and not match any attribute or key on the `dict` instance.\nOriginal exception text was: 'pet_name'." my models.py from django.db import models from django.utils.translation import gettext_lazy as _ # Create your models here. class Patient(models.Model): pet_name = models.CharField(max_length=255) cat = 'cat' dog = 'dog' bird = 'bird' PET_TYPE_CHOICES = [ (cat, cat), (dog, dog), (bird, bird), ] pet_type = models.CharField("Select Pet Type", choices=PET_TYPE_CHOICES, null=False, max_length=15) owner_name = models.CharField("Owner Name",max_length=255) owner_address = models.CharField("Owner Address", max_length=255, null=True, blank=True) owner_phone_number = models.CharField("phone", max_length=11, blank=False, default='') def __str__(self): return str(self.id) class PatientAppointment(models.Model): patient_id = models.ForeignKey(Patient, on_delete=models.DO_NOTHING, null=True) #, null=TrueSS) appointment_start_time = models.DateTimeField(_("Appointment start time"), auto_now=False, auto_now_add=False) appointment_end_time = models.DateTimeField(_("Appointment end time"), auto_now=False, auto_now_add=False) description = models.CharField(_("Enter description"), max_length=1024) USD = 'USD' EUR = 'EUR' BITCOIN = 'BITCOIN' PAYMENT_TYPE_CHOICES = [ (USD, USD), (EUR, EUR), (BITCOIN, BITCOIN), ] payment_type = models.CharField("Select payment Type", … -
Django template dispalys wrong/bad data
I am making a CRM system in which there are quite a lot of ordinary things But I stumbled upon a rather non-standard problem The template engine returns incorrect data, although when I display them in the console, everything is in order Screenshots will be below. "Experienced" models got calculated everything properly,but "New" models displaying wrong data Look at the console: It must be None everywhere,but instead im getting data just like I didnt refresh page,but i really did P.S. Im making database queries inseparate functions to which I pass GET parameters What could be the reason of this issue ? Thanks in advance -
How to get data from two different models in Django?
So, I have these two models in my Django application. class Persons(models.Model): name = models.CharField(max_length=254) def __str__(self): return self.name class PersonsImage(models.Model): person = models.ForeignKey(Persons, on_delete=models.CASCADE) image = models.ImageField(upload_to='static/images/', default="") So my question is, how can I query or connect these two models where I can get all the images of a particular person? Thanks in advance. -
Django project cloned form github
mainly please tell the meaning of this code literally confused with it {% encore_entrypoint_js 'page_index' %} {% block title %}{% translate 'AlmaLinux OS - Forever-Free Enterprise-Grade Operating System' %}{% endblock %} 7 {% block description %} 8 {% translate 'An Open Source, community owned and governed, forever-free enterprise Linux distribution.' %}{% endblock %} 9 10 {% block head_end %} 11 <link rel="stylesheet" href="/static/css/second.css"><link rel="stylesheet" href="/static/css/main.css"> 12 13 <link rel="stylesheet" href="/static/css/first.css"> 14 {% endblock %} 15 {% block body_end %} 16 {% encore_entrypoint_js 'page_index' %} *************Check this line it shows an error 17 {% endblock %} 18 19 {% block body %} 20 <section class="al-page-index"> 21 <!-- HERO --> 22 <div class="container al-py-lg"> 23 <div class="row flex-lg-row-reverse align-items-center py-2 py-md-5"> 24 <div class="d-none d-lg-block col-10 col-sm-8 col-lg-6"> 25 {# TODO #} 26 {# <a href="{% url 'showcase_index' %}">#} -
HOW To Filter within a Filter Django
I'm trying to filter category with age range , i want to see people in cirtian gender and then their age range my models from django.db import models # Create your models here. class catagory(models.Model): name = models.CharField(max_length=150) def __str__(self): return self.name class Age(models.Model): range = models.CharField(max_length=150) def __str__(self): return self.range class person(models.Model): name = models.CharField(max_length=100) gender = models.ForeignKey(catagory, on_delete=models.CASCADE) age_range = models.ForeignKey(Age, on_delete=models.CASCADE) @staticmethod def get_person_by_cataegoryID(categoryID): if categoryID: return person.objects.filter(gender=categoryID) else: return person.objects.all() @staticmethod def get_person_by_age_range(AGE_RANGE): if AGE_RANGE: return person.objects.filter(age_range=AGE_RANGE) else: return person.objects.all() def __str__(self): return self.name My views from django.shortcuts import render from .models import catagory,person,Age # Create your views here. def index(request): c = catagory.objects.all() categoryID = request.GET.get('category') AGE_RANGE = request.GET.get('age_range') p= person.objects.all() a = Age.objects.all() if categoryID: persons = person.get_person_by_cataegoryID(categoryID) elif AGE_RANGE: persons = person.get_person_by_age_range(AGE_RANGE) else: persons = person.objects.all() context = { "person": p, "catagory": c, "age": a } context["person"] = persons return render(request, "index.html", context) **My Template ** <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <h2>hello</h2> <div style="display:flex;height:100vh;width:100vw;align-items:center;justify-content:space-around;"> <div style="display:flex;flex-direction:column;"> {% for a in age %} <a href="/?age_range={{a.id}}">{{a.range}}</a> {% endfor %} </div> <div style="display:flex;flex-direction:column;"> <a href="/">All</a> {% for c in catagory %} <a href="/?category={{c.id}}">{{c.name}}</a> {% endfor %} </div> <br> <div style="display:flex;flex-direction:column;"> {% … -
Django: URL path is not working / 404 Page not found
I'm trying to build an API with Django for the first time. To see if everything works, I tried to implement a get method at a "try/" endpoint and return a simple json containing "name":"myname". The django app is running succesfully and the admin page works as intended. The endpoint "admin/try" is not reachable though and returns a 404. I have all the files related to the api in a seperate folder, not in the folder of the actual app. This should, according to some tutorials, not be a problem. This is the GET method I am trying to call at the "try/" endpoint. Its located in views.py in the api folder. from rest_framework.response import Response from rest_framework.decorators import api_view @api_view(['GET']) def tryMethod(request): something = {'name':'myname'} return Response(something) This is the urls.py file in the api folder: from django.urls import path from . import views urlpatterns = [ path('try/', views.tryMethod)] This is the urls.py file in the folder of the actual app from django.urls import path, include from django.contrib import admin from drf_spectacular.views import SpectacularAPIView, SpectacularSwaggerView from . import views urlpatterns = [ path('admin/', admin.site.urls), path('health/', views.health, name='health'), path('schema/', SpectacularAPIView.as_view(), name='schema'), path('docs/', SpectacularSwaggerView.as_view(url_name='schema'), name='swagger-ui'), path('404', views.handler404, name='404'), path('500', views.handler500, name='500'), … -
django permissions for block ip addresses import Blocklist
In django custom permissions for blocking ip addresses it seems its using some sort of model named Blocklist but I don't know how to import this model? from rest_framework import permissions class BlocklistPermission(permissions.BasePermission): """ Global permission check for blocked IPs. """ def has_permission(self, request, view): ip_addr = request.META['REMOTE_ADDR'] blocked = Blocklist.objects.filter(ip_addr=ip_addr).exists() return not blocked -
Django models choices - allow only specific transitions on the admin interface
for a models.IntegerField I can define easily choices with sth = models.IntegerField(choices=( (1, 'sth1'), (2, 'sth2'), (3, 'sth3'), )) . Is there any way where I can restrict the transitions from one value to another one? For instance if the current value is '1', it can go only to '2', but if the current value is '3', it can go to '1' and '2', etc. I need this restriction only on the admin interface. Is there anything built in for that? Thanks. -
How to make requests faster in Django
I have this code which parse a json file which has around 400 URL's and send request to each one based on the search term and retrieve it's status code. When I run this it take's lots of time(more than 10 minutes), I am wondering if there any way I can make this code fetch these URL's and it's status code in less than 10 seconds. views.py def get_sites(request): all_sites = {} if 'name' in request.GET: name = request.GET['name'] with open('sites-data.json') as f: data = json.load(f) mod_data = json.loads(json.dumps(data).replace("{}",name)) for item in mod_data: if mod_data[item]['errorType'] == "status_code": url = mod_data[item]['url'] response = requests.head(url, allow_redirects=False) status_code = response.status_code if status_code == 200: site_data = Search( term = name, sitename = item, is_available = True, ) site_data.save() else: site_data = Search( term = name, sitename = item, is_available = False, ) site_data.save() all_sites = Search.objects.all().order_by('-id') return render(request, 'main/search.html',{"all_sites":all_sites} ) search.html <div class = "container"> <br> <h2 class = "text-center">SEARCH SITES</h2> <br> <form method="GET"> <input type = "text" name = "name" placeholder="Search..." class = "text-center"> <button type = "submit" class = "btn-danger btn-sm">Search</button> </form> </div> -
Django clean method cause is_valid() false
here is my model: class Product(models.Model): category = models.ForeignKey(Category, on_delete=models.CASCADE) name = models.CharField(max_length=200) description = models.TextField(blank=True) price = models.DecimalField(max_digits=10, decimal_places=2) stock = models.PositiveIntegerField() created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) objects = models.Manager() available = ProductStockManager() and I have a form like this: class ProductForm(ModelForm): name = forms.CharField(max_length=200) price = forms.DecimalField(decimal_places=2) description = forms.Textarea() class Meta: model = Product fields = ['category', 'name', 'description', 'price', 'stock'] def clean_description(self): pass def clean_price(self): pass def clean_name(self): pass in my form when I use clean_field() for each field it makes is_valid() False except clean_description() what is this for ? why when I use clean_price(), clean_name() my is_valid() returns False? and why it doesn't when I use clean_description() ? -
The django rest framework is not able to recognize the User defined as foreign key
I'm trying to save a user profile information in a django model. The model is defined as follows class UserProfile(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) reg_date = models.DateTimeField(auto_now_add=True, blank=True) name = models.CharField(max_length=30, blank=True) family = models.CharField(max_length=30, blank=True) phoneNumber = models.CharField(max_length=20, blank=True) def __str__(self) : return self.name + self.family The serializer for the model is defined as: class UserProfileSerializer(serializers.ModelSerializer): class Meta: model= UserProfile fields = ['user', 'reg_date', 'name', 'family', 'phoneNumber'] and the view is as follows: class UserProfileView(viewsets.ViewSet): def create(self, request): UserProfile.objects.create(user = request.user) I'm sending a post request using axios as follows: const a = await ProfileAPI.post('', { headers: { 'Authorization': mytoken } }) in which mytoken is a logged in user token provided by dj-rest-auth API. Although the token is OK and the UserProfileView is executed by the request, I got the following error by the django rest: ValueError: Cannot assign "<django.contrib.auth.models.AnonymousUser object at 0x000001F069C59190>": "UserProfile.user" must be a "User" instance. Am I missed something? Is there any problem with my request or view? Please help me to fix this problem -
How to get real time stock price and plot chart
I'm working on a project in which I have to get the stock price in real time and plot the chart (like tradingview, yahoo etc) in react js. I have found a few APIs on RapidAPI but they allow to limited API call per minute. Tech stack: python, django for back-end and react js for front-end -
How to change the field options in a form view
I need to overide the field options in a FormView. However I am not able to figure out in which method or where exactly in the class I need to do it. Currently I have this for the view: views.py class ManageGroupMembersListView(FormView): model =AadGroupmember template_name = 'permissions/group_members.html' success_url = lazy(reverse, str)("manage_groupmembers") form_class = ManageGroupMemberForm __init__(): self.fields['id_aadgroup'] = ['opt1', 'opt2', 'opt3'] -
How to avoid duplicate objects in django pagination when order_by('?')
I am using viewset in rest framework. I am getting same objects in different paginated pages. How can I avoid it. class Viewset(viewsets.ModelViewSet): queryset = Model.objects.all().order_by('?') serializer_class = MySerializer pagination_class = StandardPagination -
After shutting down computer how to reactivate a django server
'm very new to django web development in python and I'm currently following a course on building a simple django website. The problem is, I went to sleep and decided to shut down my computer. After sometime I need to reactivate the website or something because the website just says 'This site can't be reached'. I opened up the code and I'm not sure if I'm suppose to write a certain command in the terminal or something. The terminal is empty when before it was running the website and had stuff there. I do understand that it is going to stop running the website when I shut down my computer because it's my computer hosting it, but I just need to know how to start running it again. So how do I 're-activate' a django website? -
Django Timesince does not show correct value
I want to display "timesince" value for a date in my application. The date is correct but the timesince value is wrong. Screenshot was taken at August 10, 4:39PM. Received Date and Timesince equivalent The first item should show 30 minutes since time is 4:09PM. Here's my HTML code: <tbody> {% if completed_trips %} {% for trip in completed_trips %} <tr> <td>{{ trip.id }}</td> <td>{{ trip.date_depart }}</td> <td>{{ trip.equipment }}</td> {% for k,v in materials.items %} {% if k == trip.material %} <td>{{ v }}</td> {% endif %} {% endfor %} <td>{{ trip.farm }}</td> <td>{{ trip.destination }}</td> <td>{{ trip.load }}</td> <td>{{ trip.date_arrive }}</td> <td>{{ trip.date_arrive | timesince }}</td> </tr> {% endfor %} {% else %} <tr> <td colspan="9" class="text-center">No trips to show.</td> </tr> {% endif %} </tbody> -
Who will review my coding for my web application?
I am a self-taught web application developer. But I don't know that my code is highly clean, maintainable and augmentability. I want to review my code to someone. The development language is python (django). github https://github.com/YuminosukeSato/MovieReview -
select_for_update not working even though it is inside a transaction
I am trying to fetch a customer object from the db. I have writtern a separate service for that. But my problem is that select_for_update is not working when i try to get customer through it but raw orm query works. Error that i am getting django.db.transaction.TransactionManagementError: select_for_update cannot be used outside of a transaction. Customer service class CustomerService: @staticmethod def get_customer(select_for_update=False, **params_dict) -> Customer: """ param: customer mobile number return: Customer object raises exception INVALID_CUSTOMER if customer does not exist """ try: customer = Customer.objects if select_for_update: customer = customer.select_for_update() customer = customer.get(**params_dict) return customer except Customer.DoesNotExist: raise ParseException(INVALID_CUSTOMER, errors='INVALID_CUSTOMER') This doesn't work- @transaction.atomic def create(self, request, *args, **kwargs): customer = CustomerService.get_customer({"id": customer_id}, select_for_update=True) but this does @transaction.atomic def create(self, request, *args, **kwargs): try: customer = Customer.objects.select_for_update().get(id=customer_id) except Customer.DoesNotExist: raise ParseException(INVALID_CUSTOMER, errors='INVALID_CUSTOMER') -
Django, default migration giving naive datetime error
After setup a Django project. python manage.py runserver works with no problem. But when I run the command python manage.py migrate and set the defualt migration file. it's starts giving raise ValueError("make_aware expects a naive datetime, got %s" % value) ValueError: make_aware expects a naive datetime, got 2022-08-10 07:39:19.737670+00:00 actually, I am not very sure is this version bug or something. I am using 4.1 but even if I downgrade it to 4.0, still having the same error after the migrate command. By the way it's migrating the defaults. But after migration under the applied column of django_migrations table this date 2022-08-10 07:39:19.737670 not suitable for the make_aware. -
AttributeError: type object 'Post' has no attribute 'objects'
My in y django project, i have a post model for my blog, but i have this error ): "AttributeError: type object 'Post' has no attribute 'objects'". my model my serializer my view -
drf error arise when i tryed to request POST : Got a `TypeError` when calling `Item.objects.create()`
I tried to create Item instance. but everytime i tried to request POST, arise type error like this... what should i do..? please please check my problem ㅠ__ㅠ Got a TypeError when calling Item.objects.create(). This may be because you have a writable field on the serializer class that is not a valid argument to Item.objects.create(). You may need to make the field read-only, or override the ItemSerializer.create() method to handle this correctly. TypeError: Item() got an unexpected keyword argument 'category' models.py from django.db import models from django.contrib.auth import get_user_model User = get_user_model() class Category(models.Model): NATIONAL_CHOICES = ( ('outer', '아우터'), ('dress', '원피스'), ('top', '상의'), ('pants', '바지'), ('skirt', '스커트'), ('shoes', '신발'), ('accessory', '악세사리'), ) big_category = models.CharField(max_length=20, choices=NATIONAL_CHOICES) small_category = models.CharField(max_length=20) class Item(models.Model): user_id = models.ForeignKey(User, related_name='item_sets', on_delete=models.CASCADE) category_id = models.ForeignKey(Category, related_name='item_sets', on_delete=models.DO_NOTHING) description = models.TextField() feature = models.TextField() product_defect = models.TextField() size = models.CharField(max_length=6) wear_count = models.IntegerField() price = models.IntegerField() class Location(models.Model): city = models.CharField(max_length=10) gu = models.CharField(max_length=10) dong = models.CharField(max_length=10) class LocationSet(models.Model): item_id = models.ForeignKey(Item, on_delete=models.CASCADE, related_name='location_sets') location_id = models.ForeignKey(Location, on_delete=models.CASCADE, related_name='location_sets') class Photo(models.Model): item_id = models.ForeignKey(Item, on_delete=models.CASCADE, related_name='photo_sets') photo = models.ImageField(upload_to='item_post', blank=True, null=True) class StylePhoto(models.Model): item_id = models.ForeignKey(Item, on_delete=models.CASCADE, related_name='style_photo_sets') user_id = models.ForeignKey(User, on_delete=models.CASCADE, related_name='style_photo_sets') photo = models.ImageField(upload_to='item_post', blank=True, … -
How to merge admin panels from different Django projects?
I want to merge admin panel from two separate projects into one admin panel. Every have their models and admin panel. Is there any way to implement it using Django admin instruments? It seems I have to write at least one private API (from one of this project) to implement it and than add it to another project admin manually. Is there any way to make it easier than implement private API? I've tried to find any cases like that, but I didn't find any. -
Invalid block tag on line 73: 'ifequal', expected 'empty' or 'endfor'. Error after replay is set
I am trying to set the replay button on my web application in Django, I am using django-messages, and I have set all libraries to the latest version for Django and python. Everything was working fine until I tried to set the replay button. inbox.html {% load static %} {% block content %} {% if user.is_authenticated %} {% load i18n %} {% if message_list %} <section class="sidebar"> <div class="sidebar--inner"> <div class="is-settings--parent"> <div class="sidebar-menu"> <ul> <li class="inboxItem isActive"><a href="#0">Inbox (<span class="numCount"></span>) </a></li> <li class="sentItem"><a href="#0">Sent</a></li> <li class="spamItem"><a href="#0">Spam</a></li> <li class="trashItem"><a href="#0">Trash</a></li> </ul> </div> </div> </div> </section> <section class="view"> <section class="emails is-component"> <div class="emails--inner"> <div> <h1 class="email-type">Inbox</h1> {% for message in message_list %} <div class="inbox"> <div class="email-card"> <div class="is-email--section has-img"> <div class="sender-img" style=""> </div> </div> <div class="is-email--section has-content"> <div class="sender-inner--content"> <p class="sender-name">From: {{ message.sender.username }}</p> <p class="email-sum">Subject: <a href="{{ message.get_absolute_url }}"> {{ message.subject }}</a></p> <p class="email-sum">Time: {{ message.sent_at|date:_("DATETIME_FORMAT") </p> </div> </div> <div class="email-action"> <span> <a href="{% url 'messages_delete' message.id %}"> <img src="https://gmailapp.surge.sh/assets/images/trashcan.png" alt="" class="action-icon trash"> </a> </span> <-- This line: --> {% ifequal message.recipient.pk user.pk %} <span> <a href="{% url 'messages_reply' message.id %}"> <img src="" alt="" class="action-icon"> </a> </span> {% endifequal %} </div> </div> </div> {% endfor %} </div> </div> </section> {% … -
How should I go building login serializer & View which uses DRF for Token Authentication?
This is how my Signup Serializer looks like class AuthUserSerializer(serializers.ModelSerializer): class Meta: model = AuthUser fields = ('first_name', 'last_name', 'email', 'password', 'role') def create(self, data): return AuthUser.objects.create(**data) Here is the view of it: class Signup(CreateAPIView): serializer_class = AuthUserSerializer queryset = AuthUser.objects.all() def create(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) user = serializer.save() headers = self.get_success_headers(serializer.data) token, created = Token.objects.get_or_create(user=serializer.instance) return Response({'token': token.key}, status=status.HTTP_201_CREATED, headers=headers) And data is getting inserted in DATA successfully, and token is being generated properly. Now I want to make login endpoint where user will enter his email and password and if true return the token. Kindly assist me, on how should I go building this login serializer & view.