Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
nested one to many serializer model django
I am trying to create a relationship between databases result : => [ { "id":1, "title":"mobile", "category_two":[ { "id":3, "title":"brand" }, { "id":4, "title":"memory" } ] } ] and i expect : => [ { "id":1, "title":"mobile", "category_two":[ { "id":3, "title":"brand", "category_three":[ { "id":1, "title":"samsung" }, { "id":2, "title":"apple" } ] }, { "id":4, "title":"memory", "category_three":[ { "id":1, "title":"32gb" }, { "id":2, "title":"64gb" } ] } ] } ] // views class get_Category(APIView): def get(self, request): category = CategoryOne.objects.all() serializer = CategoryTwoSerializer(category, many=True) return Response(serializer.data) //serializers class CategoryOneSerializer(serializers.ModelSerializer): class Meta: model = CategoryOne fields = '__all__' class CategoryTwoSerializer(serializers.ModelSerializer): category_two= CategoryOneSerializer(many=True,read_only=True) class Meta: model = CategoryTwo fields = '__all__' depth=5 class CategoryThreeSerializer(serializers.ModelSerializer): category_three = CategoryTwoSerializer(many=True,read_only=True) class Meta: model = CategoryThree fields = '__all__' depth=5 // models class CategoryOne(models.Model): title = models.CharField(max_length=225) def __str__(self): return self.title class CategoryTwo(models.Model): title = models.CharField(max_length=255) categoryone = models.ForeignKey(CategoryOne,related_name='category_two',on_delete=models.SET_NULL,null=True) def __str__(self): return self.title class CategoryThree(models.Model): title = models.CharField(max_length=255) categorytwo = models.ForeignKey(CategoryTwo,related_name='category_three',on_delete=models.SET_NULL,null=True) def __str__(self): return self.title -
Updating value on django model object does not update value on related foreign key model
I have 2 models, House and Room where Room has a foreign key to House: class House(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) name = models.CharField(max_length=50) class Room(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) name = models.CharField(max_length=50) color = models.CharField(max_length=50) house = models.ForeignKey(House, on_delete=models.CASCADE, related_name='rooms') When I run the following test, for some reason the colors are not matching, even though the ids do. Can someone help figure out why? def test_color_change(self): h = House(name='new house') h.save() r = h.rooms.create( name='living room', color='blue' ) r2 = h.rooms.get(name='living room') r2.color = 'green' r2.save() self.assertEqual(r.id, r2.id) self.assertEqual(r2.color, r.color) I've been looking at the django documentation for RelatedManager, but haven't been able to figure it out. I would have expected r and r2 to be pointing to the same object, but apparently they are not. -
Tracking Django sessions with custom cookies
I am looking for a way to track the time users spend on the site. I have found the package django-tracking2, which tracks visitors by the Django session. However, my session expiry is set to 2 weeks, which makes it useless to track daily activity. My thoughts are that I can create a different cookie that expires every day, so that I can use this cookie for tracking. However, I do not quite understand how exactly I would assign a random cookie every day for users, as the Django docs does not quite have examples on this. The desired logic is: When a user opens the app, check if cookie custom_cookie is set If not, create it with a random value (probably uuid4?) The cookie should expire the same day at midnight I have come across this way of creating cookies in the middleware, however I think it will yield different random values in the request and response objects: class MyCookieProcessingMiddleware(object): # your desired cookie will be available in every django view def process_request(self, request): # will only add cookie if request does not have it already if not request.COOKIES.get('custom_cookie'): request.COOKIES['custom_cookie'] = uuid.uuid4() # your desired cookie will be available … -
Django multistep form
I have a multi-step form that is 3 steps but it has 4 forms. In the first form, the user has to choose from two choices. The user's first form choices will determine the next form that will be displayed. The first form template. {% extends 'base.html' %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title></title> {% block head %} {% endblock %} </head> <body> {% block content %} {% if form.customer_choices == 'commercial': %} <form action="{% url 'datacollector:step2aformview' %}" method="post"> {% csrf_token %} {{ form }} <input type="submit" value="Submit"> </form> {% else %} <form action="{% url 'datacollector:step2bformview' %}" method="post"> {% csrf_token %} {{ form }} <input type="submit" value="Submit"> </form> {% endif %} {% endblock %} </body> </html> form.py from .models import CustomerInfo, CustomerDocument from django.forms import ModelForm from django import forms CUSTOMER_CHOICES = [ ('commercial', 'Commercial'), ('private', 'Private'), ] class CustomerTypeForm(forms.Form): customer_chioces = forms.CharField(label="Customertype", widget=forms.RadioSelect(choices=CUSTOMER_CHOICES)) #Commercial customer information class CustomerInfoForm1(ModelForm): class Meta: model = CustomerInfo fields = "__all__" #Private customer information class CustomerInfoForm2(ModelForm): class Meta: model = CustomerInfo fields = ['name1', 'name2', 'name3', 'street', 'house', 'zip1', 'city'] class CustomerDocumentForm(forms.ModelForm): class Meta: model = CustomerDocument fields = ['document'] Views from django.shortcuts import render … -
i keep on getting 404 error for my static file in django 4.1.3
currently trying to implement Dialogflow cx chatbot into a website using Django and Kommunicate watched a Youtube vid and followed it everything works until the last part when trying to get script.js the website just cant get the script.js part tried online solutions but didn't work for me ps its my first time asking a question on stack overflow -
How to render the values without writing the logic in every view, Django?
In my view I want to request data from database, and on other page I also need this information, but I don't want to write this request logic again. views.py def account(request): user_id = request.user.id balance = Customer.objects.filter(name_id=user_id).values("usd").first() bonus = Customer.objects.filter(name_id=user_id).values("bonus").first() context1 = {'usd':balance['usd'], 'bonus':bonus['bonus'], return render(request, 'account.html', context1) def main(request): (here I also need to request balance and bonus) In def main(request): and on other pages I also need balance and bonus, but I don't really want to request this values in every view. Can I somehow write it somewhere once and to render on pages, and do not write it in every view?? -
How to get const from forEach method in javascript?
I have django application with quiz model: class Quiz(models.Model): name = models.CharField(max_length=50) topic = models.CharField(choices=TOPICS, max_length=50) number_of_questions = models.IntegerField(validators=[MinValueValidator(1)]) time = models.IntegerField(help_text="duration of quiz in minutes", default=5) pass_score = models.IntegerField(help_text="score required to pass in %", default=90, validators = [MaxValueValidator(100), MinValueValidator(0)]) difficulty = models.CharField(choices=DIFFICULTY_CHOICES, max_length=10) I get it in view: def quiz_view(request, pk): quiz = models.Quiz.objects.get(pk=pk) return render(request, 'quizes/quiz.html', {'obj':quiz}) Then I get data of obj in html: {% for obj in object_list %} <button class="modal-button" data-pk="{{ obj.pk }}" data-name="{{ obj.name }}" data-topic="{{ obj.topic }}" data-questions="{{ obj.number_of_questions }}" data-difficulty="{{ obj.difficulty }}" data-time="{{ obj.time }}" data-pass="{{ obj.pass_score }}"> {{ obj.name }} </button> {% endfor %} <div id="modal"></div> Then I get data from button in javascript forEach method: let modal = document.getElementById('modal') const modalBtns = [...document.getElementsByClassName('modal-button')] modalBtns.forEach(modalBtn => modalBtn.addEventListener('click', ()=>{ const pk = modalBtn.getAttribute('data-pk') const name = modalBtn.getAttribute('data-name') const topic = modalBtn.getAttribute('data-topic') const numQuestions = modalBtn.getAttribute('data-questions') const difficulty = modalBtn.getAttribute('data-difficulty') const passScore = modalBtn.getAttribute('data-pass') const time = modalBtn.getAttribute('data-time') if(modal.classList.contains('close-modal')){ modal.classList.remove('close-modal') } modal.classList.add('open-modal') modal.innerHTML = ` <p class="text">Are you sure you want to open</p><p class="name_of_quiz"><b>${name}?</b></p> <ul class="description"> <li>Topic: ${topic}</li> <li>Questions: ${numQuestions}</li> <li>Difficulty: ${difficulty}</li> <li>Score to pass: ${passScore}%</li> <li>Time to solve: ${time} min</li> </ul> <div class="buttons-container"> <button class="close-button" onclick="close_modal()">Close</button> <button class="proceed-button" id='start_button' onclick="startQuiz()">Yes</button> </div> ` … -
How to create model object that via user foreignkey, FOREIGN KEY constraint failed?
In my view I am creating the object model, and in this model that I am creating is one field, name=models.ForeignKey(User, on_delete=models.CASCADE). And I am using ForeignKey because in this object can be made multiple time by a single user. And I get an error django.db.utils.IntegrityError: FOREIGN KEY constraint failed Here is the model: from django.contrib.auth.models import User ... class Customer_status(models.Model): name = models.ForeignKey(User, null=True, on_delete=models.CASCADE) creation_date = models.CharField(max_length=28) status=models.CharField(max_length = 8) def __str__(self): return str(self.name) + '_' +str(self.id) And in this view I am creating this model: def status_create(request): if request.user.is_authenticated: print('This print work but after it, is an ForeignKey error') Customer_status.objects.create ( name=request.user, creation_date=datetime.datetime.now(), status='Pending' ) The thing is that I had OneToOne and I couldn't make more than 1 model from 1 user, after I changed it to ManyToMany I have the this error django.db.utils.IntegrityError: FOREIGN KEY constraint failed. When it was models.OneToOne, request.user worked, but when I put ForeignKey, it doesn't work -
Django3.2 connection OneToOneField on related_name object has no attribute 'all'
I have a problem getting data through related_name, it can't find the attribute all(). =( The picture shows my attempts, but they did not lead to a result. -
How can I set Django views depending on api source?
I need to show my django views after login when api boils. But I can't provide this because it validates from a database in django in standard django functions. When the API I set up with Fastapi boils, I can login by generating access_token, but then I cannot authorize my viewsets or condition a condition such as access_token_required. How do you think I can achieve this? views.py def _login(request): if request.method == 'POST': loginPayload = { "username" : request.POST['username'], "password" : request.POST['password'] } loginActionResult = LoginAction(loginPayload).__login__() actionResult = loginActionResult['result'] token = loginActionResult['detail'] if not actionResult: messages.add_message(request, messages.ERROR, token) else: return redirect('chockindex') return render(request, 'account/login.html',context = { "loginform" : UserLoginForm() }) @acces_token_required <========== I want to take a precaution like this def owners(request): return render(request, 'pages/owners.html') and this loginactionfunctions class ApiUrls(): def __init__(self): self.headersDefault = { "User-Agent" : "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:106.0) Gecko/20100101 Firefox/106.0", "Content-Type" : "application/x-www-form-urlencoded", "Accept-Language" : "tr-TR,tr;q=0.8,en-US;q=0.5,en;q=0.3", "accept" : "application/json" } self.loginUrl = "http://127.0.0.1/login" self.bonusRequestsUrl = "http://127.0.0.1/results" class LoginAction(ApiUrls): def __init__(self, loginPayload): super().__init__() self.loginPayload = loginPayload def __login__(self): loginRequest = requests.post( url=self.loginUrl, headers=self.headersDefault, data=self.loginPayload ) loginResponse = loginRequest.json() try: return { "detail" : loginResponse['detail'], "result" : False } except: return { "detail" : loginResponse['access_token'], "result" … -
Can anyone help me out with discount coupons in Python Django?
everyone Currently I am working on a E-Commerce Website, I Need to Implement these Offers on add to cart as the Products are being add the Price should be deducted according to the Offer Provided. The Offers are as follows:- Offer 1- Buy one get one free, Offer 2- 50% off on more than 2000 buy, Offer 3- 30% off on selecting more than 2 products to add to the cart. I have made the E commerce website everything is fine but just don't know how to use the Offer logic and though tried multiple things but nothing worked as it should be working. The offers must automatically work on cart as soon as the products are added and before payment gateway the discount should work and get deducted. -
django DRF Performance problems with logic with multiple conditions
The shopping cart model stores cart items for both guest users and registered users. I provide the guest user a unique key using uuid and save it to the cookie. The situation that I want is to link the cart items that is included in the guest user's status to the login user's cart. So I wrote logic considering 3 situations. When you are a guest user, press the shopping cart button to create a cart model. If you fill up the shopping cart before logging in, remove the unique key of the shopping cart model and update it with your user information. If you press the shopping cart button after logging in immediately, create a cart immediately. Does configuring logic under these three conditions adversely affect performance? Is it common to use multiple conditions like this? Is it overloading the server? Help me improve my logic. thanks @api_view(['POST']) def addToCart(request): user = request.user data = request.data guest_id = request.COOKIE.get('guest_user') #if anonymous user puts item in the cart if not request.user.is_authenticated: cart = Cart.objects.create( guest_id = guest_id ) CartItems.objects.create( cart = cart, product = data['product_id'], product_option = data['product_option'], qty = data['qty'] ) serializer = CartSerializer(cart, many=False) return Response(serializer.data) #if guest_user … -
How to write dynamic data in django template
I want only integer value but string is also being printed in it how do I fix this. I want only integer value -
include self relation data in query in django
i have comment model and i want to include all child comment in list query. in this modal a comment can have parent comment class Comment(models.Model): user = models.ForeignKey( "accounts.CustomUser", on_delete=models.CASCADE) post = models.ForeignKey(Blog, on_delete=models.CASCADE) body = models.TextField(blank=True) parentId = models.ForeignKey( "self", blank=True, on_delete=models.CASCADE, null=True) class Meta: ordering = ['-created_at'] i want to list comments which should include parent commnet data expected array [ { id:1, body:"anything", parentId:{ id:34, body:"second" } }, { //second } ] -
Django 3.2 how to convert an uploaded pdf file to an image file and save to the corresponding column in database?
I have the below code that I used in Django 3.2 which works fine except in 1 point: models.py from django.db import models from django.core.validators import MaxValueValidator, MinValueValidator # Create your models here. from django.core.validators import FileExtensionValidator from django.db.models.signals import post_save, pre_save from pdf2image import convert_from_path from django.conf import settings import os COVER_PAGE_DIRECTORY = 'library_app/coverdirectory/' PDF_DIRECTORY = 'library_app/pdfdirectory/' COVER_PAGE_FORMAT = 'jpg' # this function is used to rename the pdf to the name specified by filename field def set_pdf_file_name(instance, filename): return os.path.join(PDF_DIRECTORY, '{}.pdf'.format(instance.filename)) # not used in this example def set_cover_file_name(instance, filename): return os.path.join(COVER_PAGE_DIRECTORY, '{}.{}'.format(instance.filename, COVER_PAGE_FORMAT)) class Pdffile(models.Model): # validator checks file is pdf when form submitted pdf = models.FileField( upload_to=set_pdf_file_name, validators=[FileExtensionValidator(allowed_extensions=['pdf'])] ) filename = models.CharField(max_length=50) pagenumforcover = models.PositiveIntegerField(default=1, validators=[MinValueValidator(1), MaxValueValidator(1000)]) coverpage = models.FileField(blank=True, upload_to=set_cover_file_name) def convert_pdf_to_image(sender, instance, created, **kwargs): if created: # check if COVER_PAGE_DIRECTORY exists, create it if it doesn't # have to do this because of setting coverpage attribute of instance programmatically cover_page_dir = os.path.join(settings.MEDIA_ROOT, COVER_PAGE_DIRECTORY) if not os.path.exists(cover_page_dir): os.mkdir(cover_page_dir) # convert page cover (in this case) to jpg and save cover_page_image = convert_from_path( pdf_path=instance.pdf.path, dpi=50, first_page=instance.pagenumforcover, last_page=instance.pagenumforcover, fmt=COVER_PAGE_FORMAT, output_folder=cover_page_dir, )[0] # get name of pdf_file pdf_filename, extension = os.path.splitext(os.path.basename(instance.pdf.name)) new_cover_page_path = '{}.{}'.format(os.path.join(cover_page_dir, pdf_filename), COVER_PAGE_FORMAT) # rename … -
Django Form is not updating the user database
I want to update User database using forms.When I trying to update it remains same the database and not update. So to perform this task ? forms.py from django import forms from django.contrib.auth.models import User class updateform(forms.ModelForm): class Meta: model=User fields="__all__" views.py from django.contrib.auth.models import User from .forms import updateform @permission_required('is_superuser')#only superuser can update the data base def upform(request,id): emp=User.objects.get(id=id) if request.method=='POST': frm=updateform(request.POST,instance=emp) if frm.is_valid(): frm.save() return redirect('/') else: frm=updateform(instance=emp) return render(request,'examp.html',{'frm':frm}) examp.html {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <link rel="stylesheet" href="{% static '/examp.css' %}"> <style> td,th{ border:1px solid; text-align:center; padding:10px; } </style> </head> <body> {% include 'include/header.html' %} <form action="/" method="POST"> {% csrf_token %} {{ frm.as_p }} <input type="submit" value="Submit"> </form> </body> </html> How to update the database using this given form. -
How to automatically create data fields in other apps
I want to assign some location to an item and also save it to other app. So, when I make changes to it from one app, the other gets updated too. location.py: class ManageLocation(models.Model): product = models.ForeignKey(Item, on_delete=models.CASCADE) quantity = models.IntegerField() warehouse = models.ForeignKey(Warehouse, on_delete=models.CASCADE) zone = models.ForeignKey(Zone, on_delete=models.CASCADE, default='1') section = models.ForeignKey(Section, on_delete=models.CASCADE, default='1') level = models.ForeignKey(Level, on_delete=models.CASCADE, default='1') where the referenced keys are seperate classes with name and description. ***mainpurchases:*** class MainPurchases(models.Model): METHOD_A = 'CASH' METHOD_B = 'CREDIT' PAYMENT_METHODS = [ (METHOD_A, 'CASH'), (METHOD_B, 'CREDIT'), ] product = models.ForeignKey(Item, on_delete=models.PROTECT) #assign-warehouse #assign-level #assign-zone #assign-section quantity = models.PositiveSmallIntegerField() purchase_price = models.DecimalField(max_digits=6, decimal_places=2) paid_amount = models.DecimalField(max_digits=6, decimal_places=2) date_created = models.DateTimeField(auto_now_add=True) supplier = models.ForeignKey(Supplier, on_delete=models.CASCADE) outlet = models.ForeignKey(Outlet, on_delete=models.CASCADE, blank=True, null=True) payment_method = models.CharField(max_length=6, choices=PAYMENT_METHODS, default=METHOD_A) This is where I want to assign it and save it in managelocations. better approaches are appreciated. -
HandleChange function is not working in reactjs .All the null values from initial state is being posted on django rest framework
//something is not working here idk what.I tried changing e.target.id to e.target.name .That too didnt work. Image.js import axios from 'axios'; class Image extends React.Component { constructor(props){ super(props); this.state = { floor_no:null, distance:null, area:null, no_of_rooms:null, price:null, images: null }; this.handleChange=this.handleChange.bind(this); this.handleImageChange=this.handleImageChange.bind(this); } handleChange = (e) => { this.setState({ [e.target.id]: e.target.value }) }; handleImageChange = (e) => { this.setState({ images:e.target.files[0] }) }; handleSubmit = (e) => { e.preventDefault(); console.log(this.state); let form_data = new FormData(); form_data.append('floor_no',this.state.floor_no); form_data.append('distance',this.state.distance); form_data.append('area',this.state.area); form_data.append('no_of_rooms',this.state.no_of_rooms); form_data.append('price',this.state.price); form_data.append('images',this.state.images,this.state.images); let url = 'http://localhost:8000/'; axios.post(url, form_data, { headers: { 'content-type': 'multipart/form-data' } }) .then(res => { console.log(res.data); }) .catch(err => console.log(err)) }; render() { return ( <div className="App"> <form onSubmit={this.handleSubmit}> <p> <input type="number" id='floor_no' onChange={this.handleChange} value={this.state.floor_no} required/> </p> <p> <input type="number" id='distance' value={this.state.distance} onChange={this.handleChange} required/> </p> <p> <input type="number" name='area' value={this.state.area} onChange={this.handleChange} required/> </p> <p> <input type="number" id='no_of_rooms' value={this.state.no_of_rooms} onChange={this.handleChange} required/> </p> <p> <input type="number" id='price' value={this.state.price} onChange={this.handleChange} required/> </p> <p> <input type="file" id='images' accept="image/png, image/jpeg" onChange={this.handleImageChange} required/> </p> <input type="submit"/> </form> </div> ); } } export default Image; models.py from django.db import models # Create your models here. class RenterInfo(models.Model): username= models.CharField(max_length=100) password=models.CharField(max_length=50) def __str__(self): return self.username def upload_to(instance, filename): return 'images/{filename}'.format(filename=filename) class RentDetails(models.Model): property_type=models.CharField(max_length=10) floor_no=models.IntegerField(null=True) distance=models.IntegerField(null=True) location=models.CharField(max_length=20) images=models.ImageField(upload_to='post_images',null=True) area=models.IntegerField(null=True) … -
How to add user code to web service. I want to enable users to write and embed algorithms in my site
Image Generator WEB Application (2 User Roles) Client (Filled in the data in the fields → Pressed the generate button → Received the image) Creator (Created a new generator → Created user fields → Uploaded the template → Wrote a data handler from the fields → Posted the generator to the network) Question: Implementation of the "Wrote data handler" step. User "Creator" has skills in graphic design programs. Does he know what programming is? Maybe he knows what programming is How to get algorithms from the user? Maybe there are ready-made solutions or examples. Need any information Thank you! I thought to embed No-code, low-code or python. The only example that I know of is a chat bot constructor without code. -
Django: UpdateView not showing the correct BooleanField value in Template
I have below Django Project developed with Generic Class Based View. models.py from datetime import datetime from django.urls import reverse class Product(models.Model): prodName = models.CharField(max_length=50, default=None, unique=True) def __str__(self): return self.prodName class Shipment(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) cost = models.IntegerField(max_length=4) orderDate = models.DateTimeField(default=datetime.now, editable=False) quantity = models.IntegerField(max_length=4) receieved = models.BooleanField() def __str__(self): return f'{self.product}: {self.orderDate} views.py from django.urls import reverse_lazy from django.views.generic import CreateView, UpdateView, DeleteView, ListView from .models import Product, Shipment # Create your views here. class ShipmentListView(ListView): model = Shipment fields = '__all__' class ProductCreateView(CreateView): model= Product fields = ['prodName'] success_url= reverse_lazy('modalform:shipDetail') class ShipmentCreateView(CreateView): model = Shipment fields = ('product', 'cost', 'quantity', 'receieved') success_url= reverse_lazy('modalform:shipDetail') class ShipmentUpdateView(UpdateView): model= Shipment # template_name: str= 'modal_form/shipment_update.html' fields = ('product', 'cost', 'quantity', 'receieved') success_url= reverse_lazy('modalform:shipDetail') class ShipmentDeleteView(DeleteView): model = Shipment success_url= reverse_lazy('modalform:shipDetail') shipment_form.html {% block content %} <div class="border rounded-1 p-4 d-flex flex-column"> {% if not form.instance.pk %} <h3>Create Shipment</h3> {% else %} <h3>Update Shipment</h3> {% endif %} <hr> <form action="" method="post"> <label class="form-check-label" for="product"> Product </label> <select class="form-control" name="product" id="product"> {% for id, choice in form.product.field.choices %} <option value="{{ id }}" {% if form.instance.pk and choice|stringformat:'s' == shipment.product|stringformat:'s'%} selected {% endif %} > {{ choice }} </option> {% endfor %} </select> … -
Django template extension; django.template.exceptions.TemplateSyntaxError: Invalid block tag when trying to load i18n from a base template
I have a base.html template file for Django (4.1.2) as: <!DOCTYPE html> <html lang="en"> {% load static %} {% load i18n %} <head> <meta charset="utf-8"> {% block title %} <title>My Title</title> {% endblock %} </head> <body> {% block content %} {% endblock content %} </body> </html> and an index.html page, at the same level in the /templates folder of my app, extending the base one, as: {% extends "base.html" %} {% block content %} <h1>My Django project</h1> <ul> <li><a href="/admin">{% trans "Admin" %}</a></li> <li><a href="{% url 'foo' %}">{% trans "Foo" %}</a></li> </ul> {% endblock %} But when I browse the latter page, the server returns the following error: django.template.exceptions.TemplateSyntaxError: Invalid block tag on line 6: 'trans', expected 'endblock'. Did you forget to register or load this tag? But if I simply add {% load i18n %} at the second line of the index.html, the page loads fine. What is wrong with the loading of the base template in the index.html page? -
Which is the correct bootstrap5 package to load in Django; django-bootstrap5 or django-bootstrap-v5
I am searching for a CSS framework to use with Django and I end up finding boostrap 5. But there seems to be two packages with almost the same name. So, which one is the correct (if any) bootstrap 5 package to load from PyPi in Django: this one: https://pypi.org/project/django-bootstrap5/ or this one: https://pypi.org/project/django-bootstrap-v5/ ? -
FastAPI: OAuth2PasswordBearer: 422 Unprocessable Entity
I'm trying to make an authenticated route using FastAPI and I got 422 Unpossessable Entity error first, I make Dependency to decode token and return user data get_current_user which takes Depends OAuth2PasswordBearer(tokenUrl="token") then I made the end point get_your_articles the route is: @article_route.get("/your-articles") async def get_your_articles(user: dict = Depends(get_current_user), db: Session = Depends(get_db)): if user is None: raise HTTPException( detail="invalid token, login again", status_code=400 ) try: articles = db.query(models.Article).filter(models.Article.auther_id == user.get("id")).all() return { "msg": "success", "data": articles } except SQLAlchemyError as e: return { "Error": e } I use Depends() to decode the token and return the user oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token") async def get_current_user(token: str = Depends(oauth2_scheme)): credentials_exception = HTTPException( status_code=401, detail="Could not validate credentials", headers={"WWW-Authenticate": "Bearer"}, ) try: payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM]) username: str = payload.get("sub") user_id: int = payload.get("id") if username is None or user_id is None: raise credentials_exception user = { "username": username, "id": user_id } return user except JWTError as e: raise HTTPException( detail=f" Error in jwt {e}" ) and this is the response: -
what is the need of def __str__(self) in django [duplicate]
i have a question about str(self) function in django during one documentation reading i found models.py class Product(models.Model): product_name = models.CharField(max_length=200, unique=True) slug = models.SlugField(max_length=100, unique=True) description = models.CharField(max_length=250, blank=True) price = models.IntegerField() images = models.ImageField(upload_to='photos/products') stock = models.IntegerField() is_available = models.BooleanField(default=True) category = models.ForeignKey(Category, on_delete=models.CASCADE) created_date = models.DateField(auto_now_add=True) modified_date = models.DateTimeField(auto_now=True) def __str__(self): return self.product_name what does this def str(self) do -
Django error happened when I installed debug toolbar
everything was working perfectly before until i installed debug toolbar everything was working perfectly befor until i installed django debug toolbar I don’t understand why it is now saying this in the terminal