Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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', … -
django rest frame work api with images, not displaying with <img src=" "> in html
i have made an images api with django rest frame work. when it is running server on goorm ide, it is okay to display but on the oracle cloud vm it is not displaying images on my in html is there any difference between runningn server on goorm ide and oracle cloud vm? -
Algorithm for finding shortest connection between friends in social network or betweent two wiki articles
I have models in Django like from django.db import models class TypeOfObject(models.Model): type = models.CharField(max_length=150, unique=True) def __str__(self): return self.type class Object(models.Model): title = models.CharField(max_length=150) content = models.TextField(blank=True) is_published = models.BooleanField(default=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) type = models.ManyToManyField(TypeOfObject, related_name='type_of_object', blank=False) relation = models.ManyToManyField('self', related_name='relation', blank=True, null=True) def __str__(self): return self.title Object can be Person or Article or Movie etc. They refers to each other. How to check, for example, how connected film Spider Man and Michael Jackson. We can find artists who starred in films, for example, Stoney Jackson and he starred in film with actor who starred in Spider Man. Lets count it for 1. And etc, we can estimate how some object related to another. Which way it better to do? -
Access cleaned data from django admin for pdf processing
Hi there I'm fairly new to django so please be kind if anything sounds a bit newbie to you. I am currently trying to add a print button to every existing django admin view of a project so it will not depend on a single model I could resolve manually for printing but every existing model which contains foreign keys to other models an so on. For simplicity I thought it would be the best to just get the cleaned_data of the form and process it for the pdf. I alread added the print button, the path url and so on and it will create a pdf file for me. What I am not able to do is to access the forms cleaned_data from my BaseAdmins (extends the ModelAdmin) class like this: form = BaseForm(request.POST) if form.isValid(): data = form.cleaned_data It will just give me random kinds of errors, like object has no attribute 'is_bound' So I think that I am generally wrong with the context where I am trying to get the cleaned_data from the form. Every tutorial I found is just showing how to get the data but not fully resolved if it contains foreign keys and not … -
Model constraints are not working with Faker ( Django )
I am just starting to use pytest and faker for testing while trying to create text for a field in testing db the constraints are being ignored and i don't know how to fix it. models.py from django.db import models # Create your models here. class Note(models.Model): body = models.TextField(null=True, blank=True, max_length=5) updated = models.DateTimeField(auto_now=True) created = models.DateTimeField(auto_now_add=True) def __str__(self): return self.body[0:50] factories.py import factory from faker import Faker fake = Faker() from mynotes_api.models import Note class NoteFactory(factory.django.DjangoModelFactory): class Meta: model = Note body = fake.text() conftest.py import pytest from django.contrib.auth.models import User from pytest_factoryboy import register from tests.factories import NoteFactory register(NoteFactory) @pytest.fixture def new_user1(db, note_factory): note = note_factory.create() return note test_ex1.py import pytest def test_product(new_user1): note = new_user1 print(note.body) assert True test output the problem as visible in output is that the length of the text generated and being stored in the testing db is more than 5. kindly guide me in this regard. -
How to create relationships between 3 models in django?
I'm building a marketplace that have 2 user types i.e. buyers and sellers. Now I want to create a relationship model between buyers, sellers and OrderedItems, so that the sellers gets notified once the buyers orders an item. This is the model I made: class Ordered(models.Model): ordered_items = models.ManyToManyField(Cart) seller = models.ForeignKey(SellerProfile, on_delete = models.SET_NULL, null = True) buyer = models.ForeignKey(CustomerProfile, on_delete = models.CASCADE) ordered_on = models.DateTimeField(auto_now_add = True) But I don't know how to implement this in views.py Any suggestion will be really helpful Thank you -
passing values from one function to another in django
I am creating an app in which I have to transfer value from one function to other in Django, after reading some articles I have found out I can use global functions inside the Django function. I just want to ask is it good to use global function because the app I am wokring on is gonna be live and people will use it I dont want any trouble at later stages. -
Filter is not working properly in Django REST Framework
This is my TestViewSet. class TestViewSet(ListAPIView, CreateAPIView, UpdateAPIView): permission_classes = [ IsAuthenticated, ] pagination_class = CustomPagination serializer_class = TestSerializer model = Test create_class = CreateTestSerializer filter_backends = [DjangoFilterBackend] filterset_fields = ['department__name', 'code', 'billing_category__id', 'billing_category__name'] def get_queryset(self): name_str = self.request.query_params.get("name") department_id = self.request.query_params.get("department_id") pk = self.kwargs.get("id") self.pagination_class.page_size = page_size if name_str is not None: return self.model.objects.filter( Q(name__icontains=name_str) | Q(name__iexact=name_str) | Q(name__istartswith = name_str) ) elif pk is not None: return self.model.objects.filter(id=pk) elif department_id is not None: return self.model.objects.filter(department_id=department_id) else: return self.model.objects.all() name is CharField and department is ForeignKey in Test Model. When i am passing this url - http://127.0.0.1:8000/api/v1/package/test/?name=fun&department_id=7 It is ignoring deparment_id. I just don't know why. Individually both are working fine. I'm wondering why it is ignoring deparment_id ? Thank you !! -
MiddlewareMixin missing required argument: 'get_response' django
Does anyone have any ideas on why I am getting this error? My program was working before and I don't know what I changed to cause it to break. My main website works but whenever I make this get request to http://10.0.0.233:8000/watcher/form/list I get the error below. I searched my whole project and did not find MiddlewareMixin used anywhere. urls.py: from django.urls import path from . import views urlpatterns = [ path('form/list',views.get_all_form_items), ] Views.py @api_view(['GET']) def get_all_form_items(request): snippets = form_item_db.objects.all() serializer = form_item_db_serializer(snippets, many=True) return Response(serializer.data) Error: Django version 4.0, using settings 'backend.settings' Starting development server at http://10.0.0.233:8000/ Quit the server with CTRL-BREAK. [05/Jan/2022 02:11:55] "GET /watcher HTTP/1.1" 200 644 [05/Jan/2022 02:11:55] "GET /static/js/main.1924b030.js HTTP/1.1" 304 0 [05/Jan/2022 02:11:55] "GET /static/css/main.31d6cfe0.css HTTP/1.1" 304 0 Internal Server Error: /watcher/form/list Traceback (most recent call last): File "C:\Users\bestg\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\bestg\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\bestg\AppData\Local\Programs\Python\Python310\lib\site-packages\django\views\decorators\csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "C:\Users\bestg\AppData\Local\Programs\Python\Python310\lib\site-packages\django\views\generic\base.py", line 69, in view return self.dispatch(request, *args, **kwargs) File "C:\Users\bestg\AppData\Local\Programs\Python\Python310\lib\site-packages\rest_framework\views.py", line 505, in dispatch response = self.handle_exception(exc) File "C:\Users\bestg\AppData\Local\Programs\Python\Python310\lib\site-packages\rest_framework\views.py", line 465, in handle_exception self.raise_uncaught_exception(exc) File "C:\Users\bestg\AppData\Local\Programs\Python\Python310\lib\site-packages\rest_framework\views.py", line 476, in raise_uncaught_exception raise exc File "C:\Users\bestg\AppData\Local\Programs\Python\Python310\lib\site-packages\rest_framework\views.py", line 493, … -
how to show multiple image objects in django template?
models.py class ProductVariantsImages(DateTimeModel): product_variant = models.ForeignKey(ProductVariants, on_delete=models.CASCADE, related_name='product_variants_images') variant_images = models.ImageField(upload_to='uploads/') def __str__(self): return str(self.id) HTML <div class="input-group"> {{variant_images}} </div> views.py @login_required def item_approval(request, pk): if request.method == "GET": product_form = AdminProductForm(request.POST) item = ProductVariants.objects.get(item_num=pk) variant_images = ProductVariantsImages.objects.filter(product_variant=item) print(variant_images) product_form = AdminProductForm(instance=product) item_form = ProductVariantsForm(instance=item) variant_images = ProductVariantsImagesForm(instance=product_variant_images)# here I get multiple objects print(variant_images) return render(request, 'loom_admin/product_details.html', {'item_form':item_form, 'product':product, 'product_form':product_form, 'variant_images':variant_images, }) while running I get 'QuerySet' object has no attribute '_meta' when I put variant_images = ProductVariantsImagesForm(instance=product_variant_images[0]) the error disappear. But I am getting first image object. What if I want to do to get multiple images that related to the filter query in django template? -
Drf: returns 403 instead of 401 after jwt token expires?
"DEFAULT_AUTHENTICATION_CLASSES": [ "rest_framework.authentication.SessionAuthentication", "rest_framework_simplejwt.authentication.JWTAuthentication", ], "DEFAULT_PERMISSION_CLASSES": [ "rest_framework.permissions.IsAuthenticated", ], I am using session authentication for django admin and swagger and jwt for rest of the part. The issue is I am getting 403 after token expires but I think it should return 401 since the error is Given token not valid for any token type. Or 403 is the correct response ?