Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Get Foreign Key objects in the query
I have two models. The first one represents different Projects with a name, an ID and a description The second one is for tracking wich user is in wich Project. So my models look like this: from django.contrib.auth.models import User # Create your models here. class Project(models.Model): id = models.AutoField(db_column = 'db_ID', primary_key = True) name = models.CharField(max_length=500, default = None) descriptor = models.CharField(max_length = 1000, null = True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class Meta: db_table = 'projects' def __str__(self): return self.name class Userproject(models.Model): id = models.AutoField(db_column = 'db_ID', primary_key = True) user = models.ForeignKey(User, on_delete= models.SET_NULL, null = True) project = models.ForeignKey('Project', on_delete = models.SET_NULL, null = True) created_at = models.DateTimeField(auto_now_add=True, null=True) updated_at = models.DateTimeField(auto_now=True, null = True) class Meta: db_table = 'UserProjects' def __str__(self): return self.id In the Userproject there there is only the UserID and the ProjectID, both are ForeignKeys to the other models. When I get a GET-Request with a username, I can get the userID , then I can filter all the Userprojects by the userID and serialize all those where the given ser is present. But How would I include the Project data as well If I want to send the name … -
Import-export module works not with User model for me in Django
I am trying to import new users to original User model form the Django admin site. I used to add the users one-by-one manually to the model but now I need to import lots of users and I need a solution to bulk import. I tried the code below, but I have an error: django.contrib.admin.sites.NotRegistered: The model User is not registered Please help me to solve this. admin.py from django.contrib import admin from django.contrib.auth.models import User from import_export.admin import ImportExportModelAdmin from import_export import resources class UserResource(resources.ModelResource): class Meta: model = User fields = ('id','username','first_name', 'last_name', 'email' 'password1', 'password2') class UserAdmin(ImportExportModelAdmin): list_display = ('id','username','first_name', 'last_name', 'email') resource_class = UserResource pass admin.site.unregister(User) admin.site.register(User, UserAdmin) -
django-ajax-selects autocomplete function doesn't work with inlineformset_factory
Is it possible to use the autocomplete function from django-ajax-selects (https://github.com/crucialfelix/django-ajax-selects) using inlineformset_factory? In my case the autocomplete doesn't work, when I write a letter it doesn't search anything... This is my forms.py: class FormulariMostra(ModelForm): class Meta: model = Sample fields = ("name", "sample_id_sex",) class FormulariPoolIndexList(ModelForm): class Meta: model = SamplePoolIndexCand fields = ("pool_id", "index_id", "gene_cand_list_id",) pool_id = AutoCompleteSelectField('pool_tag') index_id = AutoCompleteSelectField('index_tag') gene_cand_list_id = AutoCompleteSelectField('list_tag') PoolIndexListFormset = inlineformset_factory(Sample, SamplePoolIndexCand, form=FormulariPoolIndexList, extra=2,) My models.py: class Index(models.Model): id_index = models.AutoField(primary_key=True) index_name = models.CharField(max_length=30) index_id_index_type = models.ForeignKey(IndexType, on_delete=models.CASCADE, db_column='id_index_type', verbose_name="Tipus d'índex") index_id_index_provider = models.ForeignKey(IndexProvider, on_delete=models.CASCADE, db_column='id_index_provider', verbose_name="Proveïdor d'índex") miseq = models.CharField(max_length=9) nextseq = models.CharField(max_length=9) class Meta: db_table = 'index' unique_together = (("index_name", "index_id_index_type", "index_id_index_provider", "miseq", "nextseq"),) def __str__(self): return self.index_name class GeneCandList(models.Model): id_gene_cand_list = models.AutoField(primary_key=True) name = models.CharField(unique=True, max_length=150, verbose_name="Llista de gens candidats") class Meta: db_table = 'gene_cand_list' def __str__(self): return self.name class Pool(models.Model): id_pool = models.AutoField(primary_key=True) name = models.CharField(unique=True, max_length=50, verbose_name="Pool") hibridation = models.BooleanField(verbose_name="Hibridació OK?") samples = models.ManyToManyField('Sample', through='SamplePoolIndexCand', blank=True, verbose_name="Mostres" class Meta: ordering = ['-id_pool'] db_table = 'pool' def __str__(self): return self.name class Sample(models.Model): id_sample = models.AutoField(primary_key=True) name = models.CharField(unique=True, max_length=20) sample_id_sex = models.ForeignKey(Sex, on_delete=models.CASCADE, db_column='id_sex', verbose_name='Sexe') indexes = models.ManyToManyField(Index, through='SamplePoolIndexCand', through_fields=('sample_id', 'index_id'), blank=True, verbose_name="Índexs") pools = models.ManyToManyField(Pool, through='SamplePoolIndexCand', through_fields=('sample_id', 'pool_id'), … -
How to check if django admin is logged in or not?
I have a django project where I have 2 different login page. 1 is in the landing page. ex: https://website.com/ 2 is the django admin login. ex: https://website.com/admin/ For both the login, I am using the same postgres table. The requirement is, When I login from login page, if the user has access to admin, he should be able to login both landing page and admin page and vice versa. When I logout from any of the 2 logins, it should be able to logout from both the logins if the logged in user is same for both the logins. My login and logout code from the landing page @api_view(['POST']) def login(request): """ API for user login -> store username password using posted request.data -> check the username exists in database -> if username exists, authenticate the username,password and return response -> if username does not exists, return response """ if request.method == 'POST' and request.data: data = request.data username = data['username'] password = data['password'] user = auth.authenticate(username=username, password=password) if (user is not None) and (user.is_active): auth.login(request, user) token, created = Token.objects.get_or_create(user=user) return Response({"username": str(user), "token": token.key, "status": STATUS['SUCCESS'], "message": MESSAGE_SUCCESS['LOGIN']}, status=status.HTTP_200_OK) return Response({"status": STATUS['ERROR'], "message": MESSAGE_ERROR['LOGIN']}, status=status.HTTP_200_OK) @api_view(['POST']) @authentication_classes((TokenAuthentication,)) … -
What's the best or the most secure Authentication type in django authentication
I would like to know what the best and the most secure authentication is for django, for like a big social media app. Thanks in advance. -
Why the elif part in my if-else statement does not give me desired output even if the condition is True in Django?
I'm using a signal which was working perfectly fine earlier, when it had only one if part: @receiver(post_save, sender=Realization) def new_receivable_save(sender, instance, created, **kwargs): print('Sender: ', sender) print('Instance: ', instance) print('Instance expansion: ', instance.patient) print('Created?: ', created) print('---------------------------') pkg=Package.objects.filter(patient=instance.patient).order_by('-id').first() print('patient type: ', pkg.patient_type) print() rec=Receivables.objects.filter(patient=instance.patient).order_by('-id').first() print('expected value: ', rec.expected_value) print() print('deficit?', instance.deficit_or_surplus_amount<0) print() if created: if pkg.patient_type!='CASH' and instance.cash==False: if instance.deficit_or_surplus_amount<0: Receivables(patient=rec.patient, rt_number=rec.rt_number, discount=rec.discount, approved_package=rec.approved_package, proposed_fractions=rec.proposed_fractions, done_fractions=rec.done_fractions, base_value=rec.base_value, expected_value=instance.deficit_or_surplus_amount).save() print('The End') But I had another scenario and had to apply an elif and an else part too but that wouldn't work somehow. It looks like this now: @receiver(post_save, sender=Realization) def new_receivable_save(sender, instance, created, **kwargs): print('Sender: ', sender) print('Instance: ', instance) print('Instance expansion: ', instance.patient) print('Created?: ', created) print('---------------------------') pkg=Package.objects.filter(patient=instance.patient).order_by('-id').first() print('patient type: ', pkg.patient_type) print() rec=Receivables.objects.filter(patient=instance.patient).order_by('-id').first() print('expected value: ', rec.expected_value) print() print('deficit?', instance.deficit_or_surplus_amount<0) print() if created: if pkg.patient_type!='CASH' and instance.cash==False: if instance.deficit_or_surplus_amount<0: Receivables(patient=rec.patient, rt_number=rec.rt_number, discount=rec.discount, approved_package=rec.approved_package, proposed_fractions=rec.proposed_fractions, done_fractions=rec.done_fractions, base_value=rec.base_value, expected_value=instance.deficit_or_surplus_amount).save() print('The End') elif pkg.patient_type == 'CASH': print('patient type: ', pkg.patient_type) print() if instance.deficit_or_surplus_amount<0: print('deficit?', instance.deficit_or_surplus_amount<0) Receivables(patient=rec.patient, rt_number=rec.rt_number, discount=rec.discount, approved_package=rec.approved_package, proposed_fractions=rec.proposed_fractions, done_fractions=rec.done_fractions, base_value=rec.base_value, expected_value=instance.deficit_or_surplus_amount).save() print('The End') else: pass The if part says that if the patient is using some Government scheme instead of cash payment run the code below. The elif part … -
How to get user first login time and last logout time ,everyday?
all user login & logout number of time, everytime the datetime is storing into the db but i need everyday first logintime and last logout time of every user? models.py class AllLogout(models.Model): user = models.ForeignKey(Account,on_delete= models.CASCADE) login_time = models.DateTimeField(null=True) logout_time = models.DateTimeField(null=True) def __str__(self): return str(self.user) + ': ' + str(self.logout_time) views.py This is my view function @login_required(login_url='login') @allowed_users(allowed_roles=['Manager', 'Admin']) def welcome(request): # list of agent ids im getting data1 = Account.objects.filter(Role='Agent').values_list('id', flat=True) startdate = date.today() enddate = startdate + timedelta(days=5) some_day_last_week = timezone.now().date() - timedelta(days=7) res = [] for agentname in data1: agentdata = AllLogout.objects.filter(user_id=agentname).filter(login_time__range=[startdate,enddate]) agentdata = AllLogout.objects.filter(user_id=agentname).values('logout_time') res.append(agentdata) print(agentdata) lasttime = [] for agentname in data1: agentdatalast = AllLogout.objects.filter(user_id=agentname).filter(logout_time__range=[startdate,enddate]).last() lasttime.append(agentdatalast) zippedList = zip(res, lasttime) return render(request, 'all_adminhtmlpages/welcome.html', {'zippedList': zippedList}) -
Ram size and deep learning model disk size in production
I am trying to host a deep learning model of size 1 GB on a server with ram 512. I am using django framework. But i have confusion, when a query is sent to model, first it load into the ram. So it will give out of memory error. This is my assumption. Is it true? if it is true is there a way to resolve this issue. -
Django REST, multiple querysets in one GET
I have the following two models: models.py: from django.contrib.auth.models import User # Create your models here. class Project(models.Model): id = models.AutoField(db_column = 'db_ID', primary_key = True) name = models.CharField(max_length=500, default = None) descriptor = models.CharField(max_length = 1000, null = True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class Meta: db_table = 'projects' def __str__(self): return self.name class Userproject(models.Model): id = models.AutoField(db_column = 'db_ID', primary_key = True) user = models.ForeignKey(User, on_delete= models.SET_NULL, null = True) project = models.ForeignKey('Project', on_delete = models.SET_NULL, null = True) created_at = models.DateTimeField(auto_now_add=True, null=True) updated_at = models.DateTimeField(auto_now=True, null = True) class Meta: db_table = 'UserProjects' def __str__(self): return self.id The Userprojects 'user' and 'project' field point to the Usermodel and the Projectmodel above. Right now I have this view: class GetUserDataByNameView( APIView, ): def get(self, request, username): if User.objects.filter(username = username).exists(): uid = User.objects.get(username = username).id queryset = Userproject.objects.filter(user_id = uid) readSerializer = GetUserDataSerializer(queryset, many = True) return Response(readSerializer.data) else: return Response({"status": "error", "data":"no user with this username"}, status = 200) and this serializers from rest_framework import serializers from .models import Project from .models import Userproject class ProjectSerializer(serializers.ModelSerializer): name = serializers.CharField(max_length = 500, required = True) descriptor = serializers.CharField(max_length = 1000, default = None) class Meta: model = … -
Django DataTable with Dynamic Models
I want to read a csv or text file then create a DataTable to allow users to search and filter the loaded file. I currently have pre-defined models for sample csv files but the challenge is not knowing what file format (columns) the user will load to view and query. Is there a way to simply load a file (csv or text) in Django then interact with the data (DataTables preferred) via the browser? Thanks I currently use https://github.com/morlandi/django-ajax-datatable and it's great but requires models to be pre-defined. -
Saving the all checkbox data in the database in django
I have created multiselect dropdown check in the UI part but only checkbox selection is saving in the database. For example: If user selects US, France, Germany in country dropdown checkbox only US is getting saved in the database. I don't know where I'm going wrong. views.py: def homeview(request): userb = Userbase.objects.all() table_data= requests.get('http://127.0.0.1:1500/api/').json() if request.method == 'POST': userb = Userbase() userb.company_code = request.POST.get('company_code') userb.Area = request.POST.get('area') userb.country = request.POST.get('country') # userb.Netdue_Date = request.POST.get('datefilter') userb.From_Date = request.POST.get('from_Date') userb.To_Date = request.POST.get('to_Date') userb.Predicted_Paid_days = request.POST.get('Predicted_Paid_days') userb.PBK_Desc = request.POST.get('PBK_Desc') userb.Vendor_Name = request.POST.get('Vendor_Name') userb.Reference = request.POST.get('Reference') userb.Payment_Term = request.POST.get('Payment_Term') userb.save() return render(request, 'home.html', {'userb':userb,'table_data':table_data}) html: <div class="form-group col-sm-9" style="margin-left: 19px; font-size: 17px;"> <label for="myMultiselect">Country</label> <div id="myMultiselect" class="multiselect"> <div id="mySelectLabel" class="selectBox" onclick="toggleCheckbox()"> <select class="form-select"> <!-- <select class="selectpicker"> --> <option>Select Country</option> </select> <div class="overSelect"></div> </div> <div id="mySelectOptions" name="country"> <label for="id_country_0"><input type="checkbox" name="country" id="id_country_0" onchange="checkboxStatusChange()" value="US" /> US</label> <label for="id_country_1"><input type="checkbox" name="country" id="id_country_1" onchange="checkboxStatusChange()" value="EMEA" /> EMEA</label> <label for="id_country_2"><input type="checkbox" name="country" id="id_country_2" onchange="checkboxStatusChange()" value="ASIA" /> ASIA</label> <label for="id_country_3"><input type="checkbox" name="country" id="id_country_3" onchange="checkboxStatusChange()" value="LATAM" /> LATAM</label> <label for="id_country_4"><input type="checkbox" name="country" id="id_country_4" onchange="checkboxStatusChange()" value="UK" /> UK</label> <label for="id_country_5"><input type="checkbox" name="country" id="id_country_5" onchange="checkboxStatusChange()" value="Ireland" /> Ireland</label> </div> </div> -
Display Charts based on year select in django
I am using django=3.0.0 as my backend. I have years in my database as a datetimefield and I want to put it as an option for my select button which will change the charts dynamically in chartjs. Do I have to make a filter for this or is there any other way to put my years in chartjs. Can anyone guide me how to do this? -
Django insert OTP code to display div on website
I am reading about Django otp framework and I've implemented it in my Django admin login panel. I was following steps from this site. However, I am wondering if it is possible to implement something like this directly on website. You have content that is visible for all logged in users but in order to show div[class="supercontent"] that is on the bottom of the page user has to click this div, provide phone nunmber and insert the code that will be sent on this number. -
Passing WSGI Request with eval()
I have functions to call that come in as string so I use def sayHi(parameterA, request): print("Hi") string_function_name = "sayHi" def call_dynamic_function(A, request): eval(string_function_name+"(parameterA='{}',request='{}')".format(A, request)) call_dynamic_function(A= string_function_name, request=request) The request I am trying to pass in is Http WSGI Request. However I get an error in trying to do so. SyntaxError: invalid syntax -
How to add pagination to search result page in Django?
Here is my code but it not working. I have added this code on m search result page for articles. i don't know whether i have done a mistake {% if all_searched_article.has_previous %} <li class="page-item"> <a class="page-link" href="?page={{ all_searched_article.previous_page_number }}" tabindex="-1"><i class="fa fa-angle-left"></i></a> </li> {% else %} <li class="page-item disabled"> <a class="page-link" href="#" tabindex="-1"><i class="fa fa-angle-left"></i></a> </li> {% endif %} {% for num in all_searched_article.paginator.page_range %} {% if all_searched_article.number == num %} <li class="page-item active"><a class="page-link" href="#">{{ num }}</a></li> {% elif num > all_searched_article.number|add:"-3" and num < all_searched_article.number|add:"3" %} <li class="page-item"><a class="page-link" href="?page={{ num }}">{{ num }}</a></li> {% endif %} {% endfor %} {% if all_searched_article.has_next %} <li class="page-item"> <a class="page-link" href="?page={{ all_searched_article.next_page_number }}"><i class="fa fa-angle-right"></i></a> </li> {% else %} <li class="page-item disabled"> <a class="page-link" href="#" ><i class="fa fa-angle-right"></i></a> </li> {% endif %} </ul> </div> -
Django looses session data
This is a very strange phenomenon which i have. My site works properly most of the time. But, from time to time (in the same session), some session info is not saved. i've added at the end of my view: request.session.modified = True and in my settings, added: SESSION_SAVE_EVERY_REQUEST = True Also tried in the view: request.session.save() Still - nothing helps. From time to time, session information is not stored. i look at the Dbase and i see that it is indeed not saved. im using django session with cached_db and PickleSerializer. Any idea? -
Async Django Rest Framework Examples
Does anyone have any examples on how I can make my DRF modelviews async? Reading the Django docs there is talk of making the views call() method async but I cannot find any examples of how I would do that. Also is there any examples of unit testing my async api call? I've been using unittest to run my tests, which doesn't support testing a coroutine? -
No file was submitted. Django Rest Framework React js
I have this model in django where it have a imageField and it works when I tested it on Postman but when I try to integrate it on React the payload message is that there's no file submitted. Here is my code: models.py class File(models.Model): ... def upload_to(instance, filename): return "posts/{filename}".format(filename=filename) class UploadedFile(File): file = models.ImageField(_("Image"), upload_to=upload_to) views.py class FileUploadedCreate(APIView): permission_classes = [permissions.IsAuthenticated] parser_classes = [MultiPartParser, FormParser] def post(self, request, format=None): print(request.data) serializer = FileUploadSerializer(data=request.data) if serializer.is_valid(): serializer.save() return response.Response(serializer.data, status=status.HTTP_200_OK) else: return response.Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) serializers.py class FileUploadSerializer(serializers.ModelSerializer): class Meta: model = UploadedFile fields = "__all__" react code ... const [uploadFile, setUploadFile] = useState(null); const onChange = (e) => { if ([e.target.name] == 'image') { setUploadFile({ file: e.target.files[0] }); } console.log(e.target.files); }; useEffect(() => {}, [uploadFile]); const handleUpload = () => { if (uploadFile) { if (selectedFolder !== 0) { let formData = new FormData(); formData.append('image', uploadFile); let url = 'http://localhost:8000/classroom/resources-file/upload'; axios .post(url, formData, { headers: { 'content-type': 'multipart/form-data', }, }) .then((res) => { console.log(res.data); }) .catch((err) => console.log(err)); console.log(uploadFile.file, uploadFile.file.name, selectedFolder); } else { alert('Please select folder for your file'); } } }; .... return ( <input accept='image/*' name='image' onChange={onChange} id='upload-file-button' type='file' /> <button onClick={handleUpload}> Submit </button> Please help … -
Show multiselectfield value in Bootstrap 4 multiselect dropdown in Django template
I am following this answer for the multi-selecting dropdown. I am using django-multiselectfield to collect data in the DB model. I want to show value in bootstrap multi-selecting dropdown but getting the below result I am seeking this result These are my code snippet model.py from django.db import models from multiselectfield import MultiSelectField class Country(models.Model): name = models.CharField(max_length=40) def __str__(self): return self.name class Person(models.Model): obj=Country.objects.all() TEAM=tuple((ob,ob) for ob in obj) name = models.CharField(max_length=124) southasia=MultiSelectField(max_length=200, choices=TEAM) def __str__(self): return self.name views.py from django.http import JsonResponse from django.shortcuts import render, redirect, get_object_or_404 from .forms import PersonCreationForm from .models import Person def person_create_view(request): form = PersonCreationForm() if request.method == 'POST': form = PersonCreationForm(request.POST) if form.is_valid(): form.save() return redirect('person_add') return render(request, 'miracle/index.html', {'form': form}) forms.py from django import forms from .models import Person class PersonCreationForm(forms.ModelForm): class Meta: model = Person fields = '__all__' def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) template {% load crispy_forms_tags %} <!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" /> <script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script> <title>Dependent Dropdown in Django</title> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.13.1/css/bootstrap-select.css" /> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.bundle.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.13.1/js/bootstrap-select.min.js"></script> </head> <body> <h2>Person Form</h2> <form method="post"> {% csrf_token %} {{ … -
How to call another websocket function in django channels consumer functions?
I have following code in consumers.py def websocket_receive(self,event): print(f'[{self.channel_name}] - Recieved message - {event["text"]}') async_to_sync(self.channel_layer.group_send)( self.room_name, { 'type': 'websocket.message', 'text': event.get('text') } ) def websocket_message(self,event): print(f'[{self.channel_name}] - message Sent - {event["text"]}') self.send({ 'type':'websocket.send', 'text':event.get('text') }) I want to call the message function whenever a message is recieved so in websocket_recieve function I have addes 'type': 'websocket.message', but I don't know why websocket_message function is not being called? I am new to django channels. any help will be appreciated. -
How to configure multiple language in my django model?
Here I want to give users to select languages while creating model objects. For this I tried like this. Is this way there will be any problems ? And I think I should have to migrate MyModel each time if new language option gets added in the project setting ? What any other options would be better for this scenario ? note: I don't want to use third party packages. settings import os gettext = lambda s: s LANGUAGES = [ ("en-us", gettext("English")), ('de', gettext('German')),] models def get_project_languages(): languages = settings.LANGUAGES languages_choices = [] for lang in languages: languages_choices.append((lang[0], lang[1])) return languages_choices language_choices = get_project_languages() class MyModel(models.Model): language = models.CharField(choices=languages_choices) content = models.TextField() -
how to access template variables in ajax jquery in javascript using Django template
I have got a javascript containing ajax jquery which refreshes a template based on the data returned as shown below - =============================================================== product-filter.js is below code $(document).ready(function(){ $(".ajaxLoader").hide(); $(".filter-checkbox").on('click',function(){ var _filterObj={}; $(".filter-checkbox").each(function(index,ele){ var _filterVal=$(this).val(); var _filterKey=$(this).data('filter'); _filterObj[_filterKey]=Array.from(document.querySelectorAll('input[data-filter='+_filterKey+']:checked')).map(function(el){ return el.value; }); }); //Run Ajax $.ajax({ url:'/filter-data_b/1', data: _filterObj, dataType: 'json', beforeSend: function(){ $(".ajaxLoader").hide(); }, success:function(res){ console.log(res); $("#filteredProducts_b").html(res.data); $(".ajaxLoader").hide(); } }) }); =============================================================== I am able to get this working with /filter-data_b/1 where 1 is brand_id which is hard-coded and I want to know how to get this from the template where product-filter.js is called from the /filter-data_b/1 code in views.py and urls.py is as shown below urls.py urlpatterns = [ path('', views.home,name='home'), path('brand_product_list/<int:brand_id>', views.brand_product_list,name='brand_product_list'), path('filter-data_b/<int:brand_id>',views.filter_data_b,name='filter_data_b'), ] ================================================================= views.py is def filter_data_b(request,brand_id): colors=request.GET.getlist('color[]') categories=request.GET.getlist('category[]') brands=request.GET.getlist('brand[]') sizes=request.GET.getlist('size[]') flavors=request.GET.getlist('flavor[]') allProducts=ProductAttribute.objects.filter(brand=brand_id).order_by('-id').distinct() if len(colors)>0: allProducts=allProducts.filter(productattribute__color__id__in=colors).distinct() if len(categories)>0: allProducts=allProducts.filter(category__id__in=categories).distinct() if len(brands)>0: allProducts=allProducts.filter(brand__id__in=brands).distinct() if len(sizes)>0: allProducts=allProducts.filter(productattribute__size__id__in=sizes).distinct() if len(flavors)>0: allProducts=allProducts.filter(productattribute__flavor__id__in=flavors).distinct() t=render_to_string('ajax/product-list_b.html',{'data':allProducts}) return JsonResponse({'data':t}) =========================================================================== -
Django Bootstrap modal update form not showing data
I have created 2 modals in separate html files to handle creation and update of the applicant status. Both modals are triggered on the same page, the applicant detail, and are showing the form, and the update form is not displaying the data, even though the clickable button shows the correct link. applicant_detail.html <div class="row mb-1"> <div class="col"> <h4>Applicant Status</h4> </div> <div class="col col-auto"> <a href="#applicantStatusCreate" class="btn btn-primary text-white float-end" data-bs-toggle="modal"> Add Applicant Status </a> {% include 'recruitment/applicant_status_create.html' %} </div> </div> <!---Applicant Status Start---> {% for status in applicant_status_detail %} <div class="card mb-4"> <div class="card-body p-4"> <div class="row"> <div class="col-xl-5"> <h5>{{ status.applicant_status }}</h5> <ul class="personal-info"> <li> <div class="title">Status Date</div> <div class="text">{{ status.status_date|date:"M d, Y" }}</div> </li> <li> <div class="title">Rating</div> <div class="text">{{ status.rating }}</div> </li> </ul> </div> <div class="col-xl-7"> <a href="{% url 'recruitment:applicant_status_edit' pk=status.id %}" class="edit-icon float-end" data-bs-toggle="modal" data-bs-target="#applicantStatusUpdate"> <i class="fas fa-pencil-alt"></i> </a> {% include 'recruitment/applicant_status_edit.html' %} </div> </div> <div class="row"> <div class="col-xl-6"> <ul class="personal-info"> <li> <h6>Notes</h6> <div>{{ status.notes|safe }}</div> </li> </ul> </div> </div> </div> </div> {% endfor %} applicant_status_create.html <div class="modal fade" id="applicantStatusCreate" tabindex="-1" role="dialog"> <div class="modal-dialog modal-dialog-centered"> <form method="post" action="{% url 'recruitment:applicant_status_create' %}"> {% csrf_token %} {{ form.media }} <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title">Add Applicant Status</h5> <button type="button" … -
drf-yasg hide title property
So as shown in the image, is there any way to hide the 'title' property foreach item? I don't really see the purpose of these titles. -
Django+gunicorn+nginx upload large file connection reset error
I am trying to upload a large file (approx 4GB) to my django website. I use the regular file upload method described in the django docs. I am serving the website with Nginx -> Gunicorn -> Django on EC2 instance. Problem Uploading till 1GB files works fine. It works fine for smaller files but when I try to upload a file of 2GB or more I get a connect reset error in chrome. Logs & specs There are nothing informative in logs I can find. Versions: Django==3.2.4 Nginx==1.20 Config snippet: nginx.conf: ( in the http block) client_max_body_size 4G; client_body_buffer_size 4096M; client_body_timeout 300; Am I missing any django configuration? Hope somebody is able to shed some light on the cause and fix. Thanks for your time.