Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Understanding Django (Python) and databases
new to Django and hope someone can help me understand. I see how in Django you can set up models that become tables in say PostgreSQL. Great. What approach should I use where the schema and tables already exist in a database? I don't want to change the tables in anyway but use the data in views. I would normally think 'make an SQL statement to return the data I want and join tables where needed'. Lets say the tables are Orders and Customers and I would use an SQL: SELECT Orders.OrderID, Customers.CustomerName, Orders.OrderDate FROM Orders INNER JOIN Customers ON Orders.CustomerID=Customers.CustomerID; What is the approach for: the abstraction in django for this SQL any best practices makemigrations / migrate so I don't interfere with the source tables but keep my models up to date in the DB join to a table that is a django model? Much appreciated! -
Upload multiple files Django
models.py file_1 = models.FileField(blank=True, upload_to='PN_files/%Y/%m/%d/', verbose_name="File 1", validators=[validate_file_size], help_text="Allowed size is 50MB") views.py class PostCreateView(LoginRequiredMixin, CreateView): model = Post fields = ['title', 'file_1'] def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) HTML code: <form method="POST" enctype="multipart/form-data"> {% csrf_token %} <fieldset class="form-group"> <legend class="border-bottom mb-4">Fill the form</legend> {{ form|crispy }} </fieldset> <div class="form-group"> <button class="btn btn-outline-info" type="submit">Submit</button> </div> </form> I use this code to upload a file in my form. Now I need to upload multiple files, but when I follow the examples on Django Uploading multiple files, I can't get it to works. My views.py now looks like (and none of 3 examples work for me): class PostCreateView(LoginRequiredMixin, CreateView): model = Post fields = ['title', 'file_1'] def form_valid(self, form): form.instance.author = self.request.user widgets = {'file_1': form.ClearableFileInput(attrs={'multiple': True})} form.instance.file_1 = form.FileField(widget=form.ClearableFileInput(attrs={'multiple':True})) form.instance.file_1 = form.FileField(widget=form.FileInput(attrs={'multiple': True})) return super().form_valid(form) -
get dictionary value sent from Django in Vuejs row
I have used Django to develop a web app. The front end is vuejs. I want to render the dictionary in vuejs table. I have tried to access the dictionary using the dictionary name in vue, but failed to get the vaule. view.py: def Browse_and_adopt(request): query_results_book = Title.objects.values() return render(request, 'main.html', { "query_results_book": query_results_book }) HTML: <div id="app"> &emsp;&nbsp;Search: <input type="text" placeholder="By title, iSBN, VBID, publisher, Author, course code" v-model="filter" size="45"/> <br> <table> <thead> <tr> <th>Course Material Title</th> <th>Author/Editor</th> <th>Edition</th> <th>Publisher</th> <th>iSBN</th> <th>e-iSBN/VBID</th> <th>Category</th> <th>Material Format</th> <th>Distribution Mode</th> <th>Course Codes using title</th> <th>Adopt: Course Code</th> <th>Adopt: Starting Semester</th> </tr> </thead> <tbody data="{{ json_data }}"> <tr v-for="(row, index) in filteredRows" :key="`iSBN-${index}`"> <td>{{ row.title }}</td> <td>{{ row.author }}</td> </tr> </tbody> </table> </div> <script> const app = new Vue({ el: '#app', data: { filter:'', rows: [ { title: query_results_book.title, author: query_results_book.author } ] }, query_results_book: { type: Object, required: true, }, }); In this line: title: query_results_book.title, I get error: query_results_book not defined. How to pass my dictionary to row in vue? -
how to change two dates to number of days and hours jango
i'm trying to change two dates check_in and check_out to days and hours my models.py check_in = models.DateTimeField(default=datetime.now) check_out = models.DateTimeField() i tried this check_in_date = obj.check_in check_out_date = obj.check_out days = check_in_date - check_out_date day = days.days hour = days.seconds / 60 for the day it works as i expect except that when i select this two dates check_in=05-07-2021 04:46 PM to check_out=05-07-2021 10:46 PM i want to show 0 days 6 hours but it show 1 days 1080.0 hours ! is it possible to return such date format -
Django Paypal: 'VALIDATION_ERROR' 'MALFORMED_REQUEST_JSON'
I am trying to verify my webhooks but i am getting a key error: verification_status. This is because the response of the api call is giving an error instead of the json dump i should be getting. The error from the response is {'name': 'VALIDATION_ERROR', 'message': 'Invalid request - see details', 'debug_id': 'd303f5f9323d6', 'details': [{'field': '/webhook_event', 'location': 'body', 'issue': 'MALFORMED_REQUEST_JSON'}], 'links': []} which shows that the error is in the webhook event i think. What do i have to change to fix this? headers = { "Content-Type": "application/json", "Authorization": bearer_token, } print(request.body) print('') data = { "auth_algo": request.headers["PAYPAL-AUTH-ALGO"], "transmission_id": request.headers["PAYPAL-TRANSMISSION-ID"], "transmission_sig": request.headers["PAYPAL-TRANSMISSION-SIG"], "transmission_time": request.headers["PAYPAL-TRANSMISSION-TIME"], "webhook_id": id_is_here, "webhook_event": request.body, "cert_url": request.headers["PAYPAL-CERT-URL"], } data["webhook_event"] = data["webhook_event"].decode("utf-8") print(data["webhook_event"]) response = requests.post('https://api-m.sandbox.paypal.com/v1/notifications/verify-webhook-signature', headers=headers, json=data).json() print('worked') print(response) if response["verification_status"] == "SUCCESS": print('success') if [i["event_type"] for i in request.body] == "BILLING.SUBSCRIPTION.CREATED": print('sub created') elif [i["event_type"] for i in request.body] == "BILLING.SUBSCRIPTION.CANCELLED": print('sub cancelled') -
How to make the user able to filter on certain field in a model (Django)
Say I have a model of cars #models.py class Car(models.Model): user = models.ForeingKey(settings.AUTH_USER_MODEL, on_delete = models.CASCADE) n_doors = models.IntegerField(default=5) name = models.CharField(max_length=16) and a user has created 6 Car, where 3 have 5 doors, 2 have 4 doors and 1 have 1 door. Is there a way I can let the user filter on, say, n_doors either by a choice-list of available numbers ([5,4,1]), or by letting the user write numbers theirself? -
Django Values + Annotate Avg() doesn't group properly
I am stuck into this obviously basic issue, it feels I am missing something obvious to make this work properly. My db model is: class Review(models.Model): SCORE_CHOICES = [(1, '1'), (2, '2'), (3, '3'), (4, '4'), (5, '5')] user = models.ForeignKey(get_user_model(), related_name="reviews_by_user", on_delete=models.CASCADE) recipe = models.ForeignKey(Recipe, related_name="reviews_by_recipe", on_delete=models.CASCADE) score = models.IntegerField(choices=SCORE_CHOICES) date_created = models.DateTimeField(default=timezone.now) def __str__(self): return f"{self.user} rated {self.recipe} with {self.score}" class Meta: ordering = ['-date_created'] I am trying to group by recipe counting avg review score. This approach feels to work fine but it doesn't: Review.objects.values('recipe').annotate(Avg('score')) as result i get: <QuerySet [{'recipe': 1, 'score__avg': 5.0}, {'recipe': 1, 'score__avg': 5.0}, {'recipe': 2, 'score__avg': 4.0}, {'recipe': 2, 'score__avg': 3.0}, {'recipe': 5, 'score__avg': 3.0}, {'recipe': 5, 'score__avg': 2.0}]> Which is absolutely weird for me. I've gone through the Django Aggregation documentation but can't find any restrictions or special clauses that could help to understand what I am missing. Please let me know if someone has an idea of what's going on. -
Django Crispy Forms does not use specified template pack
I have a Django project where I use django-crispy-forms to style my forms. (I use {{ form|crispy }} in my template file to insert the template) Works perfectly fine. Now I upgraded from Bootstrap 4 to Bootstrap 5 and wanted to update my forms accordingly. I pip installed crispy-bootstrap5 (package recommended on django-crispy-forms GitHub) and added "crispy_bootstrap5" to INSTALLED_APPS as well as added CRISPY_ALLOWED_TEMPLATE_PACKS = "bootstrap5" and CRISPY_TEMPLATE_PACK = "bootstrap5" to my settings.py file. All according to crispy-bootstrap5's GitHub Page. But nothing changed. It still renders the same html as before. Maybe you can help me with getting that to work. Thank you. -
how do you identify a user every time they load up the page in React, Django rest framework web app
So usually in regular Django you can identify a user doing request.user but in django rest framework and in a completely separated frontend and backend how do you identify a user when a frontend makes a request to the backend? So lets just say I'm using react and I have an access JWT token in my localStorage and and the user object in my state. Should I just make a useEffect hook and call fetch and make a POST request in it before the component loads? and if I did, should I fetch out the user object or the access token? Or maybe there's other way of doing this? -
How to create a nice post form like the ones in forum or in stack overflow?
I am currently building a forum app in my website from scratch with django. I am quite happy with the result so far however I want to improve it. So far, when users want to post a message they need to fill a simple text form : my app Because it's only a simple text field, users can not use emojis, images or add links and the layout looks terrible. It does not look pro and any other forum would embbed a richer message form. How can I make it look like the one from stack overflow ? : my goal Thanks in advance. -
Getting a specific field (e.g. name) instead of pk in object_list for rendering
I have an app for example: class example(models.Model, TemplateHelperClass): reviewer = CharField(max_length=255, verbose_name="Title") book = ForeignKey(books, on_delete=models.PROTECT) review = TextField() ... class books(models.Model, TemplateHelperClass): author = CharField(max_length=255, verbose_name="Author") book_title = CharField(max_length=255, verbose_name="Title") publisher = CharField(max_length=255, verbose_name="Author") def __str__(self): return self.book_title ... class templateHelperClass(): paginate_by = 15 def get_fields(self): return [(field, field.value_to_string(self)) for field in self._meta.fields] *views.py* class bookReviewList(ListView): model = example template_name = "bookreviews.html" ... *bookreviews.html* {% extends "base.html" %} {% block content %} <table class="table"> <thead> <tr> {% for fld, val in object_list.0.get_fields %} <th>{{ fld.verbose_name |title }}</th> {% endfor %} <th></th> </tr> </thead> <tbody> {% for object in object_list %} <tr> {% for fl1, val1 in object.get_fields %} <td>{{val1}}</td> {% endfor %} <td><a class="btn btn-dark" href='{{ object.get_absolute_url }}'>Update</a></td> </tr> {% endfor %} </tbody> </table> {% endblock %} The output html displays the pk for the book, and not the book title (the __str__ method) in this case. I'd like to display the __str__ method. Two questions, both related: (1) Is there a more elegant way to represent the form with my attributes in table format. (I'm using bootstrap for some of the formatting) (2) If not, how do I get the foreignkey field to display the __str__ return … -
Django + django-oauth-toolkit: How to Register OpenIdConnect Endpoints?
How can I access OpenId Connect endpoints in a django + oauth environment? I'm trying to set up a Django (3.2.5) env with OAuth v2 + OpenId Connect using django-oauth-toolkit (1.5.0). I was able to follow the tutorials, which means that I have oauth support. I'm able to get Oauth tokens, and protect endpoints with them. But when I try to configure OpenId Connect, I'm unable to access o/.well-known/... end-points, they simply are not registered. I get a HTTP 404, and the debug page shows that django only knows about o/authorize/, o/token/, and o/revoke-token/. OpendId Connect section seems to imply I don't need to do anything else but enable OpenId for those views to appear. My urls.py looks like: oauth2_endpoint_views = [ path('authorize/', oauth2_views.AuthorizationView.as_view(), name="authorize"), path('token/', oauth2_views.TokenView.as_view(), name="token"), path('revoke-token/', oauth2_views.RevokeTokenView.as_view(), name="revoke-token"), ] urlpatterns = [ path('admin/', admin.site.urls), re_path('^accounts/', admin.site.urls), path('o/', include((oauth2_endpoint_views, 'oauth2_provider'), namespace="oauth2_provider")), path('api/hello', ApiEndpoint.as_view()), # an example protected resource endpoint path('api/secret', secret_page, name='secret'), # requires authentication ] As a part of OAuth config I already Added oauth2_provider to settings.INSTALLED_APPS. Added oauth2_provider.middleware.OAuth2TokenMiddleware to settings.MIDDLEWARE. Added django.contrib.auth.backends.ModelBackend, oauth2_provider.backends.OAuth2Backend, django.contrib.auth.backends.ModelBackend to settings.AUTHENTICATION_BACKENDS. Since this is a testing env, CORS_ORIGIN_ALLOW_ALL is set to True. Added path('o/', include((oauth2_endpoint_views, 'oauth2_provider'), namespace="oauth2_provider")) to `urls. Registered a … -
Django Many-To-One IntegrityError
I am new to Python and Django. I created database due to documents. I tested it and there has been error to many-to-one relationship between two models. It looks weird to me because It works like one to one relationship between those classes but it gives error if I try to add many. There are other classes with same relationship as many-to-one. I created same way and they work just fine. I am using sqlite by the way. class unites (models.Model): id = models.IntegerField(primary_key=True) unitename = models.CharField(max_length=128) class intensivecare_forms (models.Model): id = models.IntegerField(primary_key=True) hospitals_id = models.ForeignKey(hospitals, on_delete=models.CASCADE) formname = models.CharField(max_length=128) data = models.JSONField() unites_id = models.ForeignKey(unites, on_delete=models.CASCADE) It gives this error if I try to add second form into unites. IntegrityError at /admin/LocalManager/intensivecare_forms/add/ UNIQUE constraint failed: LocalManager_intensivecare_forms.unites_id_id Request Method: POST Request URL: http://localhost:8000/admin/LocalManager/intensivecare_forms/add/ Django Version: 3.2.4 Exception Type: IntegrityError Exception Value: UNIQUE constraint failed: LocalManager_intensivecare_forms.unites_id_id Exception Location: /Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/django/db/backends/sqlite3/base.py, line 423, in execute Python Executable: /Library/Frameworks/Python.framework/Versions/3.9/bin/python3 Python Version: 3.9.6 -
Simple Django blog using JSON files?
I am seeking AdSense approval and my site, even though it contains content, is apparently insufficient for AdSense approval. So I want to add a lightweight blog to the site. However, I don't want to create additional data models, etc. and would prefer to just edit a JSON file that is parsed for blog content. And following that, just include a "blog.html" template on various pages which will load the content. Is there any JSON-fed blog module for Django? I feel like this wouldn't be too hard to create, but I don't want to reinvent the wheel. Thanks! -
Handling request in django view: accessing the body
I' trying a modify my database on a condition based on a body object from the request. here is my fetch function: document.addEventListener('change', function(e) { event.preventDefault(); const magazinOption = e.target.value; const mag_url = "{% url 'my-subscriptions' %}"; if (magazinOption === 'digital') { fetch(mag_url, { method: "POST", headers: { "X-CSRFToken": Cookies.get('csrftoken'), "Accept": "application/json", "Content-Type": "application/json" }, body: JSON.stringify({ 'magazine': 'digital' }) }) .then(response => { return response.json(); }) .then(data => { console.log('Choix de magazin:', paper_magazine ); }); } }); Then in my view file i have this. def post(self, request): ... request_body = json.loads(request.body.decode('utf-8')) print(request_body) print('body:', request_body['magazine']) print('body to string:', str(request_body['magazine'])) if str(request_body['magazine']) == 'digital': user.paper_magazine = False user.save() And in my terminal this is what i see: 04/Jul/2021 08:08:18] "GET /static/src/images/earth.svg HTTP/1.1" 200 3503 {'magazine': 'digital'} body: digital body to string: digital Internal Server Error: /client-profile-new/subscriptions/ Traceback (most recent call last): File "/Users/marcusbey/.pyenv/versions/jaenv36/lib/python3.6/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/Users/marcusbey/.pyenv/versions/jaenv36/lib/python3.6/site-packages/django/core/handlers/base.py", line 126, in _get_response "returned None instead." % (callback.__module__, view_name) ValueError: The view apps.front.views.profile.NewProfileSubscriptionsView didn't return an HttpResponse object. It returned None instead. [04/Jul/2021 08:08:25] "POST /client-profile-new/subscriptions/ HTTP/1.1" 500 73892 What am i missing ? Why can't i access the body object's value? -
how to notify the user about the incoming message to the receiver in flutter chat app?
So, I need a chat feature implementation to my flutter app. Since on research many tutorials uses Firebase Firestore as their database. I use my own Django server to have my logic. So, If I'm going to use Django I can implement websockets to connect a user to database and update the changes in real time. The chat is going to be like a one to one connection. So, I have some question First of all, in all those firebase application uses a single documentID to make changes to firebase which will be like room is it a good practice to do so for professional? How can I notify the receiver about the sender message when receiver app is not open state(cleared the app from cache)? What will be the best database design for this application(I have mentioned mine below)? If all the above satisfies, How can I reinitiate the chat sequence of that one to one chat? -
Nuxt Auth Token & refresh token not set
I took the following example from the Nuxt Auth documentation: auth: { strategies: { local: { scheme: 'refresh', token: { property: 'access', maxAge: 1800, global: true, type: 'Bearer' }, refreshToken: { property: 'refresh', data: 'refresh', maxAge: 60 * 60 * 24 * 30 }, endpoints: { login: {url: '/token', method: 'post'}, refresh: { url: '/token/refresh', method: 'post'}, user: false } } } } And I got the following response from my API (Django): { "refresh": "y", "access": "x" } At last, I have the exact same login 'page' as show in the documentation of Nuxt Auth but when I run this neither the refresh or access token is set into the local storage. Upon changing login: {url: '/token', method: 'post'} to login: {url: '/token', method: 'post', propertyName: 'access'} the access token is set properly but doing similar for the refresh token doesn't work. How can I get Nuxt Auth to set both my refresh and access token properly? -
Django Multiple filter with range look-up
my model: class Attendance(models.Model): date = models.DateField() subject = models.ForeignKey(Subject, on_delete=models.CASCADE) student = models.ForeignKey(Student, on_delete=models.CASCADE) attendance = models.BooleanField() the query i am trying att = Attendance.objects.filter(date__range=(st_date,ls_date)).filter(student__range=(1,10)) it is giving me an error : File "C:\Users\user1\Desktop\backend\environment\lib\site-packages\django\db\models\sql\query.py", line 1184, in build_lookup raise FieldError('Related Field got invalid lookup: {}'.format(lookup_name)) django.core.exceptions.FieldError: Related Field got invalid lookup: range -
how to filter django model object if contains in python django
i am trying to filter out a model which contain sender,receiver,user, the problem is when i try to use return Private_messages.objects.filter(sender__contains=sender,receiver__contains=receiver,user=user) it is strict in checking and will only return if condition are met... model example id:1 sender:"dan" reciever:"harry" id:2 sender:"harry" reciever:"dan" id:3 sender:"dan" reciever:"harry" in this sometimes sender is dan sometimes not. with Private_messages.objects.filter(sender="dan",receiver="dan") i want to get all object with the who has sender dan and receiver dan not both dan how can i get something like this in python django? -
Auto-populating a Django model field using JavaScript fails consistently
I have a model named Package. It has fields named, diagnosis, treatment, patient_type, max_fractions and total_package. The fields diagnosis, treatment and patient_type have foreign keys defined in separate individual classes, making diagnosis, treatment and patient_type choice fields. Now what I want is to auto-populate the max_fractions and total_package fields whenever treatment and patient_type's values are selected. I was suggested to use JavaScript to accomplish that. I tried and wrote the codes but to no avail. I'm trying it on max_fractions field first, when I succeed in doing that, I will do it for all the needed fields. Can anyone help me on this, it will be much appreciated. Here are my models: class Diagnosis(models.Model): diagnosis=models.CharField(max_length=30, blank=True) def __str__(self): return self.diagnosis class Treatment(models.Model): treatment=models.CharField(max_length=15, blank=True) def __str__(self): return self.treatment class PatientType(models.Model): patient_type=models.CharField(max_length=15, blank=True) def __str__(self): return self.patient_type class Package(models.Model): rt_number=ForeignKey(Patient, on_delete=CASCADE) diagnosis=models.ForeignKey(Diagnosis, on_delete=CASCADE) treatment=ForeignKey(Treatment, on_delete=CASCADE) patient_type=ForeignKey(PatientType, on_delete=CASCADE) max_fractions=models.IntegerField(default=None) total_package=models.DecimalField(max_digits=10, decimal_places=2) forms.py: class DiagnosisForm(ModelForm): class Meta: model=Diagnosis fields='__all__' class TreatmentForm(ModelForm): class Meta: model=Treatment fields='__all__' class PatientTypeForm(ModelForm): class Meta: model=PatientType fields='__all__' class PackageForm(ModelForm): class Meta: model=Package fields='__all__' widgets={ "max_fractions" : forms.NumberInput(attrs={"onfocus":"mf();"}), } views.py: def package_view(request): if request.method=='POST': fm_package=PackageForm(request.POST, prefix='package_form') fm_diagnosis=DiagnosisForm(request.POST, prefix='diagnosis_form') fm_treatment=TreatmentForm(request.POST, prefix='treatment_form') fm_patient_type=PatientTypeForm(request.POST, prefix='patien_type_form') if fm_package.is_valid() and fm_diagnosis.is_valid() and fm_treatment.is_valid() and fm_patient_type.is_valid(): … -
Automatically change price when I change inventory in Django?
I am creating an invoice form. I would like to have a function where if I change the inventory (dropdown search), the corresponding price will also change. You can see an illustration of what I want here: https://www.dropbox.com/s/4kpyfve3gzxmcls/dj006_ultimate_goal_for_adding_variable_attr.jpg?dl=0 What I know so far is I can I can query the inventory dropdown search through: inventory = Inventory.objects.get(pk=request.POST['inventory_dropdown_id']) price = inventory.price But how do I propogate such "get" function throughout all the forms (since I'm using query set) how do I set the price (in the view.py) back to the html file when the html file is already rendered? Is there away around this? P.S. Probably been asked before here but I couldn't find any reference. (Hard to find what proper keyword to search) So if you want to post a link. I'd be happy to take a look at it. -
Celery Beat how to calculate difference between datetime.now() and the next scheduled Periodic Task django
I have a celery beat cron schedule set for day 3 of every week. In django shell I can access this schedule: >>> schedule = PeriodicTask.objects.get(name="Bulk Newsletter Send") which results in: >>> <PeriodicTask: Bulk Newsletter Send: * * * * 3 (m/h/dM/MY/d) UTC> My question is, how can I calculate the time difference in days between datetime.now() and the next PeriodicTask? -
When I can call myself a Django developer and be able to apply for a job?
I learnt a Python and Django, by using these I build a web-app but it is not live/online. I have neither certificate and nor IT degree. Now, I wanna actually want to know which things make me a Django/Python web-developer or I am not a web-developer? -
Cannot resolve keyword 'username' into field. Choices are: address, age, city, country, gender, name, phone, pt_id, user, user_id
Please help me, I am stuck at this error. I am new to django, I don't know how to solve this errorstrong text patients/views.py @method_decorator([login_required, patient_required], name='dispatch') class EditPatient(UpdateView): model = Patient_Profile fields = ['pt_id', 'name', 'gender', 'age', 'phone', 'address', 'city', 'country'] template_name = 'patient/patient_edit.html' slug_field = 'username' slug_url_kwarg = 'slug' success_url = reverse_lazy('patients:patient_page') def get_context_data(self, *args, **kwargs): context = super(EditPatient, self).get_context_data(*args, **kwargs) return context patients/models.py class Patient_Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) pt_id = models.CharField(max_length=50) name = models.CharField(max_length=100) gender = models.CharField(max_length=15) age = models.CharField(max_length=10) phone = models.CharField(max_length=20) address = models.TextField() city = models.CharField(max_length=100) country = models.CharField(max_length=100) def __str__(self): return self.user.username patients/urls.py app_name = 'patients' urlpatterns = [ path('', views.patient_page, name='patient_home'), path('profile/<slug>', views.EditPatient.as_view(), name='profile'), ] template <h1>I am {{user.username}} </h1> <a href="{% url 'patients:profile' slug=user.slug %}">Edit Patient</a> {%endblock%} -
Try Uploading multiple image but form was not submitting
I was trying to add multiple images in django. I had shared my code below. every time i click on submit(Add Farm) it will remain on same page. it is not calling post method. models.py class Farm(models.Model): user=models.ForeignKey(FarmUser,related_name="farm_owner",on_delete=models.CASCADE) farmname=models.CharField(max_length=50) SizeOfFarm=models.IntegerField() address=models.TextField(default='') area=models.CharField(default='',max_length=20) city=models.CharField(default='',max_length=20) pincode=models.IntegerField() class FarmImage(models.Model): farm = models.ForeignKey(Farm, related_name="farm_image", on_delete=models.CASCADE) images = models.FileField(upload_to='farm/') forms.py class FarmFormFileds(forms.ModelForm): class Meta(): model = Farm fields=('user','farmname','SizeOfFarm','address','area','city','pincode') class FarmForm(FarmFormFileds): images=forms.FileField(widget=forms.ClearableFileInput(attrs={'multiple': True})) class Meta(FarmFormFileds.Meta): fields = FarmFormFileds.Meta.fields + ('images',) views.py class NewFarm(CreateView): form_class=FarmForm template_name='farmuser/addfarm_form.html' success_url=reverse_lazy('dashboard') def post(self, request, *args, **kwargs): form_class = self.get_form_class() form = self.get_form(form_class) files = request.FILES.getlist('images') if form.is_valid(): return self.form_valid(form) else: return self.form_invalid(form) I just want to upload multiple files. In above code some functionalities are missing but the problem is that the method is not calling