Django community: Django Q&A RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How do I correctly add one model to another in Flutter?
I'm really confused on how do I add director model to my show model. I'm writing Android application in Flutter, that uses local Django Rest API. This is Director Model in Django class Director(models.Model): name = models.CharField(max_length=20) surname = models.CharField(max_length=20) country = models.CharField(max_length=20) image = models.ImageField(null=True, blank=True, upload_to="images/") This is Shows Model in Django class Show(models.Model): name = models.CharField(max_length=50) annotation = models.TextField(max_length=1000) language = models.CharField(max_length=20, null=True) image = models.ImageField(null=True, blank=True, upload_to="images/") director = models.ForeignKey(Director, on_delete=models.CASCADE, null=True) This is Director Model in Flutter import 'package:flutter/widgets.dart'; class DirectorModel with ChangeNotifier { final int id; final String name; final String surname; final String image; DirectorModel({required this.id, required this.name, required this.surname, required this.image}); factory DirectorModel.fromJson(dynamic json) { return DirectorModel( id: json['id'], name: json['name'] as String, surname: json['surname'] as String, image: json['image'] as String, ); } static List<DirectorModel> directorFromSnapshot(List snapshot) { return snapshot.map((data) { return DirectorModel.fromJson(data); }).toList(); } } This is Shows model in Flutter import 'package:flutter/widgets.dart'; import 'package:kulises_app/models/directors.dart'; class ShowsModel with ChangeNotifier { int id; String name; String annotation; String language; DirectorModel director; String image; ShowsModel( {required this.id, required this.name, required this.annotation, required this.language, required this.director, required this.image}); factory ShowsModel.fromJson(dynamic json) { return ShowsModel( id: json['id'], director: DirectorModel.fromJson(json['director']), name: json['name'] as String, annotation: json['annotation'] … -
How to add more param to Serialization Model for using at to_presentation
Here is my so class DataFieldSerializer(serializers.ModelSerializer): class Meta: model = DataField fields = ["field", "topic", "category", "group", "alias", "units"] def __init__(self, *args, **kwargs): self.extra_param = kwargs.pop('extra_param', None) super().__init__(*args, **kwargs) def to_representation(self, instance): data = super().to_representation(instance) print("Extra Param:", self.extra_param) This is how I call the DataFieldSerializer result_data = DataFieldWithUnitsSerializer(data_fields, many=True, extra_param='example').data When I run the code I got this result Extra Param:None I guess it is not the right way to add more param into a model serializer. To sum up, I want to find away to pass an extra param to the Serializer Model -
Why is a shallow copy used with self.cart in this Django Python code?
in this python code, def __iter__(self): """ Iterate over the items in the cart and get the products from the database. """ product_ids = self.cart.keys() # get the product objects and add them to the cart products = Product.objects.filter(id__in=product_ids) cart = self.cart.copy() for product in products: cart[str(product.id)]['product'] = product for item in cart.values(): item['price'] = Decimal(item['price']) item['total_price'] = item['price'] * item['quantity'] yield item Is the Python copy function a shallow copy? Why is it shallow copying self.cart instead of just using self.cart directly? using self.cart directly instead of using variable cart. -
Django allauth telegram provider not working
Has anyone successfully implemented using allauth's telegram provider? I've followed the documentation and everything but it still does nothing. -
Experience auto increment according to DOJ
I have DOJ (Date of Joining) in my Django models and also i have Experience field in my models so according to my DOJ my experience should change daily automatically. This should be done in Django Could anyone please help me on this Thanks in advance -
One to many relationship query in Django ORM, Where I want to query on One table and want to get output with many table data as a list
Here is my model: from django.db import models from django.db.models.expressions import F class Publication(models.Model): name = models.CharField('name of publication', max_length=1024, null=True, blank=True) def __str__(self): return f'{self.name}' class Meta: verbose_name = "Publication" verbose_name_plural = "Publications" class Book(models.Model): name = models.CharField('name of book', max_length=1024, null=True, blank=True) publication = models.ForeignKey(Publication, on_delete=models.CASCADE, null=True, blank=True) def __str__(self): return f'{self.name}//{self.publication.name}' class Meta: verbose_name = "Book" verbose_name_plural = "Book" I want outcome json as single publication with list of book (Please show me using Django ORM query and Django Serializer OR using DRF): Output JSON like below: [ { "id": 1, "name": "publication 001", "book": [ { "id": 1, "name": "Book 001" }, { "id": 2, "name": "Book 002" } ] }, { "id": 2, "name": "publication 002", "book": [ { "id": 3, "name": "Book 003" }, { "id": 4, "name": "Book 004" } ] } ] I tried it through several way but unable to solve it using django orm query. I've done it through raw query. But I wantto implement it through Django ORM Query. SO please help me. TIA -
Filtering the products by price in django
Here im trying to do filtering the products by price View def Shop(request): min_price = Product.objects.all().aggregate(Min('price')) max_price = Product.objects.all().aggregate(Max('price')) FilterPrice = request.GET.get('FilterPrice') if FilterPrice: Int_FilterPrice = int(FilterPrice) product = Product.objects.filter(price__lte = Int_FilterPrice) print(product) else: product = Product.objects.all() Here I got the value in backend <QuerySet [<Product: OnePlus Nord Buds 2 True Wireless in Ear Earbuds with Mic, Upto 25dB ANC>]> by filtering the product by price range HTML here in this HTML code if I click the filter button I got all the products it is not filtered by price <div class="product-widget mb-30"> <h5 class="pt-title">Filter By Price</h5> <div class="price__slider mt-30"> <input type="range" class="multi-range success" style="color:red;" value="{{FilterPrice}}" min="{{min_price.price__min}}" max="{{max_price.price__max}}" id="rangeInput" oninput="maxPrice.value=this.value" width="400px;" /> <div> <form action="" class="s-form mt-20" method="get"> <b>₹</b><input type="number" id="maxPrice" readonly="" name="FilterPrice" onkeyup="rangeInput.value=this.value" value={{FilterPrice}}{{minMaxPrice.price__min}}> <button type="submit" id="priceFilterBtn" class="tp-btn-square-lg">Filter</button> </form> </div> </div> </div> The output I expect: If I click the filter button I want to get the filtered product by price range... -
Extending 'bootstrap/base.html' works fine in Flask but not in Django, how to make it work?
{% extends 'bootstrap/base.html' %} this line works just fine in flask but doesnt work in django how can i make it work this is the head of the page fddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd -
Django ModelForm Validation not validating
Can someone check what i'm omitting here? The Validation error is not showing up even when it should. It's just returning successful when it should've showed a validation error. When I run my server and insert a title less than 5 charcters, it still returns successful instead of raising a Validating error. views.py; def form_view(request): if request.method == 'POST': form = ProductForm(request.POST) if form.is_valid(): post = form.save(commit=False) post.save() return HttpResponse("successful") else: return render(request, "product_create.html", {'form': form}) else: form = ProductForm(None) return render(request, 'product_create.html', {'form': form}) models.py; from django.db import models # Create your models here. class Product(models.Model): title = models.CharField(max_length=120) description = models.CharField(blank=True, null=True, max_length=250) price = models.FloatField() forms.py; from django import forms from .views import Product class ProductForm(forms.ModelForm): class Meta: model = Product fields = [ 'title', 'description', 'price', ] def cleaned_title(self): title = self.cleaned_data.get('title') if len(title) < 5: raise forms.ValidationError("This is not a valid title") return self.cleaned_data template; product_create.html: {% block content %} <form action="." method="post"> {% csrf_token %} {{ form.as_p }} <input type="submit" value="save"> </form>`enter code here` {% endblock %} -
How do I create a tally card for my items in my warehouse management system
I am building a warehouse management system and I want to design a tally card for each item in stock where store officers can receive and issue items in their warehouse and keep the transaction for each item. I want it to update the item balance in stock anytime the user receives and issued like a real-world tally card. I want it to look like this let's assume this is transactions made on item1. | Date | Description |Receive | Issue | Balance | | 1-2-2023 | site1 | | 76 | 235 | | 3-2-2023 | store1 | 50 | | 285 | On the Item list page, I want the user to click on a receive button and it will direct him to a form to enter the quantity he has received and the description and it will automatically update the balance and save that transaction against the item and the same applies to the issue. And when the user clicked on the item, it will display all the transactions made on that item like the table above So far, I have this in my model to save items and their info in the warehouse. Model class Item(models.Model): … -
How can I display the result of steganalysis on my website using Django and HTML?
I am currently developing a website for steganalysis. All codes and functions can be used appropriately, however I could not make the result appear on the page of my website. In this website, I should have produced the result of steganalysis onto the same pagee in its own section but it did not happen. I have intergrated the index.html and views.py according to the mentioned code below. return render(request, 'index.html') For each tasks in views.py, I have included above code, however nothing changed. The result still does not display on the web page. The concept of the website is similar to cyberchef where it does not store any of the analysis tasks. It only perform tasks selected by user and produces the results. -
How do I insert data into Django models with foreign key tables and OneToOne fields?
"Hello everyone, I hope you're doing well. I'm currently facing an issue with inserting data in models with foreign key table and OneToOne field. I've tried inserting data in, but I haven't been able to find a success. It would be great if someone could help me out or provide some guidance on how to resolve this. Any insights or suggestions would be greatly appreciated. Thank you in advance for your time and assistance!" MODELS: class Department(models.Model): department = models.CharField(max_length=100) def __str__(self) -> str: return self.department class Meta: ordering = ['department'] class StudentID(models.Model): student_id = models.CharField(max_length=100) def __str__(self) -> str: return self.student_id class Student(models.Model): department = models.ForeignKey(Department, related_name='depart', on_delete=models.CASCADE) student_id = models.OneToOneField(StudentID, related_name='studentId', on_delete=models.CASCADE) student_name = models.CharField(max_length=100) student_email = models.EmailField(max_length=100) student_age = models.IntegerField(default=18) student_address = models.TextField() def __str__(self) -> str: return self.student_name class Meta: ordering = ['student_name'] verbose_name = 'student' class Subject(models.Model): subject_name = models.CharField(max_length=100) def __str__(self) -> str: return self.subject_name class SubjectMark(models.Model): student = models.ForeignKey(Student, related_name='studentmark', on_delete=models.CASCADE) subject = models.ForeignKey(Subject, on_delete=models.CASCADE) marks = models.IntegerField() def __str__(self) -> str: return f' {self.student.student_name} {self.subject.subject_name} ' class Meta: unique_together = ['student' , 'subject'] I've tried this view but I got only errors. Views def create_student(request): if request.method == "POST": data = request.POST … -
How do I modify a Django filter to search for a specific word and variations with a dash using regex or any other option?
I have this filter filters = Q(my_text__icontains=typed_word) I need to modify it in a way that would works like this: if the typed_word is "ABCD", it should return any ABC that could have a "-" (dash) at any position in the word, examples: would return the "ABCD" itself, but also "A-BCD" and "AB-CD" and "ABC-D" btw any word in the database only have one dash, none of then would have more then one I tried some patterns using something like this my_text__iregex=pattern But no luck -
Django Filter through Form input not working
After clicking on the Filter button it shouldn't return the property with 20000 rent. But that is not happening. Anyone can explain why? I have attached the template, view, and form code below. Template code: <div class="container-fluid"> <div class="row"> <div class="col-sm-3"> <form action="/" method="post"> {% csrf_token %} {{ form }} <input type="submit" value="Filter"> </form> </div> <div class="col-sm-9 row" id="filtered-product"> {% for l in listings %} <div class="card w-25 float-left p-2"> <img src="{{ l.image.url }}" class="img-fluid" alt=""> <h3 class="card-title text-center">{{ l.type }}</h3> <h5 class="card-subtitle text-center">Rent: {{ l.rent }}</h5> <a href="/listings/{{ l.id }}/" class="btn btn-primary"> View details </a> </div> {% endfor %} </div> </div> View: def listing_list(request): form = FilterForm() if form.is_valid(): min_price = form.cleaned_data["minrent"] max_price = form.cleaned_data["maxrent"] listings = listings.filter(rent__gte=min_price) listings = listings.filter(rent__lte=max_price) else: listings = Listing.objects.all().select_related('user') context = { "listings": listings, "form": form } return render(request, "listings/listings.html", context) Form: class FilterForm(forms.Form): minrent = forms.IntegerField() maxrent = forms.IntegerField() -
How to implement authentication in postgresql based on Django?
Сould you explain or explain ? How to properly implement authorization to the django database (without migrations). That is, there is a database, it has a table in which the login and password are stored. We can simply go through authorization when accessing it. How to make it so that when a user registers, the login and password are entered directly into this table (where the login and password are stored)? An account is also created so that you can log into the database itself under this account. Initially, we have a server account connected, and when someone does something, we will see that it is the server account that does it, not the user -
Django template render a nested dict with tuples
Here's my dict = { '123': {'metric_1': [('url_1', 'caption_1'), ('url_2', 'caption_2'), ('url_3', 'caption_3'), ('url_4', 'caption_4')], 'metric_2': [('url_1', 'caption_1'), ('url_2', 'caption_2'), ('url_3', 'caption_3'), ('url_4', 'caption_4')]}, '456': {'metric_1': [('url_1', 'caption_1'), ('url_2', 'caption_2'), ('url_3', 'caption_3'), ('url_4', 'caption_4')], 'metric_2': [('url_1', 'caption_1'), ('url_2', 'caption_2'), ('url_3', 'caption_3'), ('url_4', 'caption_4')]}, '789': {'metric_1': [('url_1', 'caption_1'), ('url_2', 'caption_2'), ('url_3', 'caption_3'), ('url_4', 'caption_4')], 'metric_2': [('url_1', 'caption_1'), ('url_2', 'caption_2'), ('url_3', 'caption_3'), ('url_4', 'caption_4')]}, } it basically is a dict of a dict of a list of tuples. what I'd like to render via Django template is: 123 metric_1 url_1 url_2 url_3 url_4 caption_1 caption_2 caption_3 caption_4 metric_2 url_1 url_2 url_3 url_4 caption_1 caption_2 caption_3 caption_4 456 metric_1 url_1 url_2 url_3 url_4 caption_1 caption_2 caption_3 caption_4 metric_2 url_1 url_2 url_3 url_4 caption_1 caption_2 caption_3 caption_4 789 metric_1 url_1 url_2 url_3 url_4 caption_1 caption_2 caption_3 caption_4 metric_2 url_1 url_2 url_3 url_4 caption_1 caption_2 caption_3 caption_4 but I'm not able to do so, here's my current Django template: <div class="grid grid-cols-2 gap-2 p-2"> {% for one_analysis_id, all_metrics in url_dict.items %} <table> <tr><p>Analysis ID: {{ one_analysis_id }}</p></tr> {% for metric_name, url_and_caption_tuple_list in all_metrics.items %} <tr><p>{{ metric_name }}</p></tr> <tr> {% for url_and_caption_tuple in url_and_caption_tuple_list %} <td><img width="350" height="300" src="{{ url_and_caption_tuple.0 }}"><div>{{ url_and_caption_tuple.1 }}</div></td> {% endfor %} … -
ValueError: libcublas.so.*[0-9] not found in the system path
I'm trying to import and use ultralytics library in my Django rest framework project, I use poetry as my dependency manager, I installed ultralytics using poetry add ultralytics and on trying to import the library in my code I recieve this error ValueError: libcublas.so.*[0-9] not found in the system path [my project and virtual environment paths] so how can I solve that? I tried searching and asking ChatGPT but I didn't reach any thing. -
How to find which site ids I have in Django Admin panel sites
I have deleted my previous site xxx.xxx.com and added a new site xx1.xxx.com. So then in the settings.py I have configured the site id to 2 and, yet it's not giving me the django.contrib.sites.models.Site.DoesNotExist: Site matching query does not exist. error. How can I check the exact site ids I have right now with the shell. Because my admin panel is not loading too. I am pretty new to django. So apologies if this is a very basic one to ask. I tried to change the site id from 1 to 2 -
Django: Problems with Fileresponse in production
Django: Fileresponse works fine in local but it doesnt in deployment In local i did this @login_required @permission_required('plataforma.ADMIN', raise_exception=True) def admin_descargar_planilla(request,plantilla_id): try: plantilla = Plantilla.objects.get(pk=plantilla_id) except: return render(request, "plataforma/error.html",{"tipo_error":"No se puede realizar esta accion ya que la plantilla ya no existe"}) buffer = util.crear_pdf(plantilla) return FileResponse(buffer, content_type='application/pdf', filename=(plantilla.eett.username+" ("+str(plantilla.fecha)+")")) The function crear_pdf returns an io.BytesIO(). When I try to use this views in production I recieve an Internal Server error (500) from the server instead of an django error. In the deployment I'm using openlitespeed. Also I try using an existing pdf instead of a buffer but its worst because i receive error 404 saying the url doesnt exist when it exist (this also works fine in local) -
Hwo to save multiple vlaues, which are reteived from frontend, in database in django Many to Many relationship?
While adding a book, I have to get data from frontend. I created a AddBookForm form. Book and Author have Many-to-Many relationship. From the frontend Form I get the names of the authors for the corresponding book as a list(from dynamic input field). Now the data is saved but is stored incorrectly. I know this is not the optimized way to save many to many relationship data. Please help me do this in an optimized way. models.py: class Book(models.Model): name = models.CharField(max_length=200, null=False, blank=False) description = models.TextField(null=True, blank=True) no_of_copies = models.IntegerField(default=1, null=True, blank=True) status = models.CharField(max_length=15, choices=[('Out of Stock', 'Out of Stock'), ('Available', 'Available')], default='Available') updated_at = models.DateTimeField(auto_now=True) created_at = models.DateTimeField(auto_now=True) def __str__(self): return self.name class Author(models.Model): name = models.CharField(max_length=100, null=True, blank=True) books = models.ManyToManyField(Book) def __str__(self): return self.name class Genre(models.Model): name = models.CharField(max_length=50, null=True, blank=True) books = models.ManyToManyField(Book) def __str__(self): return self.name forms.py class AddBookForm(forms.ModelForm): authors = forms.CharField(max_length=255, required=False) genres = forms.CharField(max_length=255, required=False) class Meta: model = Book fields = '__all__' views.py def add_book(request): if request.method == 'POST': form = AddBookForm(request.POST) if form.is_valid(): book = form.save(commit=False) authors = request.POST.getlist('authors') book.save() for name in authors: author, created = Author.objects.get_or_create(name=name) author.books.add(book) return redirect("/") else: form = AddBookForm() context = {'form': form} … -
django-STATICFILES _DIRS not collecting
In my django project settings, I defined my static files like so: STATIC_URL = 'static/' STATIC_ROOT = BASE_DIR + '/static' STATICFILES_DIRS = [ BASE_DIR +'/folder1', BASE_DIR + '/folder2', ] But collectstatic doesn't collect what is defined in "STATICFILES_DIRS". Even though it works locally, on the server it doesn't work. What am I doing wrong? -
How to add input from textarea tag in Django
I have been trying to fetch input from textarea tag in Django but its not working. this my form <form method="POST" action="/" > {% csrf_token %} <textarea class="form-control" id="comment" name="comment" rows="4"></textarea> <button type="submit" class="btn btn-primary btn-sm">Post comment</button> </form> this is my view ` if request.method=='POST': username = request.user comment = request.POST.get('comment') new_comment = Pcomments(username=username,comment=comment,date = datetime.date.today()) new_comment.save() ` -
Deserializing a nested object using Django Rest Framework ModelSerializer
I have this JavaScript code in the client sending a vacation object to the server: const vacation = { employee: currentEmployee, startDate: form.querySelector('#start-date').value, endDate: form.querySelector('#end-date').value, vacationReason: form.querySelector('#reason').value, status: 'P', }; const newData = new FormData(); newData.append('csrfmiddlewaretoken', getCSRFToken()); newData.append('vacation', JSON.stringify(vacation)); const postReq = new XMLHttpRequest(); postReq.open( 'POST', '/vacations/vacation-list' ) postReq.onreadystatechange = () => { if (postReq.readyState === XMLHttpRequest.DONE) { if (postReq.status === 201) window.location.replace('/vacations'); else prompt('BAD REQUEST.'); } } postReq.send(newData); The problem is that when I try to use VacationSerializer in the vacation_list view, serializer = VacationSerializer(data=json.loads(request.POST.get('vacation')) if serializer.is_valid(): serializer.save() I get serializer.errors: an 'employee' object already exists with this id. And it's essentially meant to be a vacation for an existing employee! I could not find a way to deserialize using ModelSerializer with an existing object as part of the referencing object. These are my ModelSerializers: class EmployeeSerializer(serializers.ModelSerializer): class Meta: model = Employee fields = ['id', 'name', 'name', 'email', 'phoneNumber', 'address', 'gender', 'maritalStatus', 'availableVacationDays', 'approvedVacationDays', 'salary', 'birthDay'] class VacationSerializer(serializers.ModelSerializer): employee = EmployeeSerializer() class Meta: model = Vacation fields = ['id', 'employee', 'startDate', 'endDate', 'vacationReason', 'status'] def create(self, validated_data): employee_data = validated_data.pop('employee') vacation = Vacation.objects.create(**validated_data) vacation.employee = Employee.objects.get(id=employee_data['id']) return vacation I tried the above overriding of the create method, but it … -
trying to use djongo engine to connect to documentdb database using ssh tunnel
pymongo.errors.OperationFailure: namespace name generated from index name is too long, full error: {'ok': 0.0, 'code': 67, 'errmsg': 'namespace name generated from index name is too long', 'operationTime': Timestamp(1684956028, 1)} i'm trying to use djongo engine to connect to documentdb database using ssh tunnel -
Stuck with user profile, where users can submit there products. Can someone please help me?
I'm new to Django and working on a Django classified ads project. I've created models and templates already but now stuck with the user profile section. Where users can update there profile and submit there products, which they want to sell. I've already created super user, but really confused and don't know where to start for multiusers profile section so they users can post their products.