Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to get choice data from database and style the form fields in django
please i need a solution to this problem: i have a model called transaction, and a form called TransactionForm as below I want to style the form so i can get a select element for the vehicle and checkbox element for the services when i render it in my template. although am able to make that happen for the vehicle but unable to make it possible for services . rendering the form without the styling works very well but with styling i dont get the choice data from database. how do i achieve this pls class Transaction(models.Model): name= models.CharField(max_length=200,null=True) vehicle = models.ForeignKey(Vehicle, on_delete=models.SET_NULL, null=True) services = models.ForeignKey(ServiceType, on_delete=models.SET_NULL, null=True) updated = models.DateTimeField(auto_now=True) created = models.DateTimeField(auto_now_add=True) def __str__(self): return self.user.get_full_name() TransactionForm class TransactionForm(forms.ModelForm): class Meta: model = Transaction fields = "__all__" exclude = [ 'user'] vehicle = forms.ModelChoiceField( queryset=Vehicle.objects.all(), required=True, label='Select vehicle Type', widget=forms.Select(attrs={ 'placeholder':'Select vehicle Type', 'class':'form-select' })) services = forms.MultipleChoiceField( required=True, label='Select Service Type', widget=forms.CheckboxSelectMultiple( choices=[(service.pk, service.name) for service in ServiceType.objects.all()], attrs={ 'class':'form-select' })) -
How to filter data max marks with attributes from models to view in Django-rest-framework Api?
from rest_framework import viewsets from rest_framework.decorators import api_view from rest_framework.response import Response from .models import StudentDetails, Course, Subjects, Teachers, Marks from .serializers import * from django.db.models import Avg, Max, Min @api_view(['GET']) def studentlist(request,*args,**kwargs): max_marks = Marks.objects.filter(student_id=30).aggregate(total_marks=Max('total_marks')) ['total_marks'] serializer = StudentDetailsSerializers(max_marks, many=True) return Response(serializer.data) OUTPUT: HTTP 200 OK HTTP 200 OK Allow: GET, OPTIONS Content-Type: application/json Vary: Accept [] I'm trying to figure out max of total marks from model name Marks using DRF API, After runing server it showing nothing, Is there to add any line above code to find max(total_marks). -
Django - How to add multiple objects one after another
I want to make a Quiz app, u will enter the app and u will have 2 buttons: Create a Quiz Solve a Quiz When you press "Create a quiz" you will need to insert your name and press a button that takes you to add a new question in that quiz.I can only add one question, after i press submit it stops. The problem is that i want to continuously add questions and stop when i added enough. Each question to have a button Add Next Question that automatically saves the question and goes to add the next one and the Finnish Quiz button that stops the proccess of adding questions.I dont know how to add the questions continuously. Views.py from django.shortcuts import render from django.urls import reverse_lazy from django.views.generic import CreateView, TemplateView, DetailView from quiz.forms import QuestionForm, QuizIdentifierForm from quiz.models import Question, QuizIdentifier # HOMEPAGE class HomeTemplateView(TemplateView): template_name = "quiz/homepage.html" # QUIZ class QuizCreateView(CreateView): template_name = 'quiz/add_quiz.html' model = QuizIdentifier form_class = QuizIdentifierForm def get_success_url(self): return reverse_lazy('add-question', kwargs={'quiz_id': self.object.pk}) class QuizDetailView(DetailView): template_name = 'quiz/detail_quiz.html' model = QuizIdentifier # QUESTION class QuestionCreateView(CreateView): template_name = 'quiz/add_question.html' model = Question success_url = reverse_lazy('home') form_class = QuestionForm def form_valid(self, form): res = … -
Universal password for effective handling of bug reports
When a user of my website submits a bug report, I would like to be able to log into the staging website (so that a non-production copy of the database is used) as him to see exactly what he sees. I could achieve this by changing his user email address to mine and then resetting the password. However, it would simplify things if I could enable a universal password for the staging website, using which I could login as any user. Is there a way to achieve this with Django authentication? -
Validation of reset password link in DJANGO
So I already know that the default Time of Validation for the password reset link is 3 days, . from - https://docs.djangoproject.com/en/4.0/ref/settings/#password-reset-timeout but what happen if i send 3-4 mails for reset password,i use only one of them - what about the another links ? as i say i sent 3-4 mails so i have 3-4 links. If I used one link will the rest of the links no longer be valid? someone know how its work ? -
Is there any way to convert pdf file created with reportlab into file without saving it(in the code)?
Is there any way to convert pdf file created with reportlab into file without saving it(in the code)? I want to return back this file in django without saving it in the computer What i do now is: c = canvas.Canvas(filename) f = open(filename,encoding="ISO8859-1") os.remove(filename) response = HttpResponse(f, content_type='application/pdf') response['Content-Disposition'] = 'attachment; filename="' + filename + '"' return response -
How to get user daily average login time django
i am storing every user login time (how many times user logged in portal) so i need every user average time? **models.py** class AllLogin(models.Model): user = models.ForeignKey(Account,on_delete= models.CASCADE) login_date = models.DateField(null=True) # user login date store with custom date field login_time = models.TimeField(auto_now_add=True,null=True) # user login time stores this time will be generating automatically once login into the user page def __str__(self): return str(self.user) + ': ' + str(self.login_time) This is my views code class ListUsers(generics.GenericAPIView): def get(self,request): # last_month = datetime.today() - timedelta(days=0) m = datetime.date.today() login_details = AllLogin.objects.filter(login_date__gte=m).values('login_time').annotate(total=Count('login_time')) return Response( status=status.HTTP_404_NOT_FOUND) -
prefetch_related in Django displaying all objects instad of related ones
I am trying to get a list of all categories and below each category the list of all related articles. The problem is that I am getting the list of all articles under each category. I read documentation and few answers but nothing seems to be working and I am not suer where I am making the mistake. models.py class Category(models.Model): title = models.CharField(max_length=75, default='', blank=False, null=False) body = CharField(max_length=2000, default='', null=True, blank=True) slug = models.SlugField(unique=True, blank=True) publish = models.DateTimeField('publish', default=timezone.now) class Meta: ordering = ('-publish',) verbose_name = 'category' verbose_name_plural = 'categories' get_latest_by = 'publish' class Article(models.Model): id = models.AutoField(primary_key=True) author = models.ForeignKey(User, blank=True, null=True, on_delete=models.SET_NULL) #settings INSTALLED_APPS title = models.CharField('title', max_length=200) body = CKEditor5Field('Body', config_name='extends') last_updated = models.DateTimeField(auto_now=True) publish = models.DateTimeField('publish', default=timezone.now) #tags = TagField(required=False, widget=LabelWidget) category = models.ForeignKey(Category, on_delete = models.CASCADE, blank=True, related_name='category') slug = models.SlugField(unique=True, blank=True) views.py @login_required def hal_home(request): category_related_articles = Article.objects.prefetch_related('category').all() context = { 'category_related_articles': category_related_articles } return render(request, 'hal/homepage.html', context) homepage.html {% for category in top_categories %} <div class="btn btn-light text-center text-justify"> <div>{{ category.title }}</div> </div> <br> <p>{% for article in category_related_articles %} {{article.title}}<br> {% endfor %}</p> {% empty %} <div>No categories</div> {% endfor %} -
how to add data to list of dictionaries in Django
I want to add data to list of dictionaries a =[100, 200, 300] b =['apple', 'orange', 'grapes'] c=[] for val in a: c.append({'price':val}) for val in b: c.append({'fruit':val}) print(c) result should be like this: [ {'price':100, 'fruit':'apple'}, {'price':200, 'fruit':'orange'}, {'price':300, 'fruit':'grapes'} -
django chat logs api permission
I'm new to django. Im trying to build a social media app with real time chat using Django Channels. It works just fine so far but permission for chat logs api is not taking effect. A user should only be able to view their own chat logs but currently anyone can make get api call to view others's chat logs. Could you please have a look at the code to see what goes wrong models.py serializers.py views.py permissions.py urls.py -
Cognito can sign out the old user but not the new ones
I am using Cognito to sign up/sign in user/ sign out user with my Django App, however, Cognito can sign out the old user but not the new ones, so basically when user sign up today, and login session wouldn't expire at all( not logging out) even though its I specify 5 minutes to relog as its a payment app it's very wired that old users's session token is expired every 5 minutes but not the new users? -
Django POST method is not working when using JavaScript
I am trying to display a div on submitting a form. It displays the div on submitting the form whereas form is not submitted. Here POST method is used. JavaScript is used to display the div. html file: <form method="POST" name="myFirstForm" id="chform"> {% csrf_token %} <input type="hidden" name="details_id" value="{{details.id}}"/> <input type="hidden" name="details_user_id" value="{{details.user_id}}"/> <input type="hidden" name="user_id" value="{{user.id}}"/> <input type="submit" class="btn btn-danger" id="chat" onclick="return myFunction()" value="Chat Now"> </form> <div class="page-content page-container" id="page-content" style="display:none"></div> JavaScript: <script> document.forms['myFirstForm'].addEventListener('submit', function(event) { // Do something with the form's data here this.style['display'] = 'none'; event.preventDefault(); }); function myFunction() { var x = document.getElementById("page-content"); if (x.style.display === "none") { x.style.display = "block"; } else { x.style.display = "none"; } } </script> views.py: if request.method=='POST': jid = request.POST.get('details_id') print(jid) cjid = request.POST.get('details_user_id') print(cjid) userid = request.POST.get('user_id') print(userid) If I not want to display the div and removes JavaScript code , POST method works.Can anyone suggest a solution to solve this issue? -
Do I need "Istance Templates" and "Virtual Machines" in Django Google Cloud Development?
I am new to Google Cloud, I am trying to deploy a Django app on this host. I followed step by step the tutorial but I got configuration problems (I also asked this stackoverflow question here). Searching through the internet, I've found "Istance Templates" and "Virtual Machines" of Google Cloud. As mentioned here, they look to be necessary to the work of the app, but in the Django tutorial they're not mentioned. So, my question is: are they necessary to make my app work or are they just an extra feature that I could use in the future? -
How to set the value of the original field with django modeltranslation?
I've been adding German model translations using django-modeltranslation and I found out that I've accidentally set the original field values (that are supposed to be in English) to German. So now in the database I have: name: German value (should be English) name_en: English (correct) name_de: German (correct) Is there a way to copy over the name_en values to name either in Python or directly in PostgreSQL? I've read the access/read rules but I'm not 100% sure how they impact what I want to do. -
Shareable function in two jquery files
I have 2 jquery files, but they have the same function, I wanted to use a common file where I can import the similar function to be sharable in other files. e.g first.js file : window.addEventListener('load', function () { (function($) { "use strict"; function add(a, b) { return a + b } })(django.jQuery); }); then another file second.js : window.addEventListener('load', function () { (function($) { "use strict"; function add (a, b) { return a + b } })(django.jQuery); }); I wanted to add this similar function add in a common file like common.js then import it in file first.js and second.js , how is this done ? -
Django: NOT NULL constraint
i am new to django and i get an error when I want to save a list of objects. There are two Objects Hopper (One) and Trade (Many). I am not sure how to save it in the correct way. The Hopper Object is already in the db. So i tried to set the id of the hopper as a foreigin key into the trade object. This is the error on save the tadeArray: django.db.utils.IntegrityError: NOT NULL constraint failed: trade.hopper_id so that means the field is null when i try to save the trades, right? Models (shortened): class Trade(models.Model): # Relationships hopper = models.ForeignKey(Hopper, related_name='trades', on_delete=models.CASCADE) # this should call the error :: django.db.utils.IntegrityError: NOT NULL constraint failed: trade.hopper_id # Fields id_db = models.IntegerField(primary_key=True, default=-1) # ... many attributes trigger_strategy = models.TextField(default=None) type = models.TextField(default=None) class Meta: # Set the table name. db_table = 'trade' # Set default ordering ordering = ['id'] class Hopper(models.Model): # Relationships id_db = models.IntegerField(primary_key=True, default=None) id = models.IntegerField(default=None) open_positions_count = models.TextField(default=None) name = models.TextField(default=None) exchange = models.TextField(default=None) hopper_id = models.TextField(default=None) # ... many attributes paper_trading = models.IntegerField(default=-1) start_balance = models.TextField(default=None) Serializers: class HopperSerializer(serializers.ModelSerializer): class Meta: model = Hopper fields = ['id', 'open_positions_count', 'name', 'exchange', 'hopper_id', … -
How to set empty list [] as default value for ArrayAgg field instead of [None] in django
I have a query: Teacher.objects.alias( raw_courses_ids=ArrayAgg('courses_can_teach', distinct=True), ).annotate( courses_ids=Case( When(raw_courses_ids__contains=[None], then=Value([])), default=F('raw_courses_ids'), output_field=ArrayField(IntegerField()) ) ).values_list( 'courses_ids' ) And I have got an error: django.core.exceptions.FieldError: Cannot resolve expression type, unknown output_field What I have to do? -
Django: how can I convert PayPal script for pay on arrival?
I don't want online payments at this time. I'm setting my e-commerce site so that the courier will send the packages and collect fees. How can I config PayPal script to skip the validations and only register the payments as on arrival for now (by adding a different new button to handle this task)? This is my code: Templates: <script> //generare CSRFToken function getCookie(name) { let cookieValue = null; if (document.cookie && document.cookie !== '') { const cookies = document.cookie.split(';'); for (let i = 0; i < cookies.length; i++) { const cookie = cookies[i].trim(); // Does this cookie string begin with the name we want? if (cookie.substring(0, name.length + 1) === (name + '=')) { cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); break; } } } return cookieValue; } const csrftoken = getCookie('csrftoken'); var amount = "{{ grand_total }}" var url = "{% url 'payments' %}" var orderID = "{{ order.order_number }}" var payment_method = 'ramburs' var redirect_url = "{% url 'order_complete' %}" // Render the PayPal button into #paypal-button-container paypal.Buttons({ // Set up the transaction createOrder: function(data, actions) { return actions.order.create({ purchase_units: [{ amount: { value: amount, } }] }); }, // Finalize the transaction onApprove: function(data, actions) { return actions.order.capture().then(function(orderData) … -
Sending lat lng info to the database Bookmark note on map | geodjango | leaflet
How sending lat lng info to the database and bookmark note on map using geodjango and leaflet? With the source code below, I was able to get the display of the department layer but I couldn't get my hands on writing the information on the cards. The script for the note application does not work.Does the script for writing direct to the map have to be inside our_layers (map, options) function or does it have to be separate? #models.py class Note(models.Model): note_heading = models.CharField(max_length=200, null=True, blank=True) note = models.CharField(max_length=1000, null=True, blank=True) longitude = models.FloatField(null=True, blank=True) latitude = models.FloatField(null=True, blank=True) def __str__(self): return self.note_heading #views.py def note(request): if(request.method == 'POST'): note_heading = request.POST.get('note_heading') note_des = request.POST.get('note_des') latitude = request.POST.get('latitude') longitude = request.POST.get('longitude') note = Note(note_heading=note_heading, note=note_des, latitude=latitude, longitude=longitude) note.save() return render(request, 'note.html') return render(request, 'note.html') #urls.py app_name="note" urlpatterns = [ path('note/', views.note,name="note"), ] #note.html <script type="text/javascript"> function our_layers(map,options){ var osm = L.tileLayer('http://{s}.tile.openstreetmap.org/{z}{y}{x}.png', { maxZoom: 19,attribution: '&copy; <a ref="http://www.openstreetmap.org /copyright">OpenStreetMap</a>' }); osm.addTo(map); var department = new L.GeoJSON.AJAX("{% url 'department' %}", { onEachFeature: function (feature, layer) { if (feature.properties) { var content = "<table class='table table-striped table-bordered table-condensed'>" + "<tr><th>DepartmentName</th><td>" + "</td></tr>" + "<table>"; layer.on({ click: function (e) { layer.bindPopup(content).openPopup(e.latlng); } }); } … -
getting error while using aws to host my django website
I am trying to host my Django project with AWS. I have successfully made an ec2 instance on AWS and when I have executed the required commands on my Linux cmd it works perfectly.I have uploaded my required project on it which is as shown below (var) ubuntu@ip-172-31-81-19:~$ ls en2 final_webpage req.txt var var is the virtual environment that I have created during my project.final_webpage is my project which I have to execute. (var) ubuntu@ip-172-31-81-19:~/final_webpage$ cd form (var) ubuntu@ip-172-31-81-19:~/final_webpage/form$ ls db.sqlite3 en1 form manage.py pip3 subform when I am trying to run my manage.py it is showing an error. (var) ubuntu@ip-172-31-81-19:~/final_webpage/form$ python3 manage.py runserver Traceback (most recent call last): File "/home/ubuntu/final_webpage/form/manage.py", line 11, in main from django.core.management import execute_from_command_line ModuleNotFoundError: No module named 'django' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/home/ubuntu/final_webpage/form/manage.py", line 22, in <module> main() File "/home/ubuntu/final_webpage/form/manage.py", line 13, in main raise ImportError( ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment? this is my python version which I am using (var) ubuntu@ip-172-31-81-19:~/final_webpage/form$ python3 Python 3.9.4 (default, Apr 9 2021, 01:15:05) [GCC 5.4.0 … -
'' 'django.core.management' could not be resolved from source Pylance'', but can still run server
I am starting a Django project and I am using visual studio code. I have created a venv folder, udemy, and a django project folder, mypage, as seen from the folder picture. In manage.py, this code django.core.management has yellow wavy line under it. However, I can still use py manage.py runserver, and the server is actually running. What is happening and how do I solve it? -
How to display multiple uploaded file on template
Hello I am new in Django. This is a multiple file upload with data models. This code is working but The data is not displaying on the template. Please find out how to show this multiple uploaded file on template and display those files in the form of table. I have tried so many times. Please give me a solution. view.py: def create_to_feed(request): user = request.user if request.method == 'POST': machineform = MachineForm(request.POST) form = FeedModelForm(request.POST) file_form = FileModelForm(request.POST, request.FILES) files = request.FILES.getlist('file') #field name in model if form.is_valid() and file_form.is_valid(): feed_instance = form.save(commit=False) feed_instance.user = user feed_instance.save() for f in files: file_instance = FeedFile(file=f, feed=feed_instance) file_instance.save() return render(request,'usermaster/multipleupload.html',{'machineform':machineform,'form':form,'file_form':file_form,'user':user,'files':files}) else: machineform = MachineForm() form = FeedModelForm() file_form = FileModelForm machine = Machine.objects.all() return render(request,'usermaster/multipleupload.html',{'machineform':machineform,'form':form,'file_form':file_form,'user':user,'machine':machine}) urls.py: urlpatterns = [ path('admin/', admin.site.urls), path('multipleupload/', views.create_to_feed), ]+static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT)+static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT) models.py: class Machine(models.Model): machine_name = models.CharField(max_length=200) operation_no = models.IntegerField() def __str__(self): return self.machine_name class Feed(models.Model): user=models.ForeignKey(Machine, on_delete=models.CASCADE) text=models.IntegerField() class FeedFile(models.Model): file = models.FileField(upload_to="documents/") feed = models.ForeignKey(Feed, on_delete=models.CASCADE) forms.py: from django import forms from usermaster.models import Feed, FeedFile, Machine class MachineForm(forms.ModelForm): class Meta: model = Machine fields = '__all__' from django.forms import ClearableFileInput ... class FeedModelForm(forms.ModelForm): class Meta: model = Feed fields = ['text'] class FileModelForm(forms.ModelForm): class Meta: … -
Can inline formset be used in generic CBVs (CreateView or View)?
In a generic CreateView, can I use inline formset instead of usual forms as shown below? class SomeView(CreateView): form_class = MyInlineFormSet If this is possible, do I need to override any other methods? Or, how would you use a inline formset in a CBV? -
How to Iterate data sent from react using form Data in Django
I want to print only names React const sendDataToDjango=async (obj) => { let dependents = [{name: "ashraf", number: 96546},{name: "himanshu", number: 98766}] const data = new FormData(); dependents.forEach(item => { data.append(`dependents[]`, JSON.stringify(item))} ) } <button onClick={sendDataToDjango}>Submit</Button > Django @api_view(['POST']) def getData(request): data = request.data for dicts in data.getlist('dependents[]'): print(dict.get('name') data from react is coming like this: <QueryDict: {'dependents[]': ['{"name":"ashraf","number":96546}', '{"name":"himanshu","number":98766}']}> result should be like this: ashraf himanshu -
Django : Unable to login in django admin
I have extended the AbstractUser model. But I'm not able to login into the Django admin portal even after creating a superuser. I have even checked the status of is_staff=True, is_superuser=True & is_active=True. All the statuses are true but still not able to log in. Models.py from django.contrib.auth.models import AbstractUser from django.contrib.auth import get_user_model from django.contrib.auth.hashers import make_password # Create your models here. class User(AbstractUser): """This Class is used to extend the in-build user model """ ROLE_CHOICES = (('CREATOR','CREATOR'),('MODERATOR','MODERATOR'),('USERS','USERS')) GENDER_CHOICES = (('MALE','MALE'),('FEMALE',"FEMALE"),('OTHER','OTHER')) date_of_birth = models.DateField(verbose_name='Date of Birth', null=True) profile_image = models.ImageField(upload_to='media/profile_images', verbose_name='Profile Image', default='media/profile_images/default.webp', blank=True) bio = models.TextField(verbose_name='Bio') role = models.CharField(max_length=10, verbose_name='Role', choices=ROLE_CHOICES) gender = models.CharField(max_length=6, verbose_name='Gender', choices=GENDER_CHOICES) def save(self,*args,**kwargs): """ This method is used to modify the password field converting text into hashed key""" self.password = make_password(self.password) super(User, self).save(*args, **kwargs) I have used the save method because whenever I update a user the password is used to get stored in plain text.