Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How do I change the path of an image when linking it in a HTML template?
When a category is clicked on, the user should be shown all of the items that are in that category. However, when I click on a category, the image of the items are not shown because the image is search for in CATEGORY/media/images/... (CATEGORY is the name of the category) instead of just /media/images/... This may be due to the fact that the path of the web page starts with the category name itself, so when the images are searched from the path. How do I change the path that the images are searched from? urls.py: path('<str:name>/', views.category, name='category') # so this would end up as a /Electronics/ if the Electronics category was clicked on # so I think that this is why the image are searched from the wrong path - it is searched from /Electronics/media/images/... category.html: <div class="listings-container"> {% for i in listings %} <div class="listing"> {% if i.photo_present != None %} <div class="img-container"> {% if i.photo_url != None %} <div class="img-center"> <a href="{% url 'listing' i.pk i.name %}"> <img src=" {{ i.photo_url }} " alt=""> </a> </div> {% else %} <div class="img-center"> <a href="{% url 'listing' i.pk i.name %}"> <img src=" media/{{ i.photo_upload }} " alt=""> </a> … -
create Django object with FileField using `File` wrapper and in-memory-file?
I am trying to build a functionality in my application where an In-memory PDF file will be created and that file will get saved on a FileField in my Document model. Explaination of the process: from io import BytesIO from PyPDF2 import PdfWriter in_memory_file = BytesIO() writer = PdfWriter() writer.add_blank_page(height=200, width=200) writer.write(in_memory_file) # The contents of the `writer` got saved to the `io` file To save the above created file we can do the following with open('new_local_file.pdf', 'wb') as local_file: local_file.write(in_memory_file.getbuffer()) The above code is working fine in terminal but since I cannot create local copies in my Django app, I have to do something like this to save the file from django.core.files import File obj = Document.objects.create(file_result=File(in_memory_file.getbuffer())) The File wrapper accepts the python file object but still the above code is not working. After execution no file is getting created in my Django Admin Please comment if you need any more info. -
how do i access the object referenced by Django GenericForeignKey
I don't know exactly how to access the object referenced by the generic foreign key class Cart(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE,related_name='cart_items') product_type = models.ForeignKey(ContentType, on_delete=models.CASCADE, limit_choices_to=limits) product_id = models.UUIDField() content_object = GenericForeignKey('product_type', 'product_id') quantity = models.PositiveSmallIntegerField() I want to access the object referenced by the content_object field how do I do that exactly? -
How to get all data on page? Django
How to get all data on web-page more correctly using Django? from django.http import HttpResponse from .models import Student def get_students(request): students = Student.objects.all() return HttpResponse(''.join(f'<p>{student}</p>' for student in students)) -
What is function in django decorators
1.I have a django decorator but i don't know what is the meaning of function argument, like here by default it is set to None, what does that mean and what does actual_decorator(function) means? 2.also how does the condition 'if function' returns True while my function is None def teacher_required(function=None,): actual_decorator = user_passes_test( lambda u: u.is_teacher,) if function: return actual_decorator(function) return actual_decorator also what does sending argument to actual_decorator means? another question how can i return a permission denied error on decorator failure instead of login page? -
Type Error: Field 'id' expected a number but got <User: ILador>
I am working with Django models and Django-Rest-Framework. When I try to access the models through the Rest-Framework I get "TypeError at /home/profiles/: Field 'id' expected a number but got <User: ILador>." here's my code: Models.py- from django.db import models from django.contrib.auth.models import User from django.core.validators import MaxValueValidator, MinValueValidator from datetime import date from .countries import COUNTRIES class Profile(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) def username(self): usern = User.objects.get(id=self.user) usern = usern.username return usern setup = models.BooleanField(default=False) dob = models.DateField() def age(self): today = date.today() age = today.year - self.birthday.year - ((today.month, today.day) < (self.birthday.month, self.birthday.day)) return age orgin = models.CharField(max_length=300, choices=COUNTRIES) lives = models.CharField(max_length=300, choices=COUNTRIES) bio = models.CharField(max_length=150) email = models.CharField(max_length=255) hobbies = models.CharField(max_length=225) image = models.ImageField(upload_to='images') Serializers.py- from rest_framework import serializers from .models import Profile from django.contrib.auth.models import User from rest_framework.authtoken.models import Token class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields =('id', 'username', 'password') extra_kwargs = {'password': {'write_only': True, 'required': True}} def create(self, validated_data): user = User.objects.create_user(**validated_data) Token.objects.create(user=user) return user class ProfileSerializer(serializers.ModelSerializer): class Meta: model = Profile fields=( 'id', 'username','email', 'setup', 'dob', 'age', 'orgin', 'lives', 'bio', 'hobbies', 'image',) Why am I getting this error? -
Django depoyment with mysql database on personal server
I am working on deploying my Django project on Linode. My MySQL database that I used during development was on a ubuntu server that I have at my house. This was different that the computer that I wrote the program on. In the settings.py file, I had the database connections set up and working. On my personal server at home, I have updated the UFW to allow the new linode ip address and granted privileges to the ip address also. When I go to run the server on deployed project on linode, I get an error (2003, "Can't connect to MySQL server on 'personal server ip address':3306' (110)"). How do I get the linode server to be able to talk to my personal server's MySQL database? Thank you!! -
Djnago CheckboxSelectMultiple group
I want to create dependent select fields. For example, if I сhoose PROCEEDING_CHOICES[0][1] of model Card I can't choose any of options field first_dispute. Different situation: if I choose CHOICES[1][1] of model FirstDispute I can't continue my work with field second1_dispute. How to implement it? models.py class FirstDispute(models.Model): CHOICES=( ('1', '01 О заключении, изменении и расторжении договоров'), ('2', '02 О недействительности сделок'), ('3', '03 О неисполнении или ненадлежащем исполнении обязательств по договорам'), ... ) value = models.CharField("Категория спора (подкатегория 1):", max_length=122, choices=CHOICES, default=CHOICES[0][1]) def __str__(self): return self.value class Card(models.Model): PROCEEDING_CHOICES =( ('Административное', 'Административное'), ('Интеллектуальное', 'Интеллектуальное'), ('Экономическое', 'Экономическое'), ) SECOND1_DISPUTE = ( ('None', 'Выбирается при значения "Подкатегория 1" - "01 О заключении, изменении и расторжении договоров"'), ('01.01 о понуждении к заключению договора', '01.01 о понуждении к заключению договора'), ... ) proceeding = models.CharField("Вид судопроизводства:", max_length=16, choices=PROCEEDING_CHOICES, default=PROCEEDING_CHOICES[0][1]) first_dispute = models.ManyToManyField(FirstDispute) second1_dispute = models.CharField("Категория спора (подкатегория 2-1)", max_length=122, choices=SECOND1_DISPUTE, blank=True, null=True) filters.py class CardFilter(django_filters.FilterSet): proceeding = django_filters.MultipleChoiceFilter(choices=Card.PROCEEDING_CHOICES, label="Вид судопроизводства (выберите подходящее значение)", widget=forms.CheckboxSelectMultiple()) first_dispute = django_filters.MultipleChoiceFilter(choices=FirstDispute.CHOICES, label="Первая подкатегория спора (выберите подходящее значение)", widget=(forms.CheckboxSelectMultiple())) second1_dispute = django_filters.MultipleChoiceFilter(choices=Card.SECOND1_DISPUTE, label="Вторая (1) подкатегория спора (выберите подходящее значение)", widget=(forms.SelectMultiple())) class Meta: model = Card fields = [ 'first_dispute'] -
Django Testing Client POST Request, Getting 403 Error
I'm trying to test some client requests for the first time, and I am able to successfully sent a POST request to register a new user. However, when I attempt to login, I receive a 403 error and I'm not sure what is causing it... thinking maybe I've missed something in the test? I am successfully able to login on my deployed app. Error message: ====================================================================== FAIL: test_user_login_POST (jwt_auth.tests.TestUsers) ---------------------------------------------------------------------- Traceback (most recent call last): File "/Users/jz/Development/BetterCred/jwt_auth/tests.py", line 32, in test_user_login_POST self.assertEqual(response.status_code, 202) AssertionError: 403 != 202 ---------------------------------------------------------------------- Ran 3 tests in 1.416s Test: def setUp(self): User.objects.create( username = 'JohnnyBoy', password = 'pass123!', email = "email@gmail.com", first_name = "John", last_name = "Smith", ) def test_user_login_POST(self): req_url = reverse('user-login') login_details = { 'username': 'JohnnyBoy', 'password': 'pass123!' } response = self.client.post(req_url, login_details, content_type="application/json") print(response) self.assertEqual(response.status_code, 202) View (I added code=404 to see if my test was hitting that point, but doesn't seem like it): class LoginView(APIView): # POST - Login a user and return a token def post(self, request): # Save username and password from request to variables username = request.data.get('username') password = request.data.get('password') # Try to find user, if not found, return an ambiguous error try: user_to_login = User.objects.get(username = username) … -
I get AttributeError: 'HttpResponse' object has no attribute 'endswith' when calling window.location.reload(True) from script
i tried to reload my website just after i update the data so i tested function first adding it to management/commands an with plan to import it later: from django.core.management.base import BaseCommand from django.http import HttpResponse class Command(BaseCommand): help = 'reload page' def handle(self, *args, **kwargs): return HttpResponse("<script>window.location.reload(True);</script>") self.stdout.write("page reloaded") but whe i run puthon manage.py reload i get this error: File "C:\_dane\python\django\cryptosloth.live\venv\lib\site-packages\django\core\management\base.py", line 169, in write if ending and not msg.endswith(ending): AttributeError: 'HttpResponse' object has no attribute 'endswith' i tried many different version of this function, played with adding BASE_DIR = os.path.dirname(os.path.dirname(__file__)) STATIC_ROOT = os.path.join(BASE_DIR, 'static') i don't know why - just read some solution to other 'HttpResponse' object has no attribute problem. -
how can i solve too many values to unpack (expected 2) working with django?
guys im working with django , i have a html file that is related to a section of the site, here is my convertion.html file: {% extends 'dashboard/base.html' %} {% load static %} {% block content %} <div class="container text-center"> <form method="POST"> {% csrf_token %} <div class="form-group"> <legend class='border-bottom mb-4'></legend> {{form}} ######## <button href="" class="btn btn-outline-info" type="submit"> Select </button> </div> <fieldset class="form-group"> <legend class="border-bottom mb-4"></legend> <div class="row"> </div> </fieldset> <fieldset class="form-group"> answer </fieldset> <div class="form-group"> <button href="" class="btn btn-outline-info" type="submit"> Convert </button> </div> </form> </div> {% endblock content %} also my view.py: def conversion(request): form = ConversionForm() context = { 'form':form, 'input':False } return render(request, 'dashboard/conversion.html',context) and my forms.py: class ConversionForm(forms.Form): CHOICES = [('length'),('Length'),('mass'),('Mass')] measurment = forms.ChoiceField(choices = CHOICES, widget=forms.RadioSelect) that part i puted #####, is when i add it to my code, An error occurs: Error: Exception Value:too many values to unpack (expected 2) also this can i see in errors: Error during template rendering In template C:\Users\peima\AppData\Roaming\Python\Python310\site-packages\django\forms\templates\django\forms\table.html, error at line 16 -
django is not using my custom translation
I have a django project with django rest framwork. I want a multi language project and I am trying to have my custom translation. I use drf document https://www.django-rest-framework.org/topics/internationalization/#adding-new-translations and also django document and other sources but know django is still using drf default translation. my overriding is not applied and new strings are no translated. eg I override this line in .po file msgid "Username" msgstr "" to msgid "Username" msgstr "یوزنیم" but it is translated to "نام کاربری" and I add this line msgid "there is a user with this national id" msgstr "سامتینگ" and use that message as a serializer unique validator error but it is not translated national_id = serializers.CharField(validators=[validate_national_id, UniqueValidator(queryset=User.objects.all(), message='there is a user with this national id') ], allow_blank=True) -
странное поведение в браузере Chrome
views.py import os import openpyxl import datetime from django.conf import settings from .forms import UploadFileForm from django.shortcuts import render, redirect from openpyxl.styles import numbers from django.contrib import messages from openpyxl.styles import NamedStyle from django.http import HttpResponseRedirect from django.utils.safestring import mark_safe from django.contrib.auth.decorators import login_required @login_required def convert_file_view(request): if request.method == 'POST': form = UploadFileForm(request.POST, request.FILES) if form.is_valid(): try: file = request.FILES['file'] with open(os.path.join(settings.BASE_DIR, 'static', 'files', 'FormA.xlsx'), 'wb+') as f: for chunk in file.chunks(): f.write(chunk) wb = openpyxl.load_workbook( os.path.join(settings.BASE_DIR, 'static', 'files', 'FormA.xlsx'), ) sh1 = wb['Лист1'] row = sh1.max_row column = sh1.max_column for i in range(2, row + 1): for j in range(2, column + 1): if sh1.cell(i, 2).value: if sh1.cell(i, 3).value is None: sh1.cell(i, 3).value = int(0) if len(sh1.cell(i, 8).value) > 2: sh1.cell(i, 8).value = sh1.cell(i, 8).value[0:2] if i: sh1.cell(i, 1).value = i - 1 else: break # удаляем пустые строки count = 0 for i in range(1, row + 1): if sh1.cell(i, 1).value: count += 1 sh1.delete_rows(count + 1, 1048576) messages.success(request, mark_safe('Генерация - успешно.')) wb.save( os.path.join(settings.BASE_DIR, 'static', 'files', 'FormA.xlsx'), ) return redirect('crewlist') except Exception as e: try: file = request.FILES['file'] with open(os.path.join(settings.BASE_DIR, 'static', 'files', 'FormA.xlsx'), 'wb+') as f: for chunk in file.chunks(): f.write(chunk) wb = openpyxl.load_workbook( os.path.join(settings.BASE_DIR, 'static', 'files', … -
Invariant failed: A state mutation was detected between dispatches, in the path 'cart.itemsPrice'. This may cause incorrect behavior
I have a order placement page and I cannot proceed to place the order because of this error. I don't see where exactly any of the state is being mutated, I think it's because the variables are dynamic but it still doesn't make sense to me. Here's my page: import React, { useState, useEffect } from "react"; import { Link, useLocation, useNavigate, useSearchParams, } from "react-router-dom"; import { Form, Button, Row, Col, ListGroup, Image, Card, } from "react-bootstrap"; import { useDispatch, useSelector } from "react-redux"; import Loader from "../components/Loader"; import Message from "../components/Message"; import FormContainer from "../components/FormContainer"; import CheckoutSteps from "../components/CheckoutSteps"; import { createOrder } from "../actions/orderActions"; function PlaceOrderScreen() { const orderCreate = useSelector((state) => state.orderCreate); const { order, error, success } = orderCreate; const dispatch = useDispatch(); const history = useNavigate(); const cart = useSelector((state) => state.cart); cart.itemsPrice = cart.cartItems .reduce((acc, item) => acc + item.price * item.qty, 0) .toFixed(2); cart.shippingPrice = (cart.itemsPrice > 100 ? 0 : 10).toFixed(2); cart.taxPrice = Number(0.082 * cart.itemsPrice).toFixed(2); cart.totalPrice = ( Number(cart.itemsPrice) + Number(cart.shippingPrice) + Number(cart.taxPrice) ).toFixed(2); if (!cart.paymentMethod) { history("/payment"); } useEffect(() => { if (success) { history(`/order/${order._id}`); // dispatch({ type: ORDER_CREATE_RESET }); } }, [success, history]); const placeOrder = () => … -
How to add link in Django admin
I have an admin panel, I would like to add my own link somewhere on top (for example, to my social network). How can I do that? I think I need to change Django's built-in template. -
How can I use a variable defined in a Django method in a Django class. Both are defined in views.py
I have the following: def color(request): color = '#000000' Class Chart(otherclass): def methodchart(self): return ["one", color, "three"] So I want methodchart to return ["one", '#000000', "three"]. How do I call the variable color inside Chart Class? Is it possible? -
Could not deserialize key when sending push notification using django web push
Getting this error: ValueError: ('Could not deserialize key data. The data may be in an incorrect format, it may be encrypted with an unsupported algorithm, or it may be an unsupported key type (e.g. EC curves with explicit parameters).', [_OpenSSLErrorWithText(code=218542222, lib=13, reason=142, reason_text=b'error:0D06B08E:asn1 encoding routines:asn1_d2i_read_bio:not enough data')]) I am trying to use django-webpush to accept a subscription from my service worker and send a push notification to a specific user. This is what I added to my views in Django: subscription = json.loads('{"endpoint" : "https://fcm.googleapis.com/fcm/send/esP-gJr0HoE:APA91bF7swMPi7BGmzy9acg1k3lj8HAkU2BJNsDSXIWKWRdP3Dvbp5UCbfPioI78q7u9bwotaJ7Vo_6naCojdOxnbgFKsWUv7Srd5MlCFVhpBdhkFAasYRAtrh5FnbD1KF5a_xKKHPpN", "expirationTime" : null, "keys" : {"p256dh":"BNUFqA0mrtLFLHUnAhLfM9KGA63YfhrU913mOeuR3O8vNVmm65iSFJ25TIHoyUKPEAUQxQhEPaerjqCX_N9adgQ","auth":"YSorvfN6ZCW-QaJ0GJnK8g"}}') payload = {"head": "Welcome!", "body": "Hello World"} webpush_settings = getattr(settings, 'WEBPUSH_SETTINGS', {}) vapid_private_key = webpush_settings.get('VAPID_PRIVATE_KEY') vapid_admin_email = webpush_settings.get('VAPID_ADMIN_EMAIL') vapid_data = { 'vapid_private_key': vapid_private_key, 'vapid_claims': {"sub": "mailto:{}".format(vapid_admin_email)} } webpush(subscription_info=subscription, data=payload, ttl=0, **vapid_data) -
how to add two ForeignKey(User) in django model
I have a Group model: class Group(models.Model): leader = models.ForeignKey(User, on_delete=models.CASCADE) name = models.CharField(max_length=55) description = models.TextField() joined = models.ManyToManyField(User, blank=True) and I recently added the ability for the leader to pass over their leadership to a different User. This is fine, but then I noticed that I had a created by {{group.leader} at the top of my GroupDetail template, and I figured it would be better to have a founder and a leader that way people can see which User founded the Group vs. who is currently leading it. Now what I'm struggling with is how to implement this. I assume the founder will be correlated with one User and also with the first leader of the Group. At one point both fields will be the same User. But how do I have two ForeignKeys in the same model? Or is there a better way to go about this. As of now the logic to switch leaders is as such: <form method="POST"> {% csrf_token %} {{form.as_p}} <select id="newLeaderSelect"> {% for member in group.joined.all %} {% if member != group.leader%} <option id='newLeader' value={{ member.id }}>{{ member }}</option> {% endif %} {% endfor %} </select> <button>CHANGE LEADER</button> {{form.errors}} </form> <script> let … -
Django rearrange objects inside querySet by index
In my application i have table called "Task". In this table there is a field called priority with a restricted choice of ("High", "Medium", "Low"). I have ordered these by priority which have an order of: High, Low, Medium when i would like the order to be High, Medium, Low. How could i swap Low and Medium inside the querySet around? views.py: tasks = Tasks.objects.values("priority").annotate(count=Count("priority")) output: <QuerySet [{'priority': 'High', 'count': 3}, {'priority': 'Low', 'count': 3}, {'priority': 'Medium', 'count': 3}]> desired output: <QuerySet [{'priority': 'High', 'count': 3}, {'priority': 'Medium', 'count': 3}, {'priority': 'Low', 'count': 3}]> -
Django dynamic change of models filters
I need to create a filter that offers the following filtering categories building on previous. For example, if I chose option[0][1] in first_dispute, then I would continue filtration only by option[1][1] and option[2][1] in second1_dispute. For example, if I chose option[1][1] or option[2][1] in proceeding, I can't choose any of options in second2_dispute. models.py class FirstDispute(models.Model): CHOICES=( ('1', '01 О заключении, изменении и расторжении договоров'), ('2', '02 О недействительности сделок'), ('3', '03 О неисполнении или ненадлежащем исполнении обязательств по договорам'), ... ) value = models.CharField("Категория спора (подкатегория 1):", max_length=122, choices=CHOICES, default=CHOICES[0][1]) def __str__(self): return self.value class Card(models.Model): PROCEEDING_CHOICES =( ('Административное', 'Административное'), ('Интеллектуальное', 'Интеллектуальное'), ('Экономическое', 'Экономическое'), ) SECOND1_DISPUTE = ( ('None', 'Выбирается при значения "Подкатегория 1" - "01 О заключении, изменении и расторжении договоров"'), ('01.01 о понуждении к заключению договора', '01.01 о понуждении к заключению договора'), ... ) SECOND2_DISPUTE = ( ('None', 'Выбирается при значения "Подкатегория 1" - "02 О недействительности сделок"'), ('02.01 о признании сделки недействительной', '02.01 о признании сделки недействительной'), ... ) THIRD_DISPUTE = ( ('None', 'Выбирается при значениях "Подкатегория 1" - "02 О недействительности сделок" и "Подкатегория 2" - "02.03 о признании торгов недействительными"'), ('02.03.01 о признании незаконными решения и (или) действия (бездействия) организации либо членов комиссии', '02.03.01 … -
How can I see the display of a specific user?
You can see the user's home by pressing the user's photo like twitter or instagram. I want to do this with django, how do I change the url.py User urls.py urlpatterns = [ path('home/', HomeView.as_view(), name='home'), path('edit_profile/', ProfileEditView.as_view(), name='edit_profile'), # 追加 path('commnet_list_movie/', Comment_List_Movie.as_view(), name = 'comment_list_movie'), path('commnet_list_tv/', Comment_List_TV.as_view(), name = 'comment_list_tv'), path('password_change/', PasswordChange.as_view(), name='password_change'), path('password_change/done/', PasswordChangeDone.as_view(), name='password_change_done'), path('password_reset/', PasswordReset.as_view(), name='password_reset'), path('password_reset/done/', PasswordResetDone.as_view(), name='password_reset_done'), path('password_reset/confirm/<uidb64>/<token>/', PasswordResetConfirm.as_view(), name='password_reset_confirm'), path('password_reset/complete/', PasswordResetComplete.as_view(), name='password_reset_complete'), ] -
How to add custom action to Django Admin Save button
I'm trying to add a custom action to the save button in the admin interface. Basically, when the user changes the form and hits the save button, I don't want to change the default save action but I want to add custom functionality. Like; getting some or all data from the form and calling an endpoint or calling an other function. User saves -> Default save action happens -> *Custom action happens I'm aware that I can overwrite save_model of ModelAdmin with: class MyAdminView(admin.ModelAdmin): def save_model(self, request, obj, form, change): super().save_model(request, obj, form, change) # add custom feature <-- but I'm not really sure if this is the appropriate way to do this -
Running Django on Google Colab doesn't work
I tried to run a Django server in Colab as described in this question on stackoverflow. I did set ALLOWED_HOSTS = ['colab.research.google.com'] in settings.py. But when I run the server I always get "Error 403 (Forbidden)!!" when I open the link. Is it not possible anymore to run Django from Colab? -
How to get the image size in python as Megabyte or Kilobyte
I want to the image size of an image in megabyte or kilobyte. This type of question has been asked before and a solution wasn't really provided. NOTE:i'm not concerned with the image width and height, just the file size in megabyte or kilobytes because i'm working on the image for user input validation so its on the fly. -
I am receiving recurssionError at /register/ (django rest framework)
I have create my register endpoint with DRF, so far it has been working well but since I am trying it again it is sending error. serializers.py class RegisterSerializer(serializers.ModelSerializer): password = serializers.CharField(write_only=True,max_length=68,min_length=8,error_messages= {"min_length":f"Password must be longer than {MIN_LENGTH}characters"}, required=True, validators=[validate_password]) password2 = serializers.CharField(write_only=True,max_length=68,min_length=8,error_messages={"min_length":f"Password must be longer than {MIN_LENGTH}characters"}, required=True) class Meta: model = User fields = ('username','phone','password','password2') extra_kwargs = { 'password': {'write_only': True}, 'password2': {'write_only': True} } def validate(self,data): if data["password"]!=data["password2"]: raise serializers.ValidationError("password does not match!") return data def create(self,validated_data): user = User.objects.create( phone=self.validated_data['phone'], username=self.validated_data['username'], ) user.set_password(validated_data['password']) user.save() return user views.py class RegisterViewSet(viewsets.ModelViewSet): http_method_names = ['post'] '''This endpoint is made to register all user with phone number and password''' queryset = User.objects.all() serializer_class = RegisterSerializer ```