Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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. -
Creating object in bulk and then serialize them
model: class ProductImage(models.Model): post = models.ForeignKey(Product,...) image = models.ImageField(...) view: pobj = Product.objects.get(user=request.user, id=id) nimg = int(request.data['numofimg']) for i in range(nimg): image = request.data[f'image{i}'] obj = ProductImage.objects.create(post=pobj, image=image) pobjs = Product.objects.all() serialerize = ProductImageSeriailzer(pobjs, many=True) # it would be better if pobjs only have newly created objects (in above for loop) Is their any efficient code for the same? Here number of queries will increase with number of image How can i reduce them? -
How to avoid list index out of range in Django ORM query
I have a tricky scenario here ,usually I get 6 values from the below query , basically prices at start and month end of the month, prices value will be there every time trade_date price 01-01-2021 120.2 31-01-2021 220.2 01-02-2021 516.2 28-02-2021 751.0 01-03-2021 450.2 31-03-2021 854.9 and I need Sum of 1st month starting price + 1st month Ending price + every months ending price ie 120.2+220.2+751.0+854.9 but in some cases, last month data tend to miss, how to handle those scenarios monthly_values = Items.objects.filter(trade_date__gte=quarter_start_date, trade_date__lte=quarter_end_date).values_list('price', flat=True).order_by('trade_date') total_sum = monthly_values[0]+monthly_values[1]+monthly_values[3]+monthly_values[5]) Currently getting list index out of range from the above because of missing values -
Get count of second-degree foreign-key entities in Django
We have a data model with three basic models: Group Activity Participant Groups are related (FK) to activities. Activities are related (ManyToMany) to participants. I want to take all activities related to the group and then count all participants of that set of activities. How can I count all activity participants for all group activities from a given group? -
How to properly open a bootstrap modal that is on another file on django
I have a django app with two template file: a page.html and a modal.html and I am trying to implement a system where if a user clicks on a btn on the page.html, the modal.html is rendered as a modal. I tried to do it using django-bootstrap-modal-forms but I couldn't really get what I need because the library seems to be built around creating modals and forms in a very specific way. Specifically, the problem I am facing with this implementation is that if a user "close" the modal they are sent to another url and not to the page.html url. So basically the modal isn't dismissed properly. This is what I did so far but I am really open to different approaches using Bootstrap only. page.html ... <a id='UploadFile' class="list-files__btn-plus" href="#"> <img src="{% static 'action/img/project/files/icon_plus-file.svg' %}" alt="+"> </a> ... <script src="{% static 'action/js/project/files/files.js' %}"></script> <script src="{% static 'js/jquery.bootstrap.modal.forms.min.js' %}"></script> <script type="text/javascript"> $(document).ready(function() { $("#UploadFile").modalForm({ formURL: "{% url 'action:ModalFileUpload' %}", }); </script> modal.html ... urls.py path('modal/fileupload', file_upload.ModalFileUpload.as_view(), name='ModalFileUpload'), views.py class ModalFileUpload(MyLoginRequiredMixin,TemplateView): template_name = 'modal.html' -
How to get id from function in Django
hollo dears, I'm working on a project I have a problem with my code below, I can't get the subject_id from URL and save it in the Grade model, it gets None value.error is: Subject matching query does not exist. Grade model: class Grade(models.Model): id=models.AutoField(primary_key=True) student= models.ForeignKey('Student', null=True,on_delete=models.PROTECT) classwork= models.ForeignKey('ClassWork',on_delete=models.PROTECT) section= models.ForeignKey('Section', null=True,on_delete=models.PROTECT) subject= models.ForeignKey('Subject',null=True, on_delete=models.PROTECT) grade = models.DecimalField(null=True, decimal_places=2, max_digits=2, default=0) description = models.TextField(max_length=500, null=True) assignment1=models.DecimalField(null=True, decimal_places=2, max_digits=2, default=0) assignment2=models.DecimalField(null=True, decimal_places=2, max_digits=2, default=0) assignment3=models.DecimalField(null=True, decimal_places=2, max_digits=2, default=0) Views.py def newgrade(request, subject_id): # subject=Subject.objects.get(id=subject_id) classwork = ClassWork.objects.filter(teacher_id=request.user.id) student=Student.objects.filter(classwork__subject__id=subject_id) context = { "classwork": classwork, "student":student, "subject":subject, } return render(request, 'myapp/teacher_template/newgrade.html', context) def newgrade_save(request): if request.method != "POST": messages.error(request, "Invalid Method") return redirect('newgrade') else: subject_id = request.POST.get('subject') assignment1 = request.POST.get('assignment1') assignment2 = request.POST.get('assignment2') assignment3 = request.POST.get('assignment3') final = request.POST.get('final') sutudent_id= request.POST['student_select'] #the error is here, i want to get subject_id value from URL, and save it Grade model subject_obj = Subject.objects.get(id=subject_id) # try: # Check if Students Result Already Exists or not check_exist = Grade.objects.filter(subject_id=subject_obj, student_id=student_obj).exists() if check_exist: grades = Grade.objects.get(subject_id=subject_obj, student_id=student_obj) grades.assignment1 = assignment1 grades.assignment2 = assignment2 grades.assignment3 = assignment3 grades.final = final grades.grade= assignment1 + assignment2 + assignment3 + final grades.save() messages.success(request, "Result Updated Successfully!") return redirect('newgrade') else: result = … -
How to solve ERR_TOO_MANY_REDIRECT when deploying django rest framework web app to Azure?
I deployed an web app which django restframework base on Heroku and Azure. Same app on Heroku works fine. But when I access to Azure, it causes ERR_TOO_MANY_REDIRECT error. I googled and found that turn SECURE_SSL_REDIRECT off solved ERR_TOO_MANY_REDIRECT error. However, it causes 403 CSRF error instead. I need to find another way to fix ERR_TOO_MANY_REDIRECT or find a way to fix 403 CSRF error. Can anyone help me to solve this issue? -
Django & Ajax: How to take multiple option value in select input and save to database
I have a form where I can select multiple tags to a a single project. I am using ManyToMany Field for the tag attribute. I am using AJAX for my POST request with form data. My problem is the form won't save with multiple selected options. Any solutions? --views.py def create_project_view(request): form = ProjectForm() if request.is_ajax and request.method == 'POST': form = ProjectForm(request.POST, request.FILES) proj_title = request.POST.get('title', False) if form.is_valid(): instance = form.save(commit=False) instance.owner = request.user form.save() return JsonResponse({'title': proj_title}, status=200) context = { 'form': form } return render(request, 'projects/project-form.html', context) --project-form.html with AJAX <main class="formPage my-xl"> <div class="content-box"> <div class="formWrapper"> {% if project %} <a class="backButton" href="{% url 'project' project.id %}"><i class="im im-angle-left"></i></a> {% else %} <a class="backButton" href="{% url 'projects' %}"><i class="im im-angle-left"></i></a> {% endif %} <br> <form class="form" method="POST" id="form" action="" enctype="multipart/form-data">{% csrf_token %} {% for field in form %} <!-- Input:Text --> <div class="form__field"> <label for="formInput#text">{{field.label}}</label> {{field}} </div> {% endfor %} <input class="btn btn--sub btn--lg my-md" type="submit" value="Submit" /> </form> </div> </div> </main> <script> $(document).ready(function(){ $('#form').on('submit', function(e){ e.preventDefault() var formData = new FormData(); formData.append('title', $('#id_title').val()) formData.append('description', $('#id_description').val()) formData.append('featured_image', $('#id_featured_image')[0].files[0]) formData.append('demo_link', $('#id_demo_link').val()) formData.append('source_link', $('#id_source_link').val()) formData.append('tags', $('#id_tags').val()) formData.append('csrfmiddlewaretoken', $('input[name=csrfmiddlewaretoken]').val()); console.log(formData) $.ajax({ url: '{% url "create-project" %}', type: 'POST', …