Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Although I use django-modeltranslation, can I display only original field at createview?
I'm trying to display only original field at createview. is there anything to do that? -
Django Rest Framework nested relationship
I'm new in using Django, I need your help So, I created a model like this models.py from django.db import models # Create your models here. class Pegawai(models.Model): name = models.CharField(max_length=60) alias = models.CharField(max_length=60) def __str__(self): return self.name class Barang(models.Model): pegawai = models.ForeignKey(Pegawai,on_delete=models.CASCADE,related_name='barangs',) nama_barang = models.CharField(max_length=60) harga_barang = models.CharField(max_length=60) def __str__(self): return self.pegawai.name my serializer: serializers.py from rest_framework import serializers, fields from .models import Pegawai,Barang class BarangSerializer(serializers.ModelSerializer): class Meta: model = Barang fields = ( 'pegawai', 'nama_barang', 'harga_barang', ) class PegawaiSerializer(serializers.ModelSerializer): barangs = BarangSerializer(read_only=True, many=True) class Meta: model = Pegawai fields = ( 'id', 'name', 'alias', 'barangs', ) my views: views.py from rest_framework import viewsets from .serializers import PegawaiSerializer,BarangSerializer from .models import Pegawai,Barang class BarangViewSet(viewsets.ModelViewSet): queryset = Barang.objects.all().order_by('nama_barang') serializer_class = BarangSerializer class PegawaiViewSet(viewsets.ModelViewSet): queryset = Pegawai.objects.all().order_by('name') serializer_class = PegawaiSerializer Results: { "id": 5, "name": "Ryan", "alias": "R", "barangs": [ { "pegawai": 5, "nama_barang": "burjo", "harga_barang": "1234" }, Question: how can i change pegawai fields from id to name? like this: { "id": 5, "name": "Ryan", "alias": "R", "barangs": [ { "pegawai": Ryan, "nama_barang": "burjo", "harga_barang": "1234" }, I've searched some solutions but nothing works, I don't know where the problem is, so I need your guide. Cheers. -
assert_called() raising exception even though class was instantiated
Using this answer as a model, I am testing the following method: from django.core.mail import EmailMultiAlternatives from django.template.loader import render_to_string from django.utils.html import strip_tags def send_email(template_path, context, subject_line, from_email, to=[], cc=[], bcc=DEFAULT_BCC_EMAILS): msg_html = render_to_string(template_path, context) msg_plain = strip_tags(msg_html) email = EmailMultiAlternatives(subject_line, msg_plain, from_email, to, cc=cc, bcc=bcc) email.attach_alternative(msg_html, "text/html") email.send() using test.py: from unittest.mock import patch from django.core.mail import EmailMultiAlternatives from django.template.loader import render_to_string from django.test import TestCase from admintools.emailer import send_email from admintools.settings import DEFAULT_BCC_EMAILS class EmailerTestCase(TestCase): @patch('django.core.mail.EmailMultiAlternatives') def test_send_email(self, mockEmailMultiAlternatives): context = {} template_path = "emails/closings/seller_pre_close_update_prompt.html" msg_plain = render_to_string(template_path, context) to = [''] cc = [''] send_email(template_path, {}, 'subject', "from", to, cc=cc) mockEmailMultiAlternatives.assert_called() I receive AssertionError: Expected 'EmailMultiAlternatives' to have been called. even though email is created successfully during the running of the test (verified by a print(email) immediately after the instantiation returning <django.core.mail.message.EmailMultiAlternatives object at 0x7fbf4bb4b590>). What might be causing the assertion to fail even though EmailMultiAlternatives is being instantiated? -
Django: Writing java script inside the template vs loading java script file in the template
I am using javascript to add comment without refreshing the page. When I am using the javascript inside the template it is working perfectly fine but if I am writing the java script to a file and loading the file inside the template then it is not displaying the name of the person who wrote the comment (It is displaying the comment fine). Below is the java script I used inside the template function create_comment(event,div_id,form_id,commentinsert_id) { event.preventDefault(); var text_id = '#'.concat(div_id,' ','#comment-text') var slug_id = '#'.concat(div_id,' ','#post_slug') var appenddiv_id = '#'.concat(div_id) comment_count ++; var divcommentinsert_id = 'inserted_comment-'.concat(comment_count.toString()) $.ajax({ url : "create_comment/", // the endpoint type : "POST", // http method data : { text : $(text_id).val(), post_slug: $(slug_id).val(),}, // handle a successful response success : function(json) { div.innerHTML = ` <div id = `+divcommentinsert_id+` class="card-footer"> <div class="row"> <div> <img src="{{user.profile.profile_picture.url}}" alt="" width="40" height="40"> </div> <div class="col-md-8"> <b style="color:rgb(240, 0, 0);"> {{user.first_name}} {{user.last_name}}</b> <br> `+json.text+` <a onClick="edit_comment('`+json.slug+`','`+divcommentinsert_id+`','`+json.text+`')"><i class="fa fa-edit"></i></a> <a onClick="delete_comment('`+json.slug+`','`+divcommentinsert_id+`')"><i class="fa fa-trash-o"></i></a> </div> </div> </div>`; document.getElementById(commentinsert_id).appendChild(div); document.getElementById(form_id).reset(); }, // handle a non-successful response error : function(xhr,errmsg,err) { $('#results').html("<div class='alert-box alert radius' data-alert>Oops! We have encountered an error: "+errmsg+ " <a href='#' class='close'>&times;</a></div>"); // add the error to the dom console.log(xhr.status … -
How to use LoginRequiredMixin with UserPassesTestMixin correctly
I have a custom view with LoginRequiredMixin and UserPassesTestMixin: class CustomListView(LoginRequiredMixin, UserPassesTestMixin, ListView): template_name = '_global/_list.html' raise_exception = True permission_denied_message = 'You must select an issuer.' def test_func(self): return self.request.session.get('issuer_pk', None) is not None This works as expected unless I access the view with an anonymous user, in which case I get the 403 error and not a login redirect. The desired behaviour is to first require an authenticated user and then pass the tests. Have I got the inheritance wrong somehow? -
Updating a column in Django Rest Api causes 'Column cannot be null' error
I am trying to 'delete' a column by changing the status (Yes, it is in my model and is set upon creation) instead of physically deleting it from the database. I therefore created my view and queried the item. When I send a post request I keep getting an error 'Column 'seller_id' cannot be null'. I've been researching and I see that in models.py I should just change null=True. The problem is I don't want that column to be able to be null when creating an item. Is there a way I can update a single field without having to update the non-nullable field? Do I need to include the non-nullable info when updating? models.py seller = models.ForeignKey(AppUser, blank=True, null=False, on_delete=models.SET('inactive'), related_name='product', verbose_name='User') views.py class ProductDeleteView(generics.ListCreateAPIView): queryset = Product.objects.all() serializer_class = ProductDeleteSerializer permission_classes = (IsAdminOrOwnerOrReadOnly,) def get_queryset(self): if self.kwargs.get('pk', None) is not None: return Product.objects.get(pk=self.kwargs['pk']) else: data = {'full_messages': ['Could not delete product.']} return Response(data, status=status.HTTP_403_FORBIDDEN) def delete(self): product = queryset product.status = 99 product.save() data = {'full_messages': ['Product deleted successfully.']} return Response(data, status=status.HTTP_200_OK) serializers.py class UserDeleteSerializer(serializers.ModelSerializer): class Meta: model = Product fields = ['status'] -
Got my datepicker widget setting the right format....now validation on django form fails
I have a form (rendered with crispy forms) I define in forms.py: class Meta: model=HousingRequest fields = ('off_site_location', 'notes', 'checkin_date', 'checkout_date', 'purpose_of_visit', 'project_for_visit') widgets = { #'room' : TextInput(attrs={'tabindex':'1', 'placeholder':'Trainee First Name'}), #'user' : TextInput(attrs={'tabindex':'1', 'placeholder':'Trainee First Name'}), #these are really already from who is logged in? #'male': TextInput(attrs={'tabindex':'3', 'placeholder':'Trainee''s Institution'}), #we might get this from who is logged in also 'off_site_location' : TextInput(attrs={'tabindex':'4', 'placeholder':'Offsite location'}), 'off_site_phone' : TextInput(attrs={'tabindex':'5', 'placeholder':'Contact Phone'}), 'notes' : TextInput(attrs={'tabindex':'5', 'placeholder':'notes'}), 'checkin_date':DateInput(attrs={ 'class':'datepicker form-control', 'tabindex' : '6', 'placeholder' : 'Checkin Date MM/DD/YYYY', 'autocomplete':'off', }, format='%b %d, %Y'), ...etc... The format I set is to be: Oct 25, 2019 Great. My date picker now returns this format (when on another form it was returning 10/25/2019) it is defined in my base.html <script type="text/javascript"> $(function() { var j = jQuery.noConflict(); j('.dateinput').datepicker({ dateFormat: "M dd, yy" }); }); </script> Okay, so I click in the field, date picker comes up. Select it bam I get: Oct 25, 2019 I goto save the form the field says 'Enter a valid date'. No idea where or why the validation is failing. The whole reason for this is on another form using a simple: <td> {{ hou.checkin_date}} </td> It kept displaying as … -
Job for uwsgi.service failed because the control process exited with error code
I am trying to deploy my django app using nginx and uWSGI. However I cannot start uWSGI on emperor mode. If I sudo systemctl start uwsgi Then fails saying Loaded: loaded (/etc/systemd/system/uwsgi.service; enabled; vendor preset: enabled) Active: failed (Result: exit-code) since Thu 2020-01-09 08:15:01 JST; 1min 47s ago Process: 23295 ExecStartPre=/usr/bin/bash -c mkdir -p /run/uwsgi; chown nginx:nginx /run/uwsgi (code=exited, status=203/EXEC) my /etc/systemd/system/uwsgi.service is [Unit] Description=uWSGI Emperor service [Service] ExecStartPre=/usr/bin/bash -c 'mkdir -p /run/uwsgi; chown nginx:nginx /run/uwsgi' ExecStart=/home/me/.venv/uwsgi/bin/uwsgi --emperor /etc/uwsgi/vassals Restart=always KillSignal=SIGQUIT Type=notify NotifyAccess=all Any help is appreciated. -
How can I keep Django admin users' action history after user has left company?
When an admin user has "staff status" disabled, how can I keep their user name/action history connected to the admin pages? example: I have an order page that shows who approved an order. Employee X approves the order, but then employee X leaves the company, so their user has "staff status" turned off. This causes the user's user name disappear from the order, leaving it looking like it was approved by no one. I'm sure that other people have had this problem when using the Django admin, but I couldn't find an answer here or on google! Thanks much! -
Cannot save record from Django Model
I am making a change to a record in a sqlite3 database using Django, and the save() function doesn't seem to work. I am able to save changes using the graphical admin app however. Here is the code to the specific model I'm trying to do the save in: def pickup(self,item): room_items = Item.objects.filter(roomID = self.id) items = [ri.item_name for ri in room_items] if item in items: i = Item.objects.filter(item_name = item) i[0].roomID = 0 i[0].playerID = self.id i[0].save() return f'{self.name} picked up the {item} from {self.room}' else: return f"{item} is not in the room. can't pick it up." the pickup function is in a class called Player. I am updating an Item record. Any solutions? -
Django: get choices key from display value
Let's say I have the following Django model: class Person(models.Model): SHIRT_SIZES = ( (0, 'Small'), (1, 'Medium'), (2, 'Large'), ) name = models.CharField(max_length=60) shirt_size = models.IntegerField(choices=SHIRT_SIZES) I can create create a Person instance and get the shirt_size display value very easily: john = Person(name="John", shirt_size=2) john.shirt_size # 2 john.get_shirt_size_display() # 'Medium' How can I do this the other way? That is, given a shirt size of Medium, how can I get the integer value? I there a method for that or should I write my own method on the Person object like so: class Person(models.Model): ... @staticmethod def get_shirt_size_key_from_display_value(display_value): for (key, value) in Person.SHIRT_SIZES: if value == display_value: return key raise ValueError(f"No product type with display value {display_value}") -
Standalone REST API & Standalone React SPA vs Django and React combined
I would like to create a React SPA, which is fed by querying a Django REST API. I was reading this, and I encounter this point: I see the following patterns (which are common to almost every web framework): React in its own “frontend” Django app: load a single HTML template and let React manage the frontend (difficulty: medium) Django REST as a standalone API + React as a standalone SPA (difficulty: hard, it involves JWT for authentication) Mix and match: mini React apps inside Django templates (difficulty: simple) It seems that in case of an SPA (Single Page Application), it would be better to choose 1. As far as I understand, the React app would just be a big file with all the required css, html and js, right? So we just create this file, and serve it on a specific endpoint of the Django app. Then, I do not understand the benefits of the "standalone" way of doing things. We would need two different domains, it would cause issues with authentication, and the standalone SPA would in fact just be serving a static file right? Is there a reason why it would be interesting to use a standalone … -
Is there a way to update a update query like this?
I'm creating an API to request an email and a password, but the thing is that I want that email and password to be unavailable for 10 minutes once I called them the first time, then when the 10 minutes passed, that email and password will be available again. This is the model class User(models.Model): mail = models.EmailField(max_length=100) password = models.CharField(max_length=60) date = models.DateTimeField() def __str__(self): return self.mail The serializers. from .models import User class UserSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Usuario fields = ['mail', 'password', 'date'] class InactiveUser(serializers.HyperlinkedModelSerializer): class Meta: model = User fields = ['mail'] The views class UserViewSet(viewsets.ModelViewSet): permission_classes = (IsAuthenticated,) queryset = Usuario.objects.all().order_by('mail') serializer_class = UsuarioSerializer class GetUser(viewsets.ModelViewSet): permission_classes = (IsAuthenticated,) future = timezone.now() + timezone.timedelta(minutes=10) queryset = User.objects.filter(date__lt=future)[:1] for u in queryset: u.date = timezone.now() u.save() break serializer_class = UserSerializer -
Modal and Contact form in Django
I'm busy creating a website. I was busy setting the URL's of the Navbar and I came across a conundrum Currently, I have a contact form at the bottom of my Index page. the contact form uses the Include method from Django to render the parts of the Index page. So to the short end of it is that the Contact form doesn't have a view or URL So I was wondering if there is a way to set the Contact form by Id or class in my Navbar so when the user is on the Index page it slides down to the contact form and on other pages, it opens a modal containing the from. I would like to avoid having the modal pop up on the Index page because then it makes the contact form at the bottom kind of redundant. If this is not possible then I think I might just remove the contact form at the bottom and just use a modal site wide. Need some advice if this is possible or other approaches would be welcomed Kind Regards. -
Password Reset in Django with rest_auth
I have extended PasswordResetConfirmSerializer from rest_auth.views. and the url pattern is mapped as follows. urlpatterns = [ . path('password/reset/confirm/<uidb64>/<token>/', PasswordResetConfirmView.as_view(), name='password_reset_confirm'), . ] The email generates the password reset content which provide the link matching the above pattern. But this api has fields for : new_password1 new_password2 uid token How to pass the uid and token from URL to the post field? Or is there any other method? -
set the default authentication to IsAuthenticated in settings.py globally but I can still access the endpoints in django rest framework
I have set the default authentication class to IsAuthenticated globally in settings.py file but still, I can still access the endpoints. what could be the issue? Below are the Django rest frameworks' configs in settings.py file. REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSESS': [ 'rest_framework.permissions.IsAuthenticated', ], 'DEFAULT_AUTHENTICATION_CLASSES': ( 'liquor.authentication.JSONWebTokenAuthentication', ), 'DEFAULT_SCHEMA_CLASS': 'rest_framework.schemas.coreapi.AutoSchema', 'DEFAULT_PARSER_CLASSES': [ 'rest_framework.parsers.FormParser', 'rest_framework.parsers.MultiPartParser', 'rest_framework.parsers.JSONParser', ], 'DEFAULT_FILTER_BACKENDS': ['django_filters.rest_framework.DjangoFilterBackend'], 'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination', 'PAGE_SIZE':100, 'DEFAULT_RENDERER_CLASSESS': ( 'rest_framework.renderers.JSONRenderer', 'rest_framework.renderers.BrowsableAPIRenderer', ), } -
Model to view as dictionary then render it as a html table
Im learning Django and get stuck with this problem. I need to list "users" with their respective data to an html list. I tried but there is no list generated. Already have my db populated with 100 lines. This is my models.py from django.db import models # Create your models here. class General(models.Model): id = models.CharField(max_length=128, primary_key=True) name= models.CharField(max_length=128) lastname= models.CharField(max_length=128) state= models.CharField(max_length=128) asd= models.CharField(max_length=128) spc= models.CharField(max_length=128) dot = models.CharField(max_length=128, blank=True) def __str__(self): return self.name This is my views.py, already tried "return render_to_response", and tried to use General.objects.all()/General.objects.get() but it says "General has no objects" so i cant make the dictionary manually from django.shortcuts import render from Myapp.models import General from django.forms.models import model_to_dict # Create your views here. def VisualizadorGeneral(request): listaGeneralDic = model_to_dict(General) return render(request, "VisualizadorGeneral.html", context=listaGeneralDic) And this is my HTML: <div class="container"> {% if listaGeneralDic %} <table class="table table-bordered table-hover"> <thead> <tr> <th>id</th> <th>name</th> <th>lastname</th> <th>state</th> <th>asd</th> <th>spc</th> <th>dot</th> </tr> </thead> <tbody> {% for dato in listaGeneralDic %} <tr> <td scope="row">{{ dato.id }}</td> <td>{{ dato.name }}</td> <td>{{ dato.lastname }}</td> <td>{{ dato.state }}</td> <td>{{ dato.asd }}</td> <td>{{ dato.spc }}</td> <td>{{ dato.dot }}</td> </tr> {% endfor %} </tbody> {% else %} <p>Nothing to see</p> {% endif %} </table> </div> … -
How do I access Django URL parameter /<thing>/ in HTML template?
urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^', include('Homepage.urls')), url(r'^RepairLog/', include('RepairLog.urls')), url(r'^RepairLog/DMRView/', TemplateView.as_view(template_name="RepairLog/DMRView.html"),name="dmr view"), url(r'^RepairLog/DMRtab/', TemplateView.as_view(template_name="RepairLog/DMRtab.html"),name="dmrtab"), url(r'^RepairLog/DMRwork/', TemplateView.as_view(template_name="RepairLog/DMRwork.html"),name="dmrwork"), url(r'^Inventory/', include('Inventory.urls')), url(r'^Inventory/inventory/<barcodething>/', TemplateView.as_view(template_name="Inventory/inventory.html"),name="inventory"), url(r'^Inventory/inventory/', TemplateView.as_view(template_name="Inventory/inventory.html"),name="inventory"), url(r'^Inventory/createitem/', TemplateView.as_view(template_name="Inventory/createItem.html"),name="createitem"), url(r'^Inventory/manageitem/', TemplateView.as_view(template_name="Inventory/manageItem.html"),name="manageitem"), url('accounts/', include('django.contrib.auth.urls')),] ##Necessary to login validation I am trying to access barcodething in my inventory.html template. I have tried {{barcodething}} but that does not work. URL I am using is http://127.0.0.1:8000/Inventory/inventory/123456789/ which should pass barcodething=123456789 -
oTree / Django crashes in Heroku. Procfile issue?
I'm trying to start a Django app (oTree) from Heroku. The app runs locally without any problem. This is not the first time I'm using Heroku with otree, but it's been a while and last time it did not require a Procfile. Any help to understand what is going on and how to solve this is most welcome. This is what I have: Procfile: web: otree worker: otree requirements.txt -r requirements_base.txt psycopg2>=2.5.1 requirements_base.txt otree[mturk]>=2.4.0 numpy>=1.16.2 runtime.txt python-3.7.2 This is what I get from heroku logs --tail: 2020-01-08T21:41:00.953405+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=#####.herokuapp.com request_id=dc8f2e6b-dd42-472a-83e0-718dbff70da7 fwd="###.##.###.###" dyno= connect= service= status=503 bytes= protocol=https 2020-01-08T21:40:40+00:00 app[heroku-redis]: source=REDIS addon=redis-trapezoidal-96051 sample#active-connections=1 sample#load-avg-1m=0.055 sample#load-avg-5m=0.04 sample#load-avg-15m=0.035 sample#read-iops=0 sample#write-iops=23.208 sample#memory-total=15664264kB sample#memory-free=10627332kB sample#memory-cached=2909616kB sample#memory-redis=1686888bytes sample#hit-rate=1 sample#evicted-keys=0 2020-01-08T21:42:36+00:00 app[heroku-redis]: source=REDIS addon=redis-trapezoidal-96051 sample#active-connections=1 sample#load-avg-1m=0.03 sample#load-avg-5m=0.04 sample#load-avg-15m=0.035 sample#read-iops=0 sample#write-iops=23.093 sample#memory-total=15664264kB sample#memory-free=10618212kB sample#memory-cached=2921856kB sample#memory-redis=1686888bytes sample#hit-rate=1 sample#evicted-keys=0 -
Django HttpResponseRedirectwith URL Variables handling
I created an input form to get the data into web and use the inputs for an AP call. When I want t refresh the page, there is a popup asking if you want to refresh the input. This is very annoying. The solution was to use HttpResponseRedirect, which workout nicely, but it's throwing away all the inputs. Then the though would be to use variable in the URL with "URL?rds=2". How do you get the input variables through the HttpResponseRedirect to the same site? And also how to get variables from URL to input and from input to the URL? -
How to implement different sessions for different users in django
My front end is login in different users but when the 2 different users send a ajax request at same time or different time backend(python) is taking the recent request and over writing the old request, How to overcome this in django. Additional info: I deployed my application using aws elastic beanstalk and using apache server -
Django Delete Picture On Update
I have in my models to auto size a picture when a user uploads a picture on their profile. However i want to create a delete rule to delete the original picture . What is easiest way to do this ? Here is my def for the down size. class Profile(models.Model): user = models.OneToOneField(User, on_delete= models.CASCADE) image = models.ImageField(default ="default.png", upload_to='profile_pics') grade = models.CharField(max_length = 2, default= "") bio = models.TextField(max_length = 255, default= "") teacherpsid = models.CharField(default = "", max_length = 50, null = True) def __str__(self): return f'{self.user.username} Profile' def save(self, *args, **kwargs): super().save(*args, **kwargs) img =Image.open(self.image.path) if img.height > 300 or img.width > 300: output_size = (300, 300) img.thumbnail(output_size) img.save(self.image.path) -
Gatsby and django - dynamic subpages
I'm trying to combine my Gatsby frontend and Django backend. The communication seems to be flawless using the django rest framework. However, I do not know, how to dispatch traffic correctly. Currently, I'm basing on the following urls.py config. urlpatterns = [ path('', views.IndexView.as_view(), name='index'), path("elements/template_1/<int:id>/", views.template_1, name='template-1'), ] And it is how the view looks like: def template_1(request): return render(request, 'template_1/index.html') It works nearly good, but after index.html is loaded it changes the url to elements/template_1/ effectively cutting the id part. I think it will be a matter of gatsby's prefix path, which is defined as elements/template_1/. How can I preserve the correct URL? It is necessary for user (as he will be able to copy a direct link to particular item). -
Django Sending Email with Office365 on Pythonanywhere
I have deployed my web project on Pythonanywhere. Im sending email with gmail SMTP but i want to send with Office365 (company account). I used many options but i didnt figure it out. It exists in whitelist of Pythonanywhere It throws that error: Expection value : [Errno 101] Network is unreachable in my settings.py like that: EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.office365.com' EMAIL_HOST_USER = 'xyz@domainname.com' EMAIL_HOST_PASSWORD = '########' EMAIL_PORT = 587 EMAIL_USE_TLS = True DEFAULT_FROM_EMAIL = 'xyz@domainname.com' SERVER_EMAIL = 'xyz@domainname.com' Thank you all. -
How to render an input field in a template bound to a model field in Django
The problem seems so solvable yet it eludes me. Hope I am able to explain my predicament. I am trying to include a jQuery autocomplete in a form. The autocomplete itself is working fine. I am now trying to link it to a model which is something like this: models.py class SupplierCatchment(models.Model): supp = models.ForeignKey(Supplier.....) supp_area = models.ForeignKey(Country, ...) supp_remarks = models.CharField(max_length=150,...) For rendering the form, I am using a model form. Case 1: In my template I am rendering the fields manually looping through the fields. For the autocomplete field, however I am using html input like this: Template ..... {% if field.name == "supp_area" %} <input type="text" id="supp_area" name="supp_area" placeholder="..."> <!-- My area of concern --> {% else %} {{ field }} .... During processing, the autocomplete field id="supp_area" picks up the values correctly from the Country model. However on saving, I am able to save only the data entered in field supp_remarks and the field supp_area remains blank (it is not a required field). Case 2: I have tried to force field id using attrs in my model form like this (adapted from here): class CreateSuppAreaForm(forms.ModelForm): .... class Meta: model = SupplierCatchment fields = ('supp_area', 'supp_remarks') widgets …