Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to exclude a serialiser field from being used in an UpdateView in Django REST Framework
Hi everyone I have an issue, I have created a sign up using a Custom user model which inherits from AbstractBaseUser, when the user signs up all fields required are there to be full filled but when the user visits /my-account endpoint I want a field to not be there in the RetrieveUpdateDestroy View so that user cannot change that data any thoughts about this? -
How to tell browser that the form was wrong and do not save password
I have a website with a login form. My problem is that every time this form is submitted, chrome suggests to save the password, even if it's incorrect The form: <form method="POST" action="" id='sign-in'> {% csrf_token %} <div class="form-group inner-addon"> <input name="txt_login_username" type="text" class="form-control" placeholder="Username"> <i class="fa fa-user fa-lg fa-fw" aria-hidden="true"></i> </div> <div class="form-group inner-addon"> <input name="txt_login_pass" type="password" class="form-control" placeholder="Password"> <i class="fa fa-key fa-lg fa-fw" aria-hidden="true"></i> </div> {% for message in messages %} <p class='alert alert-danger'>{{ message }}</p> {% endfor %} <button type="submit" class="btn btn-primary" name="btn_login">Log In</button> </form> -
How to add the logged in user's username with django
I am building a basic blog site with Django. Here's my views.py (AddPostView should be the relevant class) : class HomeView(ListView): model = Post template_name = 'community.html' ordering = ['-id'] class ArticleDetailView(DetailView): model = Post template_name = 'articles_details.html' class AddPostView(CreateView): model = Post form_class = PostForm template_name = 'add_post.html' #fields = '__all__' And here's my forms.py: class PostForm(forms.ModelForm): class Meta: model = Post fields = ['title','author', 'body', 'image'] widgets = { 'title': forms.TextInput(attrs={'class': 'form-control'}), 'author': forms.TextInput(attrs={'class': 'form-control'}), 'body': forms.Textarea(attrs={'class': 'form-control'}), } And models.py: class Post(models.Model): title = models.CharField(max_length=255) author = models.CharField(max_length=255, null=True) #author = models.ForeignKey(User, null=True, blank=True, on_delete=models.CASCADE) body = models.TextField() date = models.DateTimeField(auto_now_add=True) image = models.ImageField(null=True, blank=True, upload_to='images/qpics') def __str__(self): return self.title + ' - ' + self.author def get_absolute_url(self): return reverse('community') I do get that I have to remove the author from forms.py and change it accordingly into models.py and write a code in views.py but i can't find a working solution to my problem. Most of the answers online are for class based views and do not work for me. Little help will be appreciated. THANKS! -
time data '03/16/2021 5:06 PM' does not match format '%d/%m/%Y %I:%M %p'
I have a variable in my Django project named this_rmg_date. Now I am trying to reformat it (for saving it in my database's DateTimeField) print(this_rmg_date) this_rmg_date = datetime.strptime(this_rmg_date, "%d/%m/%Y %I:%M %p") Here the print(this_rmg_date) print the value in console, and it is: 03/16/2021 5:06 PM but an error occers with the next line, it says: ValueError at /input_industryinfo/ time data '03/16/2021 5:06 PM' does not match format '%d/%m/%Y %I:%M %p' Yesterday, I did almost the same kind of code and that was working perfectly, other parts of my code are like this: stackOverflow-link. How can I fix this problem? -
Validate file existence
Django 3.1.5 class PhpFile(models.Model): subdir = models.CharField(max_length=255, null=False, blank=False, unique=True, verbose_name="Subdir") file = models.FileField(upload_to=php_upload_to, verbose_name="PHP file",) class ReadonlyFiledsForExistingObjectsMixin(): """ Disable a field "subdir" when modifying an object, but make it required when adding new object. """ def get_readonly_fields(self, request, obj=None): if obj: # editing an existing object return self.readonly_fields + ('subdir',) return self.readonly_fields @admin.register(PhpFile) class PhpFileAdmin(ReadonlyFiledsForExistingObjectsMixin, admin.ModelAdmin): form = PhpFileForm exclude = [] class PhpFileForm(ModelForm): def clean_file(self, *args, **kwargs): if "file" in self.changed_data: uploading_file = self.cleaned_data['file'].name subdir = self.cleaned_data['subdir'] upload_to = get_upload_to(subdir, uploading_file, FILE_TYPES.PHP) file = os.path.join(MEDIA_ROOT, upload_to) if os.path.isfile(file): raise ValidationError( "File already exists. Change its version or don't upload it.") return self.cleaned_data['file'] # File doesn't exist. I want files to be concentrated in subdirs. So, a model contains a subdir field. And I want to check if a file has already been uploaded. If it has been, I raise validation error. This code works only if I don't use ReadonlyFiledsForExistingObjectsMixin. If I uncomment it, subdir is not visible in the cleaned_data. Could you help me organize both: Readonly subdir field for existing objects. Validation for existence of a file with such a name. -
Django cut and put only the face in the picture field using opencv
This is the first question Django cut and put only the face in the picture field using opencv2 I have some problems First. It works even when I update it, so the picture gets weird. Second. The image size is weird because 'ProcessedImageField' works first and 'FaceCropped' works later. here we go my codes class Student(models.Model): picture = ProcessedImageField( verbose_name = 'pictures', upload_to = 'students/%Y/', processors=[ResizeToFill(300,300)], options={'quality':80}, format='JPEG', null=True, blank=True, default='students/no-img.jpg', ) def save(self, *args, **kwargs): super().save(*args, **kwargs) FaceCropped(self.picture.path) def FaceCropped(full_path): base_dir = os.path.dirname(os.path.abspath(__file__)) file_list = os.listdir('student') for i in file_list: if i == 'haarcascade_frontalface_default.xml': face_cascade_path = os.path.join(base_dir, i) face_cascade = cv2.CascadeClassifier(face_cascade_path) full_path = full_path path,file = os.path.split(full_path) ff = np.fromfile(full_path, np.uint8) img = cv2.imdecode(ff, cv2.IMREAD_UNCHANGED) gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) faces = face_cascade.detectMultiScale(gray, 1.3,5) for (x,y,w,h) in faces: cropped = img[y - int(h/4):y + h + int(h/4), x - int(w/4):x + w + int(w/4)] result, encoded_img = cv2.imencode(full_path, cropped) if result: with open(full_path, mode='w+b') as f: encoded_img.tofile(f) break; What i want to is When 'FaceCropped' works, only when i create a new model. So that it doesn't work when i update the model. plz help me up -
Sort a queryset by related model field and some operations
I have 3 models as follows: class Topic(models.Model): title = models.CharField(max_length=128) created = models.DateTimeField(auto_now_add=True) class Thread(models.Model): topic = models.ForeignKey(Topic, on_delete=models.CASCADE) description = models.TextField() created = models.DateTimeField(auto_now_add=True) class Message(models.Model): thread = models.ForeignKey(Thread, on_delete=models.CASCADE) text = models.TextField() created = models.DateTimeField(auto_now_add=True) I want to get: 1- most active topics in this week by number of new messages 2- most active topics by most recent messages Note: I have solved this challenge by getting the QuerySet and sorting it with python code. I want to know if there is a way to do the same with django ORM. -
How to solve Value Error assign error in Django?
I am creating a system with Django. I create a system for limiting. I have several company, and every company has to create their own limit criteria. I think I can use foreign key for that. What I mean is I want to take company name from user's company name. You can understand clearly from my models. But user should not see comp_name field in their page, it should only be seen from the admin page (kind of a hidden field in frontpage. I tried a model for what I want but I get an error: ValueError at /add/limit Cannot assign "'Test 1'": "DoaTable.comp_name" must be a "CompanyProfile" instance. how can I solve it? views. py def create_doa_table(request): form_class = DoaTableForm current_user = request.user userP = UserProfile.objects.get_or_create(username=current_user) companyName = userP[0].comp_name # If this is a POST request then process the Form data if request.method == 'POST': # Create a form instance and populate it with data from the request (binding): form = DoaTableForm(request.POST) # Check if the form is valid: if form.is_valid(): newDoaElement = form.save() newDoaElement.comp_name = companyName newDoaElement.save() # redirect to a new URL: return render(request, 'doa_table.html') else: form = form_class() return render(request, 'add_doa_element.html', {'form': form}) models.py class DoaTable(models.Model): … -
Set href dynamically
{% for stg in statusUrl %} <tr> <td>{{forloop.counter}}</td> <td>{{stg.title}}</td> <td> <a href="{% url {{stg.addLink}} %}" class="btn text-secondary px-0"> <i class="fas fa-plus"></i></a> </a> <a href="{% url {{stg.editLink}} invoice.id %}" class="btn text-secondary px-0"> <i class="fa fa-edit fa-lg"></i> </a> <a href="{% url {{stg.deleteLink}} invoice.id %}" class="btn text-secondary px-0"> <i class="far fa-trash-alt fa-lg text-danger float-right"></i> </a> <a href="{% url {{stg.previewLink}} invoice.id %}" class="btn text-secondary px-0"> <i class="fas fa-file-invoice"></i> </a> </td> </tr> {% endfor %} Trying to set href to dynamically passed urls from the views. How can href be adjusted to render a hyperlink to the path in urls.py. -
Setting href to dynamic view name
{% for stg in statusUrl %} <tr> <td>{{forloop.counter}}</td> <td>{{stg.title}}</td> <td> <a href="{% url {{stg.addLink}} %}" class="btn text-secondary px-0"> <i class="fas fa-plus"></i></a> </a> <a href="{% url {{stg.editLink}} invoice.id %}" class="btn text-secondary px-0"> <i class="fa fa-edit fa-lg"></i> </a> <a href="{% url {{stg.deleteLink}} invoice.id %}" class="btn text-secondary px-0"> <i class="far fa-trash-alt fa-lg text-danger float-right"></i> </a> <a href="{% url {{stg.previewLink}} invoice.id %}" class="btn text-secondary px-0"> <i class="fas fa-file-invoice"></i> </a> </td> </tr> {% endfor %} Trying to pass urls.py view names dynamically to template and then creating hyperlink to each view. How can href be adjusted to handle it. -
The record cannot be inserted into the database after adding a record on the admin panel in django
models.py from django.db import models class NewsUnit(models.Model): catego = models.CharField(max_length=10,null=False) nickname = models.CharField(max_length=20,null=False) title = models.CharField(max_length=50,null=False) message = models.TextField(null=False) pubtime = models.DateTimeField(auto_now=True) enabled = models.BooleanField(default=False) press = models.IntegerField(default=0) def __str__(self): return self.title views.py from django.shortcuts import render from newsapp import models import math # Create your views here. page1 = 1 def index(request,pageindex=None): global page1 pagesize = 8 newsall = models.NewsUnit.objects.all().order_by('-id') datasize = len(newsall) totpage = math.ceil(datasize/pagesize) if pageindex == None: page1 = 1 newsunits = models.NewsUnit.objects.filter(enabled=True).order_by('-id')[:pagesize] elif pageindex == '1': start = (page1-2)*pagesize if start >= 0: newsunits = models.NewsUnit.objects.filter(enabled=True).order_by('-id')[start:(start+pagesize)] page1 -= 1 elif pageindex == '2': start = page1*pagesize if start < datasize: newsunits = models.NewsUnit.objects.filter(enabled=True).order_by('-id')[start:(start+pagesize)] page1 += 1 elif pageindex == '3': start = (page1-1)*pagesize if start < datasize: newsunits = models.NewsUnit.objects.filter(enabled=True).order_by('-id')[start:(start+pagesize)] currentpage = page1 return render(request,'index.html',locals()) def detail(request, detailid=None): unit = models.NewsUnit.objects.get(id=detailid) category = unit.catego title = unit.title pubtime = unit.pubtime nickname = unit.nickname message = unit.message unit.press += 1 unit.save() return render(request, "detail.html", locals()) urls.py from django.contrib import admin from django.urls import path from newsapp import views urlpatterns = [ path('',views.index), path('index/<pageindex>/',views.index), path('detail/<detailid>/',views.detail), path('admin/', admin.site.urls), ] For this django project, I would like to insert the new record on the database list after adding a … -
invalid literal for int() with base 10: 'undefined'
I have model Employee and same table in my local database. I need to have the possibility to edit any record and save it locally. When I tried to edit record with actual id I got this error: invalid literal for int() with base 10: 'undefined'. I made a research but can't really find something helpful in my case. my edit function in views.py: def staff_edit(request, id=0): #employees = Employee.objects.all() #print(employees) if request.method == 'GET': if id == 0: form = EmployeeEditForm() else: employees = Employee.objects.get(pk=id) form = EmployeeEditForm(instance=employees) return render(request, 'staffedit.html', {'form': form}) else: if id == 0: form = EmployeeEditForm(request.POST) else: employees = Employee.objects.get(pk=id) form = EmployeeEditForm(request.POST, instance=employees) if form.is_valid(): form.save() return redirect('feedback:index_employees') context = {'form': form} #when the form is invalid return render(request, 'staffedit.html', context) this is my model.py for Employee: class Employee(models.Model): coreapiemployee_id = models.CharField(max_length=100) webflow_id_employee = models.CharField(max_length=100, default=True) first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100, default=True) email = models.EmailField(max_length=100) user_type = models.CharField(max_length=100) status = models.CharField(max_length=100, default=True) roles = models.ManyToManyField('Role', through='EmployeeRole') def __str__(self): return self.coreapiemployee_id + " " + self.email + self.first_name + self.last_name this is my general html staff.html: $(document).ready(function() { var data; fetch("http://192.168.2.85:8000/displayEmployeesToFroentend/") .then(response => response.json()) .then(json => data = json) .then(() => {console.log(data); let … -
ValueError: Related model 'auth.Group' cannot be resolved when running django test
I am new to Django REST Api testing and I am running an error like this raise ValueError('Related model %r cannot be resolved' % self.remote_field.model) ValueError: Related model 'auth.Group' cannot be resolved when running an error, and im not sure this happen -
Multiple instance jquery function with bootstrap modal
I am trying to run jquery function once modal is shown, but I close modal by clicking on the side or one close button and then open I find multiple instances of the inner function running. <script type="text/javascript"> $(document).ready(function () { $(".test").click(function () { var cid = $(this).attr('cid'); $("#post-form").one('submit',function (event){ event.preventDefault(); $.ajax({ url: '{% url 'create_request' %}', type: 'POST', data: { 'cid': cid, 'req_num' : $('#request_number').val(), }, success: function (data) { console.log("success") if (data['request']=='0') { alert("Request is already there"); } else if(data['request']=='1') { alert("Not enough components:("); } $("#exampleModal").modal('hide'); } }) }) }) }) </script> -
How to fix OS error at '/' Invalid Argument?
I have a django application that converts excel to csv files. This works fine but for larger files,it shows OSError at /conversion/ [Errno 22] Invalid argument: '<django.core.files.temp.TemporaryFile object at 0x000001C4C2C21A60>' I have successfully tested with converting smaller files but when I upload large files and try to process it, it shows the above error. views.py def conversion(request): excel_form = '' if request.method == 'POST': excel_form = ConversionForm(request.POST,request.FILES) if excel_form.is_valid(): excel_file = request.FILES['excel_file'].file df = pd.read_excel(excel_file) filename1 = excel_form.cleaned_data.get('excel_file').name filename1 = filename1.replace('.xlsx','') filename1 = filename1.replace('.xls','') df.to_csv(filename1 +'.csv',encoding='ascii',index=None, header=True) context = {'excel_form': excel_form, } return render(request,'colorlib-regform-6/convert_result.html',context) else: excel_form = ConversionForm() rontext = {'excel_form' : excel_form} return render(request,'colorlib-regform-6/convert_result.html',rontext) else: return render(request,'colorlib-regform-6/convert_result.html') -
Django Utils six for Django 3.1.5
I have a token generator that uses six from django.contrib.auth.tokens import PasswordResetTokenGenerator from django.utils import six class AccountActivationTokenGenerator(PasswordResetTokenGenerator): def _make_hash_value(self, user, timestamp): return ( six.text_type(user.pk) + six.text_type(timestamp) + six.text_type(user.is_active) ) account_activation_token = AccountActivationTokenGenerator() This runs on Django 2.2 but my boss told me to run this on latest 3.1.5. However, six was already depreciated. I also checked this SO suggestion https://stackoverflow.com/a/65620383/13933721 Saying to do pip install django-six then change from django.utils import six to import six I did the installation and changes to the code but it gives error message: ModuleNotFoundError: No module named 'six' I think I did something wrong or something is missing but I don't know how to proceed. Here is my pip freeze for reference asgiref==3.3.1 Django==3.1.5 django-six==1.0.4 djangorestframework==3.12.2 Pillow==8.1.0 pytz==2020.5 sqlparse==0.4.1 -
DjangoAdmin: How to get the Add/Edit/Del buttons for an `AutocompleteSelect` form field
I'm using the AutocompleteSelect widget for a ForeignKey field. To do this, you override the ModelForm class like so: class XForm(forms.ModelForm): ... x = forms.ModelChoiceField( queryset=X.objects.all(), widget=AutocompleteSelect(x.field.remote_field, admin.site) ) However, by using this widget I lose the + ✎ ✕ buttons that are available on the Django Admin interface for a Foreign Key field by default. What will be a good way to use AutoCompleteSelect widget but also keeping these Add/Edit/Delete buttons besides the foreign key field on the Admin UI? -
Insert duplicate column value in Django
Is there any way how can I duplicate value to another column,the value should be the same whenever I upload data to column 1 for example. I have 3000 in column 1, the value of column 2 should automatically write 3000, it is possible to trick in models? or When Inserting query instead using default? Thanks in advance!. Current output Column 1 Column 2 5000 5000 3650 5000 2000 5000 Expected output Column 1 Column 2 5000 5000 3650 3650 2000 2000 models.py class Person(models.Model): amount = models.CharField(max_length=50,blank=True, null=True) amount_paid = models.CharField(max_length=60,default='5000', null=True) -
Django edit user profile with Class Based Views
I am trying to develop a profile edit page in Django 3.1. I am new to this so if something is funky just say so. I copied some of this from Django edit user profile Views.py from myapp.forms import UserForm, UserProfileInfoForm from django.views.generic import (View, TemplateView, UpdateView) from myapp.models import UserProfileInfo class UpdateProfile(UpdateView): model = UserProfileInfoForm fields = ['first_name', 'last_name', 'email', 'phone', 'title', 'password'] template_name = 'profile.html' slug_field = 'username' slug_url_kwarg = 'slug' models.py class UserProfileInfo(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) phone = PhoneField(blank=True, help_text='Contact phone number') title = models.CharField(max_length=255) system_no = models.CharField(max_length=9) def __str__(self): return self.user.username forms.py #... from myapp.models import UserProfileInfo class UserForm(forms.ModelForm): password = forms.CharField(widget=forms.PasswordInput()) class Meta(): model = User fields = ('username', 'email', 'password', 'first_name', 'last_name') class UserProfileInfoForm(forms.ModelForm): class Meta(): model = UserProfileInfo fields = ('phone', 'title', 'system_no') myapp/urls.py from django.urls import path from . import views app_name = 'myapp' urlpatterns = [ path('', views.index,name='index'), path('about/',views.AboutView.as_view(),name='about'), path('register/', views.register,name='register'), path('profile/', views.UpdateProfile.as_view(), name='profile'), ] I have a link that only show after login in: base.html (href only) <a class="nav-link active" href="{% url 'myapp:profile' %}">Profile</a> Can you tell me what to fix? After clicking on the above link I get an error message in the browser AttributeError at /profile/ type … -
How can I make the Dropdown in Django?
I'm a beginner for Django. I'm trying to make the Dropdown to change the table for searching something. I don't know how to make it.... example) when I choose the A in dropdown, It have to search A table. when I choose the B in dropdown, It have to search B table. view.py class SearchFormView(FormView, LoginRequiredMixin): form_class = SearchForm template_name = 'purchase_order/order.html' print(form_class) def form_valid(self, form): searchWord = form.cleaned_data['search_word'] print(searchWord) cat_list = Catalog_info.objects.filter(Q(CAT_ID__icontains=searchWord)|Q(CAT__icontains=searchWord)|Q(CATEGORY__icontains=searchWord)|Q(CAT_NAME__icontains=searchWord)).distinct() context={} context['form']=form context['search_term']=searchWord context['object_list']=cat_list return render(self.request, self.template_name, context) forms.py from django import forms class SearchForm(forms.Form): search_word = forms.CharField(label='Search Word') Please advise me. -
'tuple' object has no attribute 'method'
Getting this error everytime I try to send mail. This is my .view code. Any suggestions? def contact(*request): if request.method == 'POST': contact_name = request.POST.get('contact_name') contact_email = request.POST.get('contact_email') contact_content = request.POST.get('contact_content') artist_name = request.POST.get('artist_name') artist_email = request.POST.get('artist_email') county = request.POST.get('county') service = request.POST.get('service') sessiontime = request.POST.get('sessiontime') mobilenumber = request.POST.get('mobilenumber') from_email = settings.EMAIL_HOST_USER to_email = [from_email , 'otheremail@email.com'] send_mail( contact_name, contact_content, contact_email, artist_name, artist_email, county, service, sessiontime, mobilenumber, fail_silently=False, ) return render (request, 'contact.html') else: return render (request, 'contact.html') Below is the error I get AttributeError at /contact/ 'tuple' object has no attribute 'method' Request Method: POST Request URL: http://127.0.0.1:8000/contact/ Django Version: 3.1.5 Exception Type: AttributeError Exception Value: 'tuple' object has no attribute 'method' Exception Location: E:\Programming Projects\Official Website\studioapp\blog\views.py, line 14, in contact Python Executable: E:\Programming Projects\Official Website\Black_Truman\Scripts\python.exe Python Version: 3.9.1 Python Path: ['E:\Programming Projects\Official Website\studioapp', 'C:\Users\User\AppData\Local\Programs\Python\Python39\python39.zip', 'C:\Users\User\AppData\Local\Programs\Python\Python39\DLLs', 'C:\Users\User\AppData\Local\Programs\Python\Python39\lib', 'C:\Users\User\AppData\Local\Programs\Python\Python39', 'E:\Programming Projects\Official Website\Black_Truman', 'E:\Programming Projects\Official Website\Black_Truman\lib\site-packages'] Server time: Fri, 29 Jan 2021 05:36:28 +0000 -
Active nav-item highlighting based on pk passed in url
I have 4 nav-items being generating dynamically based on the Django Model entries. My template code is as below: {% for stockbroker in stockbrokers %} <li class="nav-item"> <a class="nav-link" href="{% url 'broker:display_stocks' stockbroker.id %}" id="nav">{{ stockbroker.broker_name }} </a> </li> {% endfor %} I want to highlight the currently active nav based on the id I am passing in the url section of the a tag href. Is it possible to achieve this? -
Django cut and put only the face in the picture field using opencv2
I coded FaceCropped using cv2 and it works! I want to put img through facecropped method in ProcessedImageField model. Is there anyway? What I want is to automatically cut the face and put it in the database when uploading pictures into student model. method facecropped import numpy as np import cv2 import os import glob def FaceCropped(full_path, extra='face', show=False): face_cascade = cv2.CascadeClassifier('C:../haarcascade_frontalface_default.xml') full_path = full_path path,file = os.path.split(full_path) ff = np.fromfile(full_path, np.uint8) img = cv2.imdecode(ff, cv2.IMREAD_UNCHANGED) gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) faces = face_cascade.detectMultiScale(gray, 1.3,5) for (x,y,w,h) in faces: cropped = img[y - int(h/4):y + h + int(h/4), x - int(w/4):x + w + int(w/4)] result, encoded_img = cv2.imencode(full_path, cropped) if result: with open(path + '/' + extra + file, mode='w+b') as f: encoded_img.tofile(f) if show: cv2.imshow('Image view', cropped) cv2.waitKey(0) cv2.destroyAllWindows() my model.py class Student(models.Model): picture = ProcessedImageField( verbose_name = 'picture', upload_to = 'students/%Y/', processors=[ResizeToFill(300,300)], options={'quality':80}, format='JPEG', null=True, blank=True, default='students/no-img.jpg', ) name = models.CharField(max_length=255) my views.py class StudentAdd(FormView): model = Student template_name = 'student/list_add.html' context_object_name = 'student' form_class = AddStudent def post(self, request): form = self.form_class(request.POST, request.FILES) if form.is_valid(): student = form.save(commit=False) student.created_by = request.user student.save() messages.info(request, student.name + ' addddd', extra_tags='info') if "save_add" in self.request.POST: return HttpResponseRedirect(request.META.get('HTTP_REFERER')) return redirect('student_detail', pk=student.pk, … -
Error "Object of type QuerySet is not JSON serializable" when using request.session in django
I have a trouble when using request.session in search function django It shows error "Object of type QuerySet is not JSON serializable". def list_contract_test(request): context = {} if request.method == 'GET': query1= request.GET.get('search1') query2= request.GET.get('search2') submitbutton= request.GET.get('submit') if query1 or query2 is not None: lookups_contract= Q(contract__icontains=query1) lookups_name = (Q(name__icontains=query2.upper())|Q(name__icontains=query2.lower())) contract_posts= Contracts.objects.filter(lookups_contract,lookups_name).distinct() context['contract_posts'] = contract_posts #request.session['contract_posts'] = contract_posts return render(request, "customer2.html", context) else: contract_posts= Contracts.objects.all() context['contract_posts'] = contract_posts request.session['contract_posts'] = contract_posts return render(request, 'customer2.html', context) else: return render(request, 'customer2.html') Please help me! -
What are these warning? How to fix this?
This shows me warnings when I try to install PIPENV. Click in this link for the screenshot ⬇ warnings pip3 install pipenv Collecting pipenv Downloading pipenv-2020.11.15-py2.py3-none-any.whl (3.9 MB) |████████████████████████████████| 3.9 MB 655 kB/s Requirement already satisfied: pip>=18.0 in /usr/lib/python3/dist-packages (from pipenv) (20.0.2) Requirement already satisfied: setuptools>=36.2.1 in /usr/lib/python3/dist-packages (from pipenv) (45.2.0) Requirement already satisfied: virtualenv in /usr/local/lib/python3.8/dist-packages (from pipenv) (20.4.0) Collecting virtualenv-clone>=0.2.5 Downloading virtualenv_clone-0.5.4-py2.py3-none-any.whl (6.6 kB) Requirement already satisfied: certifi in /usr/lib/python3/dist-packages (from pipenv) (2019.11.28) Requirement already satisfied: filelock<4,>=3.0.0 in /usr/local/lib/python3.8/dist-packages (from virtualenv->pipenv) (3.0.12) Requirement already satisfied: distlib<1,>=0.3.1 in /usr/local/lib/python3.8/dist-packages (from virtualenv->pipenv) (0.3.1) Requirement already satisfied: appdirs<2,>=1.4.3 in /usr/local/lib/python3.8/dist-packages (from virtualenv->pipenv) (1.4.4) Requirement already satisfied: six<2,>=1.9.0 in /usr/lib/python3/dist-packages (from virtualenv->pipenv) (1.14.0) Installing collected packages: virtualenv-clone, pipenv WARNING: The script virtualenv-clone is installed in '/home/papan/.local/bin' which is not on PATH. Consider adding this directory to PATH or, if you prefer to suppress this warning, use --no-warn-script-location. WARNING: The scripts pipenv and pipenv-resolver are installed in '/home/papan/.local/bin' which is not on PATH. Consider adding this directory to PATH or, if you prefer to suppress this warning, use --no-warn-script-location. Successfully installed pipenv-2020.11.15 virtualenv-clone-0.5.4