Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Integrate Django blog project in HTML website
I have a regular website where HTML5, CSS3, JQUERY and static images have been used. I also have a Blog written in Django and I would like to integrate it in the website. I am really new to Django so I was wondering which is the best approach to use. Should I integrate the website code as part of the Django project or there are some other solutions? thanks! -
New to Python - Django, Need To Read Log
I have been handed over an application which is built in Python - Django. I need to support it. There was no handover or anything like that. Pitty Me! I am new to this language and framework. When I try to run the server with python manage.py runserver I get following errors: Unhandled exception in thread started by .wrapper at 0x108f48e18> Traceback (most recent call last): File "/Users/atariq/Sites/Python_Stuff/123/venv/lib/python3.7/site-packages/django/utils/autoreload.py", line 228, in wrapper fn(*args, **kwargs) File "/Users/atariq/Sites/Python_Stuff/123/venv/lib/python3.7/site-packages/django/core/management/commands/runserver.py", line 116, in inner_run autoreload.raise_last_exception() File "/Users/atariq/Sites/Python_Stuff/123/venv/lib/python3.7/site-packages/django/utils/autoreload.py", line 251, in raise_last_exception six.reraise(*_exception) File "/Users/atariq/Sites/Python_Stuff/123/venv/lib/python3.7/site-packages/django/utils/six.py", line 685, in reraise raise value.with_traceback(tb) File "/Users/atariq/Sites/Python_Stuff/123/venv/lib/python3.7/site-packages/django/utils/autoreload.py", line 228, in wrapper fn(*args, **kwargs) File "/Users/atariq/Sites/Python_Stuff/123/venv/lib/python3.7/site-packages/django/init.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) File "/Users/atariq/Sites/Python_Stuff/123/venv/lib/python3.7/site-packages/django/apps/registry.py", line 85, in populate app_config = AppConfig.create(entry) File "/Users/atariq/Sites/Python_Stuff/123/venv/lib/python3.7/site-packages/django/apps/config.py", line 94, in create module = import_module(entry) File "/Users/atariq/Sites/Python_Stuff/123/venv/lib/python3.7/importlib/init.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "", line 1006, in _gcd_import File "", line 983, in _find_and_load File "", line 967, in _find_and_load_unlocked File "", line 677, in _load_unlocked File "", line 728, in exec_module File "", line 219, in _call_with_frames_removed File "/Users/atariq/Sites/Python_Stuff/123/venv/lib/python3.7/site-packages/django/contrib/admin/init.py", line 4, in from django.contrib.admin.filters import ( File "/Users/atariq/Sites/Python_Stuff/123/venv/lib/python3.7/site-packages/django/contrib/admin/filters.py", line 10, in from django.contrib.admin.options import IncorrectLookupParameters File "/Users/atariq/Sites/Python_Stuff/123/venv/lib/python3.7/site-packages/django/contrib/admin/options.py", line 12, in from django.contrib.admin … -
Django loaddata ignore existing objects
I have a fixture with list of entries. eg: [ { "fields": { "currency": 1, "price": "99.99", "product_variant": 1 }, "model": "products.productprice", "pk": 1 }, { "fields": { "currency": 2, "price": "139.99", "product_variant": 1 }, "model": "products.productprice", "pk": 2 } ] This is only initial data for each entry (The price might change). I would like to be able to add another entry to that fixture and load it with loaddata but without updating entries that already exist in the database. Is there any way to do that? Something like --ignorenonexistent but for existing entries. -
Serialize model fields related through another model
I have three models linked like so: class A: some fields class B: ForeignKey('A') class C: ForeignKey('B') Now, when I serialize C, I want to serialize model fields from A. Of course, this can be done using nested serializers like so: class ASerializer: class Meta: model = A fields = ('id', some fields) class BSerializer: a_s = ASerializer(read_only=True) class Meta: model = B fields('id', 'a_s') class CSerializer: b_s = BSerializer(read_only=True) class Meta: model = C fields('id', 'b_s') However, I want to only display the fields of related A objects when serializing C (without using BSerializer). How do I do this? -
Django Manytomanyfield in Ajax CRUD
I implemented an Ajax CRUD. My Model has one ManyToMany field. If i choose only one item for this field everything will be good, but if choose multi items it shows form invalid error. Please tell me what should I do. model.py: class BusienssCategory(models.Model): title = models.CharField(max_length=20, unique=True) slug = models.SlugField(unique=True) description = models.CharField(max_length=45) def __str__(self): return self.title class BusienssProfile(models.Model): title = models.CharField(max_length=20) shortDescription = models.CharField(max_length=40) category = select2.fields.ManyToManyField(BusienssCategory) image = models.ImageField(upload_to=upload_image_path, null=True, blank=True) def __str__(self): return self.title form.py: class BusinessForm(forms.ModelForm): class Meta: model = BusienssProfile fields = ('title', 'category', 'shortDescription') view.py: def save_business_form(request, form, template_name): data = dict() form = BusinessForm(request.POST, request.FILES) if request.method == 'POST': if form.is_valid(): form.save() data['form_is_valid'] = True businesses = BusienssProfile.objects.all() data['html_business_list'] = render_to_string('business/business_profile/partial_business_list.html', { 'businesses': businesses }) else: data['form_is_valid'] = False context = {'form': form} data['html_form'] = render_to_string(template_name, context, request=request) return JsonResponse(data) ajax.js: var saveForm = function() { var form = $(this); var data = new FormData($('form').get(0)); var categories = $("#id_category").val(); alert(categories) var featured = $('#id_featured').prop('checked'); var active = $('#id_active').prop('checked'); data.append("image", $("#id_image")[0].files[0]); data.append("title",$("#id_title").val()); data.append("category", categories); data.append("description",$("#id_Description").val()); $.ajax({ url: form.attr("action"), data: data, processData: false, contentType: false, type: form.attr("method"), dataType: 'json', success: function (data) { if (data.form_is_valid) { Command: toastr["success"]("The profile has been deleted.", "Success"); } … -
Nginx bad gateway error on some methods while other works
I am running Django on nginix but one of my functions is returning this error: upstream prematurely closed connection while reading response header from upstream While other methods are working fine. I have traied increasing server timeout in nginx.conf file but still it gives me the same error. This methods runs fine whe i run my django independently with python manage.py runserver 0.0.0.0:8000 Can someone help me to resolve it? -
I can't create custom reset pass view - django - logic error
thank you for helping But I'm trying to create reset password view, without using the default Django reset password to view. by following this tutorial: https://wsvincent.com/django-user-authentication-tutorial-password-reset/ and a second tutorial https://simpleisbetterthancomplex.com/tutorial/2016/09/19/how-to-create-password-reset-view.html my code is the same as the code for the tutorial but for better, understanding I posted a picture of the Django Project URL here:my codes structure of password reset -
Django query, return only if all children's column value is zero
is there any easy way to do a query where it only returns the parent object (trade) if all of its children's(tradeleg) quantity column has zero value? e.g. return trade_1 if trade_1 has five children and all of its children has "0" value on their quantity field. e.g. do not return trade_2 if trade_2 has two children and one of its children has value of "1" on its quantity field. I have this model: class Trade: name = models.CharField( default='', max_length=50, blank=True, null=True ) date = models.DateField( default=None, blank=True, null=True ) class TradeLeg(models.Model): trade = models.ForeignKey( Trade, on_delete=models.CASCADE ) quantity = models.IntegerField( default=0 ) my current query: trade = Trade.objects.filter(tradeleg__quantity = 0) -
django: messages.add_message not displaying in html page
I have a Django library application, wherein I have a book_detail page in which the user can download/email the book's pdf link to himself. On sending such an email(which is working perfectly, the email is being received), I want to display a pop-up or an alert message on that same html page instead of redirecting to some other page. Here is the views.py code: def send_email(request): try: send_mail('Book request', 'email body', settings.EMAIL_HOST_USER, ['xyz@gmail.com'], fail_silently=False) #this message is not getting displayed in the same html page messages.add_message(request, messages.SUCCESS, 'Email sent successfully.') except EmailMessage: messages.add_message(request, messages.SUCCESS, 'Error has occurred') HTML page book_detail.html code: ...... rest of the code.... {% if messages %} <ul class="messages"> {% for message in messages %} <li{% if message.tags %} class="{{ message.tags }}"{% endif %}>{{ message }}</li> {% endfor %} </ul> {% endif %} {% endblock %} The error occuring: Please suggest what should be done, is there any other solution I can try for displaying an alert box/message on that same html page, without redirecting it to any other page. Thanks! -
authenticate function not working for ldap authentication with ldap3
I am trying to configure my app with ldap. I am using ldap3. I am getting this error : Non-ASCII character '\xe2' in file C:\Users\dm050767\Documents\UserProfile\auth\auth_backend.py Following are the files: settings.py AUTHENTICATION_BACKENDS = [ 'auth.auth_backend.UserAuthentication', ] views.py def login_user(request): username = request.POST['username'] password = request.POST['password'] print(username,password) user = authenticate(request, username=username, password=password) print(user) if user is not None: print('User not none') login(request, user) print('Login successful') return redirect(request.POST['next'] or '/') else: print('Login failed') return redirect('/login?error=auth') def login_view(request): if request.method == "POST": return login_user(request) else: return render(request, 'Profile/login.html') auth/auth_backend.py class UserAuthentication: def authenticate(self, request, username=None, password=None, domain="domain"): # TODO add error handling when uid and or pwd is not passed # Check the username/password and return a user. If not valid, it should return None. user = domain + username server = Server('server', get_info=ALL) conn = Connection(server, user=user, password=password, authentication=NTLM) valid_user = conn.bind() if valid_user: try: user = User.objects.get(username=username) if settings.DEBUG: print("YouRockAuth.authenticate: found user %s" % user.username) except User.DoesNotExist: pass else: user = None return user def get_user(self, user_id): try: user = User.objects.get(pk=user_id) return user except User.DoesNotExist: return None -
custom email authentication backend not working in django 2.1.4
I am having trouble in integrating custom authentication backend in django 2.1.4 . Following is my code : my FMS.authBackend module : from django.contrib.auth import get_user_model from django.contrib.auth.backends import ModelBackend class authEmailBackend(ModelBackend): def authenticate(self, username=None, password=None, **kwargs): print("aaaaaaa") UserModel = get_user_model() try: user = UserModel.objects.get(email=username) except UserModel.DoesNotExist: return None else: if user.check_password(password): return user return None my settings.py : AUTHENTICATION_BACKENDS = ( 'FMS.authBackend.authEmailBackend', 'django.contrib.auth.backends.ModelBackend', ) my urls.py : from django.contrib.auth import views as auth_views urlpatterns = [ path('login', my_decos.logout_required(auth_views.LoginView.as_view(template_name = 'register/login.html')),name = 'login') ] The above code is not working in my case. Function authenticate in authEmailBackend is never called as nothing printed in console but I print statement in authenticate function. although the same code was working for django 2.0.8, the only difference then was that the urls.py was : from django.contrib.auth import views as auth_views urlpatterns = [ path('login', my_decos.logout_required(auth_views.login(template_name = 'register/login.html')),name = 'login') ] but in the newer django the django.contrib.auth.views.login doesn't support any more and we need to use django.contrib.auth.views.LoginView. I read somewhere that to use custom AUTHENTICATION_BACKEND our url must point to django.contrib.auth.views.login but which is not possible here. So can you please help me to overcome the problem. -
How to pass data to template from class based generic form view
views.py class CompanyUpdateView(UpdateView): model = Company fields = ['company_name', 'company_description','company_email', 'company_phone', 'company_address', 'company_website' , 'company_status', 'company_monthly_payment'] company_form.html {% extends "super_admin/base.html" %} {% load crispy_forms_tags %} {% block content %} <div class="content-section"> {{ object.update }} <form action="" method="POST"> {% csrf_token %} <fieldset class="from-group"> <legend class="border-bottom mb-4">Enter New Company</legend> {{ form | crispy}} </fieldset> <div class="form-group"> <button class="btn btn-outline-info" type="submit">Submit</button> </div> </form> </div> {% endblock content %} I am getting the form values in company_form.html but i want static value which will be stored in CompanyUpdateView and will be display in company_form.html template. The reason i am doing this because i am using same template for update delete and create company where when i click on edit button it will show delete button instead of save button {% extends "super_admin/base.html" %} {% block content %} <a class="btn btn-primary" href="{% url 'super-company-create' %}" role="button">Add a Company</a> <table class="table"> <thead class="thead-dark"> <tr> <th scope="col">#</th> <th scope="col">Company Name</th> <th scope="col">Company Email</th> <th scope="col">Company Website</th> <th scope="col">Company Status</th> <th scope="col">Company Monthly Payment</th> <th scope="col">Edit</th> </tr> </thead> <tbody> {% for company in companies %} <tr> <th scope="row">{{ company.id }}</th> <td>{{ company.company_name }}</td> <td>{{ company.company_email }}</td> <td>{{ company.company_website }}</td> <td>{{ company.company_status }}</td> <td>{{ company.company_monthly_payment }}</td> <td><a href="{{ company.id … -
Django Form Inheritance
I am trying to subclass a form and I need to get all args/kwargs from the main form. I know pythonic way but is there something I need to do for Django specifically. Main Form: class BasketLineForm(forms.ModelForm): save_for_later = forms.BooleanField( initial=False, required=False, label=_('Save for Later')) def __init__(self, strategy, *args, **kwargs): super(BasketLineForm, self).__init__(*args, **kwargs) self.instance.strategy = strategy max_allowed_quantity = None num_available = getattr(self.instance.purchase_info.availability, 'num_available', None) basket_max_allowed_quantity = self.instance.basket.max_allowed_quantity()[0] if all([num_available, basket_max_allowed_quantity]): max_allowed_quantity = min(num_available, basket_max_allowed_quantity) else: max_allowed_quantity = num_available or basket_max_allowed_quantity if max_allowed_quantity: self.fields['quantity'].widget.attrs['max'] = max_allowed_quantity def clean_quantity(self): qty = self.cleaned_data['quantity'] if qty > 0: self.check_max_allowed_quantity(qty) self.check_permission(qty) return qty def check_max_allowed_quantity(self, qty): qty_delta = qty - self.instance.quantity is_allowed, reason = self.instance.basket.is_quantity_allowed(qty_delta) if not is_allowed: raise forms.ValidationError(reason) def check_permission(self, qty): policy = self.instance.purchase_info.availability is_available, reason = policy.is_purchase_permitted( quantity=qty) if not is_available: raise forms.ValidationError(reason) class Meta: model = Line fields = ['quantity'] SubForm to Inherit Main Form in different app: class BatteryForm(CoreBasketLineForm): class Meta(CoreBasketLineForm.Meta): model = Batteries fields = ('title', 'price', 'comment') -
how to get value of select field in django without any forms.py
I have only this select field i want to get value of this field .I do not have any forms, i just want to get the data from this field <label>Portal Language:</label> <select name="language"> {% get_available_languages as LANGUAGES %} {% for lang in LANGUAGES %} <option> {{ lang.1 }} </option> {% end for %} </select> -
How to make model property to editable in djagno admin panel
When I tried to add property into the list_editable into the Django admin.py file, I got an error when running the server. <class 'test_project.admin.SalesAdmin'>: (admin.E100) The value of 'list_editable[2]' refers to 'amount', which is not an attribute of 'test_project.Sales'. -
Github Issue and travis returning errors - python
I'm a student participating in Google Code-In. There's a task in which I need to fix this issue on GitHub. My Travis build is failing and here's my PR. An exception need to be raised and I must check for it. I don't really want everything given to me, just some kind of help so that I can move forward. Anything would be welcome, thanks! -
what does get_expiry_age() return in Django
Instead of returning actual seconds left for expiry, request.session.get_expiry_age() returns fixed value=10 set in request.session.set_expiry(10). But when I manually set request.session['var1']=1 in homepage and then try to print this var1 in another view, I get KeyError after 10 seconds, saying 'var1' doesnt exist. So this session does expire after 10 seconds. So ideally if i wait on homapge for 5 seconds and then move to another view, request.session.get_expiry_age() should return 5 seconds instead of 10 seconds. Django doc contradict this observation. Is there any other inbuilt function that can show actual seconds left for session expiry. Thanks -
Django How to send data from view to template
model.py class Peer(models.Model): router = models.ForeignKey(Router, on_delete=models.CASCADE) ipv4_address = models.CharField(max_length=250) remote_as = models.CharField(max_length=250) I have a custom button in Django admin Change form <input type="submit" value="Test Peer" name="_peer-test"> Then in admin.py def response_change(self, request, obj): if "_peer-test" in request.POST: self.message_user(request, "Peer Tested") url = request.POST.get('obj', '/peeringmanager/export') remote_as = obj.remote_as url += "?remote_as={}".format(remote_as) return HttpResponseRedirect(url) So I sent the data (remote_as) from the obj to another view views.py def export(request): remote_as = request.GET.get('remote_as','') selected_peer = Peer.objects.filter(remote_as__exact=remote_as) template= loader.get_template('delete-peer.html') content= { 'selected_peer':selected_peer, } return HttpResponse(template.render(content,request)) Here I want to use remote_as object to get all object in the form related to that Remote_as and sent it to a html. delete-peer.html {% block content %} {% for peer in content %} <p>{{ peer.remote_as }}</p> {% endfor %} {% endblock %} But I don't get any Data in HTML. any Idea? of a better way? -
Django URL Dispatcher not matching unicode slug
I'm currently trying to process a request using unicode-enabled slugs. i.e., '127.0.0.1:8080/æøå/' works fine for the generic ListView: path('<slug>/', ServiceList.as_view(), name='service-list'), but fails on the DetailView with 0 matches in the SQL query: path('<slug>/', ServiceDetail.as_view(), name='service-detail'), No further errors are given. Am I missing some unicode conversion between the request and the database (SQLite3)? -
Dynamically create serializer based on model field value
I have a model like so: class A: name = models.CharField() group = models.ForeignKey('SomeModel', null=True, blank=True) When I serialize this, I would like the serielizer to have different formats based on whether the 'group' field is blank or not. Of course this can be achieved by having different serializers for different formats and calling them as required in the View layer: class TypeASerializer(serializers.ModelSerializer) class Meta: model = A fields = ('id', 'name') class TypeBSerializer(serializers.ModelSerializer) class Meta: model = A fields = ('id', 'name', 'group') But I wanted to handle it in the serializer layer itself and have a single serializer for this. Is that possible? -
What is the simplest way to create Sign Up form without username. (require only email and password)
I want to create SignUp and Login form with only email and password. Also it means I need CustomUser model without username. I know this question is the one someone else already asked but I couldn't find a good and recent resource of this. Is there anyone could help me? I am really having trouble with this... -
How to filter all the details of a particular data field from one model (Product) and populate it into form
I have a 'Product' Model in which all the details of a product is available and I have a 'Order' Model with Foreign Key of Product Model. I want a dropdown list in From.html with all product name of Product model and if I select any one of them then all the details should automatically filled in the input field. I applied this concept on a particular field like this: Product.objects.filter(pname='Lenovo K8 Plus').values('pname','catgry','brand') From.Html <form class="well form-horizontal" method="post" action="{% url 'new_order' %}"> {% csrf_token %} <fieldset> <div class="form-group"> <label class="col-md-4 control-label">Select Product</label> <div class="col-md-6 inputGroupContainer"> <div class="input-group"> <span class="input-group-addon" style="max-width: 100%;"><i class="glyphicon glyphicon-list"></i></span> <select class="selectpicker form-control" name="pname"> {% for n in ListPrdt %} <option>{{n.pname}}</option> {% endfor %} </select> </div> </div> </div> <div class="form-group"> <label class="col-md-4 control-label">Category Name</label> <div class="col-md-6 inputGroupContainer"> <div class="input-group"><span class="input-group-addon"><i class="glyphicon glyphicon-user"></i></span> {% for n in ListPrdt %} <input id="fullName" name="catgry" placeholder="Full Name" class="form-control" required="true" value="{{n.catgry}}" type="text"> {% endfor %} </div> </div> </div> <div class="form-group"> <label class="col-md-4 control-label">Brand Name</label> <div class="col-md-6 inputGroupContainer"> <div class="input-group"><span class="input-group-addon"><i class="glyphicon glyphicon-user"></i></span> {% for n in ListPrdt %} <input id="fullName" name="brand" placeholder="Full Name" class="form-control" required="true" value="{{n.brand}}" type="text"> {% endfor %} </div> </div> </div> <div class="form-group"> <label class="col-md-4 control-label">Quantity</label> <div class="col-md-6 inputGroupContainer"> <div … -
wsgi_module not found on windows
The wsgi_module loaded as shown in the log below: [Mon Dec 10 10:39:39.048697 2018] [wsgi:info] [pid 16708:tid 692] mod_wsgi (pid=16708): Python home c:/users/.../appdata/local/programs/python/python37. [Mon Dec 10 10:39:39.048697 2018] [wsgi:info] [pid 16708:tid 692] mod_wsgi (pid=16708): Initializing Python. [Mon Dec 10 10:39:39.081683 2018] [wsgi:info] [pid 16708:tid 692] mod_wsgi (pid=16708): Attach interpreter ''. [Mon Dec 10 10:39:39.084682 2018] [wsgi:info] [pid 16708:tid 692] mod_wsgi (pid=16708): Adding 'E:/projects/python/...' to path. [Mon Dec 10 10:39:39.089662 2018] [wsgi:info] [pid 16708:tid 692] mod_wsgi (pid=16708): Imported 'mod_wsgi'. But at the apache modules, the wsgi_module says, No module file as shown in the picture below: It is my http.conf lines which are associated with the mod_wsgi: LoadFile "c:/users/.../appdata/local/programs/python/python37/python37.dll" LoadModule wsgi_module "c:/users/.../appdata/local/programs/python/python37/lib/site-packages/mod_wsgi/server/mod_wsgi.cp37-win_amd64.pyd" WSGIPythonHome "c:/users/.../appdata/local/programs/python/python37" WSGIPythonPath "E:/projects/python/..." WSGIScriptAlias /scripts "E:/projects/python/.../.../wsgi.py" DocumentRoot "E:\\projects\\python\\...\\...\\..." <Directory "E:\\projects\\python\\...\\...\\..."> <Files wsgi.py> Allow From all </Files> # # Possible values for the Options directive are "None", "All", # or any combination of: # Indexes Includes FollowSymLinks SymLinksifOwnerMatch ExecCGI MultiViews # # Note that "MultiViews" must be named *explicitly* --- "Options All" # doesn't give it to you. # # The Options directive is both complicated and important. Please see # http://httpd.apache.org/docs/2.4/mod/core.html#options # for more information. # Options +Indexes +FollowSymLinks +Multiviews +ExecCGI # # AllowOverride controls what directives may … -
Fullcalendar with Django does not save events
I connected the fullcalendar to my django project and now when I save events from the month view, everything works, but as soon as I switch to the day or week display, the events are not saved to the database. However, there are no errors. fullcalendar script <script> $(document).ready(function() { $('#calendar').fullCalendar({ dayClick: function(date, jsEvent, view) { var clickDate = date.format(); $('#start-date').val(clickDate); $('#dialog').dialog('open'); }, eventSources: [ { events: [ {% for i in events %} { title: "{{ i.event_name}}", start: '{{ i.start_date|date:"Y-m-d" }}', end: '{{ i.end_date|date:"Y-m-d" }}', }, {% endfor %} ], } ] }); //add new event $( "#dialog" ).dialog({ autoOpen: false, show: { effect: 'drop', duration: 500 }, hide: { effect: 'clip', duration: 500 } }); $('.datepicker').datepicker({ dateFormat: 'yy-mm-dd' }); }); </script> views.py def event(request): all_events = Events.objects.all() if request.method == 'POST': event_form = ModelEventsForm(request.POST) if event_form.is_valid(): update = event_form.save(commit=False) update.owner = request.user.profile start_date = event_form.cleaned_data['start_date'] update.save() return redirect('events:event') else: event_form = ModelEventsForm() context = { "events": all_events, 'event_form': event_form } return render(request, 'profile/event_management.html', context) models.py class Events(models.Model): owner = models.ForeignKey(Profile, blank=True, null=True, on_delete=models.CASCADE) event_name = models.CharField(max_length=255, null=True, blank=True) start_date = models.DateTimeField(null=True, blank=True) end_date = models.DateTimeField(null=True, blank=True) event_type = models.CharField(max_length=10, null=True, blank=True) -
Danjgo: Unsupported lookup 'case_exact' for CharField or join on the field not permitted
This is the GET request hitting on my server. HTTP GET /testPage/?persona_name=Aman&key_name=country&key_label=My+Country&key_value=India&Save=Submit 500 With the help of this view i am fetching the values from GET request. def PersonaSave(request): persona_name = request.GET.get('persona_name',) persona_key = request.GET.get('key_name',) persona_key_value = request.GET.get('key_value',) persona_key_label = request.GET.get('key_label',) persona_submit = request.GET.get('Save',) return( persona_name , persona_key , persona_key_label , persona_key_value , persona_submit Now following is the function where i am checking whether object with the given persona name exists or not. If it exists then i am updating the values if it is a new persona then i am making new testPersona object. def TestPageView(request): x=PersonaSave(request) persona_name = x[0] persona_key = x[1] persona_key_label=x[2] persona_key_value=x[3] persona_submit=x[4] testPersonaName = TestPersonaName(name=persona_name) testPersonaName.save() if(persona_name is None and persona_key is None and persona_key_label is None and persona_key_value is None): return render(request, 'dashboard/test_page.html') # Below is the function for updating testPersona . elif TestPersonaName.objects.filter(name__case_exact=persona_name).exists(): testpersona = TestPersona.objects.get(name__case_exact=persona_name) if testpersona.key == persona_key: testpersona.label= persona_key_label testpersona.value = persona_key_value testpersona.save() #If persona with new name is detected then saving a new testPersona object. testpersona=TestPersona(name=persona_name,key=persona_key,label=persona_key_label,value=persona_key_value) testpersona.save() return render(request,'dashboard/test_page.html') Following is the error that i am getting. django.core.exceptions.FieldError: Unsupported lookup 'case_exact' for CharField or join on the field not permitted. Below are TestPersona and TestPersonaName models. class TestPersonaName(models.Model): name …