Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django views error in importing custom python files
I am trying to import main1.py file in views.py of my django app. But unable to import it. Moreover location of my main file and sub-dependent file also lies at the view.py folder location. I have tried with following options 1 import main with this error is : No module found with name main 2 from .app_name import main using this error is : import * only allowed at module level folder structure is -
How to replace threads in Django to Celery worker
I know it's not best practice use threads in django project but I have a project that is using threads: threading.Thread(target=save_data, args=(dp, conv_handler)).start() I want to replace this code to celery - to run worker with function save_data(dispatcher, conversion) Inside save_data I have infinite loop and in this loop I save states of dispatcher and conversation to file on disk with pickle. I want to know may I use celery for such work? Does the worker can see changes of state in dispatcher and conversation? -
Django queryset : How to exclude objects with any related object satisfying a condition
I stumbled upon a weird behaviour of django querysets while making a difficult query and I'd like to know if somebody knew how to improve this query. Basically I have a model like this: class Product(models.Model): pass class Stock(models.Model): product_id = models.ForeignKey(Product) date = models.DateField() initial_stock = models.SmallIntegerField() num_ordered = models.SmallIntegerField() And I'd like to select all Product that are not available for any date (means that there are no stock object related to the product which have their initial_stock field greater than the num_ordered field). So at first, I did: Product.objects.exclude(stock__initial_stock__gt=F('stock__num_ordered')).distinct() but I checked and this query translates as: SELECT DISTINCT * FROM "product" LEFT OUTER JOIN "stock" ON ("product"."id" = "stock"."product_id") WHERE NOT ("product"."id" IN ( SELECT U1."product_id" AS Col1 FROM "product" U0 INNER JOIN "stock" U1 ON (U0."id" = U1."product_id") WHERE (U1."initial_stock" > (U1."num_ordered") AND U1."id" = ("stock"."id")) )) Which makes a left join on stocks and then filters out the lines where the initial_stock is greater than the num_ordered before sending me back the distinct lines as a result. So as you can see, it doesn't work when I have a stock object that is out of stock and another stock object that is not out … -
Publish to MQTT in django Serializer save() method
I have a really simple API that uses django with restframework that act as an endpoint for iot devices. iot Devices --HTTP POST--> REST API (django) Data is validated and saved. No need for any render or GET/PATCH/DELETE at all. The only thing is that I'm not saving to database but I'd like to push to MQTT channel (other process that listen for messages will save/postprocess) As I am not a django expert at all, My idea was to override the Serializer save() method that it actually does not save but publish. MODEL class Meas(models.Model): SENSOR_TYPES = [ ('temperature','temperature'), ('humidity','humidity') ] sensorType = models.CharField(max_length=100, default='UNKNOWN', choices = SENSOR_TYPES ) sensorId = models.CharField(max_length=100) homeId = models.CharField(max_length=100) roomId = models.CharField(max_length=150) hubId = models.CharField(max_length=100) value = models.CharField(max_length=100) last_seen = models.DateTimeField() elapsed = models.IntegerField() objects = MeasManager() SERIALIZER class MeasMQTTSerializer(serializers.ModelSerializer): client = RMQPublisher(ch_name=rmq_chname,routing_key=rmq_routingkey,host=rmq_host,user=rmq_user,password=rmq_pass,port=rmq_port) class Meta: model = Meas fields = '__all__' def save(self): logging.debug("Saving measurement") measurement = self.validated_data['sensorType'] mytags = { 'sensorId' : self.validated_data['sensorId'], 'roomId' : self.validated_data['roomId'], 'hubId' : self.validated_data['hubId'], 'homeId' : self.validated_data['homeId'], 'elapsed' : self.validated_data['elapsed'], 'last_seen' : self.validated_data['last_seen'] } for a, x in mytags.items(): mytags[a]=str(x) value = float(self.validated_data['value']) rmq_msg = mytags rmq_msg['value']=value rmq_msg['measurement'] = measurement MeasMQTTSerializer.client.pushObject(rmq_msg) logging.debug("Pushed to RMQ") and RMQPublisher use just … -
Delay in updating live status from text file in django
I want to update some live status through text file on django html template. Issue is sometimes delay comes very late, not sure if this is due to linux-server dependencies or something else. Also, what is recommended location to store live logs for reading purpose, currently I am using static directory in django server. function update() { var xmlhttp = new XMLHttpRequest(); xmlhttp.onreadystatechange = function () { document.getElementById("live_status").innerHTML = this.readyState; if (this.readyState == 4 && this.status == 200) { var myObj = JSON.parse(this.responseText); x = "{{ details.chip_name }}" + "</br>"; for ( i in myObj.users ){ for ( j in myObj.users[i].live_status ){ x += myObj.users[i].live_status[j] + "</br>"; } } document.getElementById("live_status").innerHTML = x; //document.getElementById("live_status").innerHTML = "Test"; } }; xmlhttp.open("GET", "{% static 'live_status.txt' %}", true); xmlhttp.send(); } update(); setInterval(update, 10000); -
Login system which search in database in django
I have my own model and and i want to make login system which check in that model rather than default user model . Can anybody help me with this . I have been stuck in this problem for long time. I searched alot but could not find any solution. -
How to make a view as a url in templates.? (Python 3.6, Django 2.2)
These are my code #urls urlpatterns += [ path('blog/', include('blog.urls', namespace='blog')), path('products/', include('products.urls', namespace='products')), ] This is app urls # urls app_name = 'products' urlpatterns = [ path('', ProductHomeView.as_view(), name='home'), path('details/', ProductView.as_view(), name='details'), ] This is my view #views class ProductHomeView(View): def get(self, request, *args, **kwargs): product_data = Product.objects.all() context = { 'product': product_data, } return render(request, 'product_home.html', context) class ProductView(View): def get(self, request, *args, **kwargs): product_data = Product.objects.all() context = { 'product': product_data, } return render(request, 'product.html', context) this is my template # template product_home.html {% for product in product %} <h1>{{ product.tittle }}</h1> <p>{{ product.short_description }}</p> <button type="button"><a href="{% url 'products.details' %}">Explore More</a></button><br> {% endfor %} This is the error Error django.urls.exceptions.NoReverseMatch: Reverse for 'products.details' not found. 'products.details' is not a valid view function or pattern name. How do I resolve this? -
IntegrityError at /create/ (1048, "Column 'laenge' cannot be null")
While submitting my form in Django I get an IntegrityError that I can't resolve. I found other solutions to this problem where it was sugested to set null=True and blank=True. However, I don't want this field to be null=True. I submitted the form with trailform-laenge = '44', and I also printed out the cleaned data in my view which gave me 44. The DEBUG mode shows me that internaly laenge is set to Null when storing it in the database. I already reset the database and migrated the model again, but the same error still appears. views.py def create_trail(request): if request.method == 'POST': trailform = TrailForm(request.POST, request.FILES, prefix="trailform") etappeformset = EtappeFormset(request.POST, prefix="etappeformset") bildformset = BildFormset(request.POST, prefix="bildformset") if trailform.is_valid() and etappeformset.is_valid() and bildformset.is_valid(): trail = trailform.save(commit=False) trail.autor = request.user trail.save() trail = get_object_or_404(Trail, pk=trail.id) models.py class Trail(models.Model): laenge = models.DecimalField( #in Kilommeter max_digits=7, decimal_places=2, verbose_name='Streckenlänge', help_text='in Kilometern', validators=[MinValueValidator(0)] ) IntegrityError at /create/ (1048, "Column 'laenge' cannot be null") Request Method: POST Request URL: Django Version: 2.2 Exception Type: IntegrityError Exception Value: (1048, "Column 'laenge' cannot be null") Exception Location: /home/name/.local/lib/python3.6/site-packages/django/db/backends/mysql/base.py in execute, line 76 Python Executable: /usr/bin/python Python Version: 3.6.7 Python Path: ['/home/t_puetz16/django_code/stupro', '/usr/lib/python36.zip', '/usr/lib/python3.6', '/usr/lib/python3.6/lib-dynload', '/home/t_puetz16/.local/lib/python3.6/site-packages', '/usr/local/lib/python3.6/dist-packages', '/usr/lib/python3/dist-packages'] Server time: … -
AUTH_USER_MODEL refers to model 'auth.User' that has not been installed , how to provide default user logged in value in models.py
im trying to provide default value from models.py class OrderManager(models.Manager): def staff_rest(self ,request): return self.staff = request.user class Order(models.Model): staff = models.CharField(max_length=20 , default='') id = models.AutoField(primary_key = True) pass objects = OrderManager() but i got this error AUTH_USER_MODEL refers to model 'auth.User' that has not been installed i also tried to override same() method def save(self , *args,**kwargs): self.staff = request.user super(Order,self).save() error :name 'request' is not defined thanks for helping -
"NoReverseMatch" issue in Django
NoReverseMatch at /en-us/schools/1/classroom/1/update/ Reverse for 'index' with arguments '('',)' not found. 1 pattern(s) tried: ['en-us/schools/(?P\d+)/index/$'] urls.py url(r'^(?P\d+)/classroom/(?P\d+)/update/$', views.ClassroomUpdateView.as_view(), name='classroom_update') -
Unable to migrate with django_mssql_backend to outside host
I'm trying to migrate my django project and use SQL Server 2012 as database backend. For connection, i'm using django-mssql-backend. But, something wrong happen when trying to migrate. File "C:\ProgramData\Anaconda3\lib\site-packages\django\db\backends\utils.py", line 76, in _execute_with_wrappers return executor(sql, params, many, context) File "C:\ProgramData\Anaconda3\lib\site-packages\django\db\backends\utils.py", line 84, in _execute return self.cursor.execute(sql, params) File "C:\ProgramData\Anaconda3\lib\site-packages\django\db\utils.py", line 89, in __exit__ raise dj_exc_value.with_traceback(traceback) from exc_value File "C:\ProgramData\Anaconda3\lib\site-packages\django\db\backends\utils.py", line 82, in _execute return self.cursor.execute(sql) File "C:\ProgramData\Anaconda3\lib\site-packages\django_mssql_backend-2.2.0-py3.7.egg\sql_server\pyodbc\base.py", line 536, in execute django.db.utils.Error: ('21000', '[21000] [Microsoft][ODBC Driver 13 for SQL Server][SQL Server]Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression. (512) (SQLExecDirectW); [21000] [Microsoft][ODBC Driver 13 for SQL Server][SQL Server]The statement has been terminated. (3621)') And here my code for define database in settings.py: DATABASES = { 'default': { 'ENGINE': 'sql_server.pyodbc', 'NAME': 'djangodb', 'USER': 'user', 'PASSWORD': 'pass', 'HOST': '172.30.55.7', 'PORT': '', 'OPTIONS': { 'driver': 'ODBC Driver 13 for SQL Server', }, } } As info, database host to another server and I ain't use model. But, if I change database host into 'localhost' (of course, I created same database in my local computer), migration process success. Thanks for help. -
How can I create objects in a for-loop in python?
I'm trying to create some objects in database through a for loop in python, but when I try, it only inserts last one. This is the code I have, where 'langssplit' is a list, the result of spliting a string like '2-3' (the pks of the Language rows in the table). I need to create and insert an object into the database for each element on the list, but it only saves the last one. The newprofile is an object I have already created. langsparam = request.GET.get('langs', '') langssplit = langsparam.split('-') for lan in langssplit: lang = Languages.objects.filter(pk=lan).first() newprofilelan = ProfilesLanguages(profile=newprofile, language=lang) newprofilelan.save() What am I doing wrong? Thanks for any help! -
Validation of custom widgets
How should validation errors be propagated for custom widgets where the widget input itself may be incoherent? Case in point, I'm creating a custom date input widget for a Date field that allows the user to select the date according to the Japanese Imperial calendar. This requires an era dropdown and a year input, and it's perfectly possible to select an era–year combination that is in itself invalid. The widget converts this input to/from a Python date object using the MultiWidget.value_from_datadict/MultiWidget.decompress methods: def value_from_datadict(self, data, files, name): era, imperial_year, month, day = [widget.value_from_datadict(data, files, f'{name}_{i}') for i, widget in enumerate(self.widgets)] try: return date(self._j2w.convert(f'{era}{imperial_year}年'), int(month), int(day)) except ValueError: # selected era/year combination was invalid return '' All I can do in this method is catch any ValueError and return an empty value instead, which means the field's validator complains about missing data, not about an incorrect value. If I simply raise the ValueError or a ValidationError, it's causing an uncaught exception error. Where and how should this kind of validation happen? I'd like the keep the abstraction of the Japanese picker purely inside the UI layer, and keep the backing field a simple Date field. -
django celery not executing tasks.py in digitalocean server
I used Celery in my django project for schedule tasks, it was kinda perfect in local server, I upload this update to my digitalocean server, and after 3 days of searching and fixing issues I couldn't understand that pinch of mistakes I did ! , here is my project structure ├── app │ ├── __init__.py │ ├── admin.py │ ├── urls.py │ ├── models.py │ ├── apps.py │ └── views.py ├── manage.py ├── corsa │ ├── __init__.py │ ├── celery.py │ ├── settings.py │ ├── urls.py │ └── wsgi.py ├── requirements.txt └── templates ├── base.html ├── other tasks.py : @shared_task def just_testing(): print(' test log ') @shared_task def tasks_to_do_daily(): # some stuff to do daily @shared_task def tasks_to_do_weekly(): # some stuff to do weekly celery.py : os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'corsa.settings') app = Celery('corsa') app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks() app.conf.beat_schedule = { 'add-contrab1': { 'task': 'app.tasks.just_testing', 'schedule': 6.0, }, 'add-contrab2': { 'task': 'app.tasks.tasks_to_do_daily', 'schedule': crontab(minute='26', hour='09'), }, 'add-contrab3': { 'task': 'app.tasks.tasks_to_do_weekly', 'schedule': crontab(minute='00', hour='00', day_of_week='sat,tue'), }, } app.conf.CELERY_TIMEZONE = 'Asia/Hong_Kong' settings.py : CELERY_BROKER_URL = 'amqp://localhost' Ok, now issues part .. For local I tried these commends celery -A corsa worker -l info , celery -A corsa beat -l info , celery worker -A corsa --loglevel=INFO … -
Style guide: how to not ot get int o a mess in a big project
Django==2.2.5 In the examples below two custom filters and two auxiliary functions. It is a fake example, not a real code. Two problems with this code: 1. When a project becomes big I forget what aux functions I have already written. Not to mention team programming. What is the solution here? To organize a separate module for functions that can be imported? And sort them alphabetically? 2. Some functions from here may be reused outside this package, and some may not. Say, the combine function seems to be reusable, while "get_salted_str" is definitely for this module only. I think that it is better to distinguish between functions that may be imported and those that may not. Is it better to use underline symbol to mark unimported functions? Like this: _get_salted_str. This may ease the first problem a bit. 3. Does Django style guide or any other pythonic style guide mention solutions to the two above mentioned problems? def combine(str1, str2): return "{}_{}".format(str1, str2) def get_salted_str(str): SALT = "slkdjghslkdjfghsldfghaaasd" return combine(str, SALT) @register.filter def get_salted_string(str): return combine(str, get_salted_str(str)) @register.filter def get_salted_peppered_string(str): salted_str = get_salted_str(str) PEPPER = "1234128712908369735619346" return "{}_{}".format(PEPPER, salted_str) -
Filter data based on current date + 365 days in Django Rest framework
I am trying to build a web app. Part of the requirement is when the user clicks on a time interval like "1 year", he can view all the upcoming movies in one year. When the user clicks on "1 year" it should trigger a filter which displays movies from today till next year. How is it possible in django ? I want to make a filter similar to this logic - class sales_plot(APIView): def post(self, request, *args, **kwargs): interval = json.loads(request.body).get('interval') queryset = model_name.objects.filter(date_of_relase= current_date + interval) serialize = serializer_name(queryset, many=True) return Response(serialize.data, status=status.HTTP_200_OK) How can I do that ? -
How to deal with standard Error object on frontend?
I have a frontend app with many API requests, but it's a pain to work with error responses. Sometimes I need to go through many objects like: error.response.data.email and sometimes it is error.response.data.address.province[0]. I can't predict all of the errors, and writing manual "parsers" looks like a dirty extra solution to me: const errorsObject = err.response.data let errors = '' Object.keys(errorsObject).map(key => { if (key === 'address') { Object.keys(errorsObject.address).map( key => (errors += `${key} : ${errorsObject.address[key]}\n`) ) } else { errors += `${key} : ${errorsObject[key]}\n` } return undefined }) yield toast.error(errors) Also it still doesn't cover everything. Is there any frontend parsers for that? If not, our backend is Python(Django), maybe there is a package for backend side? Ideally I'd want to see a flat array of objects {title, message}. -
How to setup vue template with django project
I have downloaded vuejs template,I want to setup with django project(my django side is already up and running) I don't want to spend much time reading the structure of vuejs and its components by now. Am wondering is there any easy way to setup like vue CLI or any. Please help me any easy way to integrate!! -
How to save files via django serializers after processing them in my views?
I have a excel/csv file that I read using pandas once the user uploads the file. I process the file in my views.py and save them directly using the command df.to_excel("filename.xlsx") or df.to_csv("filename.csv") Is there a way to save the files through django serializer? I've tried df.to_excel("filename.xlsx") directly on the serializer data as shown on the code, but the file ends up writing to my disk directly instead of being saved via the serializer. data = { 'file': df_template.to_excel(output_file_name, index=False), 'created_for': project.id, } outputrecord_serializer = OutputRecordSerializer(data=data) if outputrecord_serializer.is_valid(): #print('Check if serializer is valid') outputrecord_serializer.save() #print('saved') else: print(outputrecord_serializer.errors) -
KeyError for 'id' field when ModelForm CheckboxSelectMultiple choices are 'id'
I am new to Django. I have a form where I want to have list of 'id's of model items as choices of CheckboxSelectMultiple field. Here is my example Models.py class TryDjango(models.Model): name = models.CharField(max_length=120) Views.py class trydjango_view(View): template_name = 'trydjango.html' failed_template = 'generic_error.html' viewContext = { "title" : "Page title ", "columnNames" : ["Name"], "url" : 'trydjango', 'loginInfo' : 'logout', } def get(self, request): self.viewContext['deleteTryDjangoForm'] = \ deleteTryDjangoForm(prefix='delete') login_result = getLogin(request) self.viewContext.update({'loginInfo' : login_result['loginInfo']}) return render(request, self.template_name, self.viewContext) ModelForms.py class deleteTryDjangoForm(forms.ModelForm): myPrefix ='delete-' class Meta: model = TryDjango fields = ['id'] def __init__(self, *args, **kwargs): super(deleteTryDjangoForm,self).__init__(*args, **kwargs) sportSeriesList = listOfSportSeries() print(sportSeriesList) self.fields['id'].widget = \ forms.CheckboxSelectMultiple(choices=[(1,1)]) #<<-- Line 399 in the error Finally the error I am getting KeyError at /trydjango/ 'id' Request Method: GET Request URL: http://127.0.0.1:8000/trydjango/ Django Version: 2.0.7 Exception Type: KeyError Exception Value: 'id' Exception Location: /Users/sbt/dev/trydjango/src/myPrjApp/modelforms.py in __init__, line 399 Where line 399 is the line "forms.CheckboxSelectMultiple(choices=[(1,1)])" from my form. The form doesn't give this error if I change the field from 'id' to 'name'. I have few other models whose primary keys are not the 'id' fields. I can delete those model items using the corresponding primary keys. However, the form fails only if the … -
is there a way to fix a database isssue on django?
I'm not sure if removed some pycache files and it messed my website up or if me pulling some files from git has changed my folders about but I'm getting database connect issues. I have tried makemigrations, migrate and runserver and I'm getting the same error each time. I can't uninstall wagtail or django as it comes up failed to create process. I'm getting the horrible feeling it might be time to scratch the project and start again. Here is the error self.connection = self.get_new_connection(conn_params) File "..\venv\lib\site-packages\django\db\backends\sqlite3\base.py", line 194, in get_new_connection conn = Database.connect(**conn_params) sqlite3.OperationalError: unable to open database file The above exception was the direct cause of the following exception: Traceback (most recent call last): File "..\threading.py", line 926, in _bootstrap_inner self.run() File "..\threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "..\autoreload.py", line 54, in wrapper fn(*args, **kwargs) File "..\runserver.py", line 120, in inner_run self.check_migrations() File "..\base.py", line 453, in check_migrations executor = MigrationExecutor(connections[DEFAULT_DB_ALIAS]) File "..\executor.py", line 18, in __init__ self.loader = MigrationLoader(self.connection) File "..\loader.py", line 49, in __init__ self.build_graph() File "..\loader.py", line 212, in build_graph self.applied_migrations = recorder.applied_migrations() File "..\recorder.py", line 73, in applied_migrations if self.has_table(): File "..\recorder.py", line 56, in has_table return self.Migration._meta.db_table in self.connection.introspection.table_names(self.connection.cursor()) File "..\base.py", … -
How to store a table to database in Django 2.1?
I use Django 2, that is why I post similar questions and I am a beginner in Django. Question: I have a table inside html, and I need to save it into database using view and model and form. Here are some part of the code: template.html <form method="post" action="/images/save/" enctype="multipart/form-data"> {% csrf_token %} <table class="table" border="1" id="tbl_posts"> <tbody id="tbl_posts_body"> {% for name, age in lines %} {% with i=forloop.counter0 %} {% with i|add:1|stringformat:"s" as i_id %} {% with id="rec-"|add:i_id %} <tr id={{id}}> <td><span class="sn">{{ i|add:1 }}</span>.</td> <td><INPUT type="text" name="txt1" value=""\></td> <td><INPUT type="text" name="txt2" value=""\></td> </tr> {% endwith %} {% endwith %} {% endwith %} {% endfor %} </tbody> </table> <input type="submit" value="Submit"> </form> model.py: class Names(models.Model): name= models.CharField(max_length=255) age= models.IntegerField() view.py: def save_form(request): template = "template.html" context = {'txt1': "Name", 'txt2': 0} if request.method == 'POST': dname= request.POST.get("txt1") dage= request.POST.get("txt2") names1= Names(name=dname, age=dage) names1.save() return render(request, template, context) Question: So, it works perfectly, but the issue is that It saves only the last row. I think there is a way to enter the whole data. I need to enter all data in the table not only the last row. Can someone help me? Update: lines is a zip a … -
Migrations issue in Cpanel postgresql
I have a query regarding Cpanel, Please help me out. I had created python application with using Django Framework and Postgresql as Database and I am facing issue while migrating the Database, Below is the mentioned error please do the needful. Thanks in Advance -
No phone number record in django admin site
Currently on my own django project at the admin site, I can only see username, email , first name, last name and staff status. The UserCreationForm I am using provided by django has a phone number text field that I included to let users key in their phone number, however, I cant seem to get the admin site to store the phone number record. Please tell me if there are any changes that should be made to my current code so that I can see the phone records. Wondering if there is anything that I should be including to my admin.py or forms.py. /* forms.py */ from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm from validate_email import validate_email class UserRegisterForm(UserCreationForm): email = forms.EmailField() phone_number = forms.IntegerField(required=True) class Meta: model = User fields = ['username', 'email'] def clean_email(self): email = self.cleaned_data.get("email") if not validate_email(email, verify=True): raise forms.ValidationError("Invalid email") return email /* views.py */ from django.shortcuts import render, redirect from django.contrib import messages from .forms import UserRegisterForm def register(request): if request.method == 'POST': form = UserRegisterForm(request.POST) if form.is_valid(): user = form.save() phone_number = form.cleaned_data['phone'] # do something with phone number?? username = form.cleaned_data.get('username') messages.success(request, f'Account created for {username}!') … -
Chained form fill in django form
I have a django model Models.py class ReceiveDocket(models.Model): sender_parent_client = models.ForeignKey(Client, on_delete=models.CASCADE, related_name='sender_parent_client') client_location = models.ForeignKey(Client, on_delete=models.CASCADE, related_name='client_location') received_at_warehouse = models.ForeignKey(Warehouse, on_delete=models.CASCADE, related_name='warehouse_list') class Client(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) client_company = models.CharField(max_length=255, default=0) client_name = models.CharField(max_length=255, default=0) client_shipping_address = models.CharField(max_length=255, default=0) and a form of receive docket: Views.py @method_decorator([login_required, employee_required], name='dispatch') class ReceiveDocketFormView(CreateView): model = ReceiveDocket fields = "__all__" template_name = 'packsapp/employee/docketRecievedForm.html' def form_valid(self, form): product = form.save(commit=False) product.save() messages.success(self.request, 'The Docket was created with success!') return redirect('employee:docket_table') How can I change my views such that when I select the sender parent client it automatically fills the client address in client location or at least show the client address in the drop-down ?