Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
changing celery task codebase (autoreload) without killing celery workers
I run a django based web app with celery for background tasks. I'm looking at the issue of deploying new code (or updating virtualenv pip libraries). The way I see now to deploy new code is to kill celery and start it again. This could lead to killing workers in the middle of a task, leaving the system in an inconsistent state. Ideally, I would like to be able to deploy new code, let the current workers finish their tasks gracefully and let the new tasks run from the new code. Seems to me like a very sensible requirement :) how can I do this? Does the warm shutdown in celery have something to do with this? I'm killing celery process with killall -9 celery -
if i have two models, model A and model B and i want the average of field of model A to be the value of a field in Model B
I have two models: class Order(models.Model): truck = models.ForeignKey(Truck, on_delete=models.CASCADE, related_name='relation_truck',default=None) date= models.DateField() product=models.CharField(max_length=30) depot = models.CharField(max_length=10) volume = models.CharField(max_length=30, blank=True) volume_delivered = models.CharField(max_length=30, blank=True) order_status = models.CharField(max_length=50, blank=True) pub_date = models.DateTimeField(auto_now_add=True, blank=True) and anothe model: class LoadingDashboard(models.Model): order = models.ForeignKey(Order, on_delete=models.CASCADE, related_name='relation_loading',default=None,blank=True) product = models.CharField(max_length=3) loading_average = models.IntegerField(null=True) expect_quantity = models.IntegerField() loaded_quantity = models.IntegerField() remaining_quantity = models.IntegerField(null=True) total_trucks = models.IntegerField(null=True) loaded_trucks=models.IntegerField() remaining_trucks = models.IntegerField(null=True) i want to do some mathematical operations which is as follows: the product in Model Loaded are only two: PMS And AGO the product in Model Order is also PMS and Ago trucks who are loaded with PMS in Model Order have specific volume which is 35000 and the volume_delivered should be a little bit short than 35000 for example 34294 trucks who are loaded with AGO have their specific volume which is 33000 and the volume_delivered can be for example 32294 i want the Field loading_average in Model Loaded to be the average of field volume_delivered with specified product be it AGO or PMS since they have different volume_delivered values divided by 1000 the expect_quantity in Model Loaded is given meaning i will decide the value loaded_quantity in Model Loaded should be the sum … -
Allowing options in ManyToMany to be selected by one object at a time
I have a model defined as follows: class Group(models.Model): name = models.CharField(max_length=30) countries = models.ManyToManyField(Country) I need to prevent countries from being assigned to multiple groups via the Django Admin. How can I achieve that? -
How to apply authentication scheme to the auth_user table itself
I am new to python and exploring django rest framework. I have created an api for users and is now trying to apply auth scheme on users table itself. What I want to achieve i my ModelViewSet is that: get should display only details of logged in user post should create a user update should update only logged in user I am not able to figure out how to achieve that in django-rest-framework. My code is as below. from rest_framework import viewsets from django.contrib.auth.models import User from atest.serializers import UserSerializer from rest_framework import permissions from atest.permissions import IsOwnerOrReadOnly from rest_framework.decorators import action class UserViewSet(viewsets.ModelViewSet): """ This viewset automatically provides `list` and `detail` actions. """ queryset = User.objects.all() serializer_class = UserSerializer What do I need to change so that I am able to see the login icon in the View of API on top right in below page and perform the required operations. Image In simple words, I want to have permissions on users api itself. IsOwnerOrReadOnly. But, how to I apply login for Users? -
Update Multiple objects using 'PUT' request in Django ViewSet
Here is the view class in views.py. url : 127.0.0.1/users/family class FamilyView(CreateModelMixin,UpdateModelMixin): queryset = FamilyProfile.objects.all() serializer_class = FamilyProfileSerializer def create(self, request, *args, **kwargs): # some logic def update(self, request, pk=None): # some logic I want to update multiple family objects at once. When I hit the above url with put request containing a list of objects. It gives the error that PUT method is not allowed here. I suppose this is the default Django behaviour. The update works while updating single object using url 127.0.0.1/users/family/some_id. Is there a way to bypass this behaviour where the PUT method is not allowed in the url 127.0.0.1/users/family/. If I the use the url 127.0.0.1/users/family/some_id, this would not be right as this will be for single family object whereas I want to update the family in one go. I know I can achieve my goal with some logic using POST method. Is there an efficient inbuilt solution to this problem. I am ok if I am able to bypass the 'PUT Method not allowed' issue -
Sending Multiple Dictionary Variables as one in Template
I have a dataset in multiple dictionary variables that I want to pass as Template servera = {'svr': ServerA, 'tc': 10, 'bs': 100, 'bf': 0, 'te': 0, 'per': '0.00'} serverb = {'svr': ServerB: 'tc': 20, 'bs': 20, 'bf': 0, 'te': 0, 'per': '0.00'} . .. . and so on around 14 like this I want to pass them to template as below def function(request) #process data using code return render(request,'output.html'{servera:servera,serverb:serverb,serverc:serverc,.......} While this works, this increases efforts when adding a dictionary variable, need to add it to the return statement. How can I achieve below somevariable = <all dictionary variabled clubbed> def function(request) #process data using code return render(request,'output.html'{somevariabe:somevariable} and then how will I access that in the Templates Something like {% for name in somevariable.list.all %} {% for servername in name.list.all %} {{ servername.tc }} {% endfor %} {% endfor %} Any Help will be appreciated -
Django select vaule from radio button in view
i have a form where a user can select a specific currency and a vaule of that selected currency to send it to another user. Now i don't understand how to check for the sending users selected currency option vaule to send. Or in other words, "does the sending user has enought funds on his account for that selected currency to send a payment"? Beside that, how to properly create radio buttons? In my case i want to display USD, EUR and RUB as a radiobutton to select the currency. e.g.: def send_payment(request, pk=None): if pk: user = get_user_model().objects.get(pk=pk) if request.method == 'POST': form = Send_Payment_Form(request.POST) #fantasy code start if form.currency_selection < user.acc_balance.selected_currency: messages.add_message(request, messages.ERROR, "Not enought funds on your account") else: .... send_payment blablabla #fantasy code end forms.py class Send_Payment_Form (forms.ModelForm): class Meta: model = User vaule = forms.IntegerField() fields = ['acc_usd_balance', 'acc_eur_balance', 'acc_rub_balance'] CHOICES = (('acc_usd_balance', 'USD',), ('acc_eur_balance', 'EUR',), ('acc_rub_balance', 'RUB',)) choice_field = forms.ChoiceField(widget=forms.RadioSelect, choices=CHOICES) def __init__(self, *args, **kwargs): super(Send_Payment_Form, self).__init__(*args, **kwargs) self.fields['vaule'].widget.attrs.update({'class': 'class-one-input-fields fieldbreak'}) -
Modifying ModelViewSet's queryset for many2many relation query based on django-guardian permissions
I got 2 models which are connected as ManyToMany as you can see below. The thing i'm trying to achive is; serve people to users only when a user has a at least view right on the list that person belongs. Here is my simplified models; class List(TimeStampedModel, UserAwareModel): """Model definition for List.""" name = models.CharField(_('list name'), max_length=50) ... class Person(TimeStampedModel, UserAwareModel): """Model definition for Person.""" member = models.ManyToManyField(List, blank=True) ... Here is my my views; class ListViewSet(viewsets.ModelViewSet): """ API endpoint that allows Lists to be viewed or edited. """ queryset = List.objects.all() serializer_class = ListSerializer permission_classes = (CustomObjectPermissions, DjangoModelPermissions) filter_backends = (filters.DjangoObjectPermissionsFilter,) def perform_create(self, serializer): serializer.save(owner=self.request.user) class PersonViewSet(viewsets.ModelViewSet): """ API endpoint that allows People to be viewed or edited. """ # queryset = Person.objects.all().order_by('-created') serializer_class = PersonSerializer permission_classes = (DjangoModelPermissions, ) def perform_create(self, serializer): serializer.save(owner=self.request.user) def get_queryset(self): user = self.request.user allowed_lists = get_objects_for_user(user, ('view_list'), klass=List) queryset = set() for lst in allowed_lists: queryset.add(Person.objects.filter(member=lst)) return queryset I've tried to override get_queryset method as you can see but I couldn't managed that properly. With this code I'm getting this error; django_1 | Traceback (most recent call last): django_1 | File "manage.py", line 20, in <module> django_1 | main() django_1 | File … -
Foreign Key problem with django csv import-export package
I'm trying to import three datasets for three data models that are interconnected and I cannot seem to properly add in the foreign key. When I try to use the fields.Feild() function to create the foreign key, I get the nameerror in this line: hid = fields.Field(column_name='hid',attribute='hid',..). Please help, I've been trying to upload my datasets for a week. I originally tried to do it manually, but was unable, so now I'm using this package django-import-export. NameError: name 'fields' is not defined Here is my models.py class Service(models.Model): """Model representing an author.""" serviceid = models.UUIDField(default=uuid.uuid4, help_text='Unique ID for this particular service in database') desc_us = models.TextField(blank=True, primary_key = True) cpt = models.IntegerField(default= 10000) price = models.DecimalField(max_digits=6, decimal_places=2, blank=True, null=True) _str__(self): """String for representing the Model object.""" return self.desc_us # Create your models here. class Library(models.Model): """Model representing Librarys.""" hid = models.CharField(max_length = 8, null=True) name = models.CharField(max_length=200, primary_key=True) hopid = models.UUIDField(default=uuid.uuid4, help_text='Unique ID for this particular library in database') address = models.CharField(max_length = 200, null = True) city = models.CharField(max_length = 50, null = True) state = models.CharField(max_length = 2, null=True) zipcode = models.CharField(max_length = 5, null=True) phone = models.CharField(max_length = 12, null=True) updateDate = models.DateField(blank=True, null=True) class Meta: ordering … -
Why I cannot pass positional argument in Django rest-framework unittest
I have implemented a test method which is like below: request = self.factory.get(reverse('users:user-details', kwargs={'user_id': 'd6cb0d1850241a04caaae516f27762d0c0cbc716'})) response = UserDetailsAPIView.as_view()(request) The URL path is as below: url( r'users/(?P<user_id>\w+)/details/?$', UserDetailsAPIView.as_view(), name='reservation-details' ) And it's API view is as below: class UserDetailsAPIView(APIView): http_method_names = ['get'] def get(self, request, user_id, *args, **kwargs): Why I get the below error: Traceback (most recent call last): File "/home/.local/lib/python3.5/site-packages/mock/mock.py", line 1305, in patched return func(*args, **keywargs) File "/vagrant/apps/props/reservations/tests/test_views.py", line 95, in test_get_user_detail_by_user_id response = UserDetailsAPIView.as_view()(request) File "/home/.local/lib/python3.5/site-packages/django/views/decorators/csrf.py", line 58, in wrapped_view return view_func(*args, **kwargs) File "/home/.local/lib/python3.5/site-packages/django/views/generic/base.py", line 68, in view return self.dispatch(request, *args, **kwargs) File "/home/.local/lib/python3.5/site-packages/rest_framework/views.py", line 495, in dispatch response = self.handle_exception(exc) File "/home/.local/lib/python3.5/site-packages/rest_framework/views.py", line 455, in handle_exception self.raise_uncaught_exception(exc) File "/home/.local/lib/python3.5/site-packages/rest_framework/views.py", line 492, in dispatch response = handler(request, *args, **kwargs) TypeError: get() missing 1 required positional argument: 'user_id' -
how return parent products , RecursiveField in rest api?
I don't have return parent in products rest api django. when i request sub-categories in url show parent recursive ,but when i request products in url parent field is empty. please help me, thanks. serializers.py : i have used RecursiveField. from rest_framework import serializers from products.models import Product, SubCategory from rest_framework_recursive.fields import RecursiveField class SubCategorySerializer(serializers.ModelSerializer): parent = serializers.ListField(read_only=True, source='get_children', child=RecursiveField()) class Meta: model = SubCategory fields = ('id', 'name', 'parent',) class ProductSerializer(serializers.ModelSerializer): subcategory = SubCategorySerializer(read_only=True) class Meta: model = Product fields = ('id', 'name', 'subcategory',) models.py file from django.db import models from mptt.models import MPTTModel, TreeForeignKey class SubCategory(MPTTModel): name = models.CharField(max_length=50, unique=True) parent = TreeForeignKey('self', on_delete=models.CASCADE, null=True, blank=True, related_name='children') class MPTTMeta: level_attr = 'mptt_level' order_insertion_by = ['name'] def __str__(self): return self.name class Product(models.Model): name = models.CharField(max_length=128) subcategory = models.ForeignKey(SubCategory, on_delete=models.CASCADE, null=True, blank=True, default=None) def __str__(self): return self.name urls.py from products.views import (ProductViewSet, SubCategoryViewSet) from rest_framework.routers import DefaultRouter router = DefaultRouter() router.register(r'products', ProductViewSet, basename='product') router.register(r'sub-categories', SubCategoryViewSet, basename='subcategory') http://127.0.0.1:8000/sub-categories/ ==> show parent: enter image description here http://127.0.0.1:8000/products/ ==> does not show parent enter image description here -
Django Q lookup returning duplicates which are found in both models
In below queryset I have used or condition but still it is returning me the duplicates. queryset = queryset.filter(reduce(or_, [ Q(user__skill__title__contains=q) | Q(user__availability__locations__contains=q) for q in ['Python', 'Perl', 'C++', 'Unix'] ])) Please advice. -
Generics.ListCreateAPIView (Django Rest Framework)
ViewClass (SessionList): class SessionList(generics.ListCreateAPIView): throttle_scope = 'session' throttle_classes = (ScopedRateThrottle,) #I want to get the session list of speifc user #for ex: queryset = Session.objects.all.filter(id=1) queryset = Session.objects.all() serializer_class = SessionSerializer name = 'session-list' filter_class = SessionFilter ordering_fields = ( 'distance_in_miles', 'speed' ) Session Model: class Session(models.Model): distance_in_miles = models.FloatField() speed = models.FloatField() owner = models.ForeignKey( 'auth.User', related_name='Session', on_delete=models.CASCADE) class Meta: ordering = ('-distance_in_miles',) I'm using (django.contrib.auth.models.User) to create my users. How to filter the quyerset to get only the list of sessions that belong to the logged in user? -
Django Ajax Pagination
I have DetailView where is my AJAX pagination .But i can't return JsonResponse in my scipt.js . It doesn't append next page data. So when i click next button it returns error in console my comments . error my views.py class PhotoDetailView(DetailView): queryset = Photo.objects.select_related('user').prefetch_related('comments', 'comments__user', 'likes') context_object_name = 'photo' template_name = 'photo_detail.html' def get_success_url(self): return reverse('photo_detail', kwargs={'pk': self.object.pk}) def get_context_data(self, **kwargs): context = super(PhotoDetailView, self).get_context_data(**kwargs) page = self.request.GET.get('page') comments = paginator.Paginator(self.object.comments.all(), 5) try: pag_comments = comments.page(page) except (paginator.PageNotAnInteger, paginator.EmptyPage): pag_comments = comments.page(1) if self.request.is_ajax(): return JsonResponse({'pag_comments': list(pag_comments), 'comment': [comment for comment in comments]}) # context['pag_comments'] = pag_comments context['form'] = AddCommentForm(initial={'post': self.object.pk}) context['is_liked_by_user'] = self.request.user in self.object.likes.all() return context script.js var showMore = $('.load-more') showMore.click(function(event){ event.preventDefault(); $.ajax({ url: $(this).attr('href'), type: "GET", success : function(data){ $('.row').prepend('' + data["pag_comments"]); } }) }) comments.html <div class="block-to-be-refreshed"> {% for comment in pag_comments %} <p><strong>{{ comment.user }}</strong> {{ comment.text }}</p> {% endfor %} </div> <div class="row"> </div> <div class="pagination"> <span class="step-links"> {% if pag_comments.has_next %} <a href="?page={{ pag_comments.next_page_number }}" class="load-more">next</a> {% endif %} </span> </div> without AJAX it works -
Django - disable duplicates in related set
There is a class Order, SubOrder and class Product. I want to make sure that no Order object will contain multiple SubOrder objects with the same Product object. class Order(TimeStampedModel): .... class SubOrder(models.Model): order = models.ForeignKey('orders.Order', on_delete=models.CASCADE, related_name='suborders') product = models.ForeignKey('products.Product', on_delete=models.CASCADE) quantity = models.PositiveIntegerField(verbose_name='Počet') So if there were 3 products - A, B, C I don't want allow one Order object to have multiple SubOrders with the same Product. For example Order[Suborder[A,12],Suborder[B,12],Suborder[B,5]] should raise ValidationError because there are two SubOrders with the same Product B. Is it possible to do that on the model or database layer? -
hi can anyone suggest how to pass "result: in to django views
hi can anyone suggest how to pass result:(result returns name of folders which are selected" , i want to pass this name to django backend?? <form id = "form" enctype="multipart/form" method="post"> <ul id = "selectable"> {% for folder in folders %} {% csrf_token %} <li>{{folder}}</li> {% endfor %}enter code here </ul> </form> result:<div id="result"></div> # This show which folder is selected <script type="text/javascript"> $(document).ready(function () { $('#selectable').selectable({ stop: function () { var result = ''; $('.ui-selected').each(function () { result += $(this).text() + '<br/>'; }); $('#result').html(result); }); }); </script> -
How move each network call on celery as task for worker
By writing this question , need to know how to achieve the same as mentioned in subject, description as follows i have a class which has various functions each function has some different link which helps in making url and request to some server. and here i override the init function to store some variable as per need. here i want to move generate_otp function as task for my celery my class with some functions explained as below class FinoApi(): def __init__(self, request): self.url = api_url self.request_data = request self.headers = { "content-type": "application/json", "authentication": headers_encrypted } def generate_otp(self): """Generate OTP""" link = '/ProcessRequest/CityCashGenerateOTP' new_url = self.url + link result = self.get_request(new_url, link) return result def registration(self): """Citycash registration""" link = '/ProcessCityCashRegistration' new_url = self.url + link result = self.get_request(new_url, link) return result def posting_transaction(self): """Transaction posting""" link = '/ProcessRequest/TransactionPosting' new_url = self.url + link result = self.get_request(new_url, link) return result -
Django Form field created in __init__ does not exist in request.POST
Form.py class FormA(forms.ModelForm): fieldA = forms.CharField(required=True) fieldB = forms.CharField(required=True) def __init__(self, *args, **kwargs): super(OfflineAccountEditForm, self).__init__(*args, **kwargs) self.fields['fieldC'] = forms.CharField(required=True) class Meta: model = Profile fields = ('username','first_name','last_name') As you can see, I try to initiate a new field named fieldC in init function. During request 'get' method, it display nicely on form. However, when I submit form, i print out my form, the fieldC field is missing. if request.method == 'GET': if obj: form = FormA(instance=obj) else: form = FormA() else: if obj: form = FormA(request.POST, instance=obj) else: form = FormA(request.POST) print form When I run cleaned_data, it can't find the field. fieldC = form.cleaned_data['fieldC'] Any solution? Please guide. Thanks in advance and appreciate your help. -
How to make Django background tasking when logged out
I want to make a background process in Django that loops some function when you push start button, and stops looping when stop button is pushed. It have to work when the user is 'offline' (logged out).Every user should have separate process. So far I have figured out to use Threading, but I don't know yet how it will work I just created class which starts or stops Threads it looks like that: class Decide(threading.Thread): """Thread for making decision to buy or sell """ def __init__(self, name): threading.Thread.__init__(self) # flag to pause thread self.paused = True self.pause_cond = threading.Condition(threading.Lock()) self.pause_cond.acquire() self.name = name def run(self): while True: with self.pause_cond: while self.paused: self.pause_cond.wait() # Buy_wait_sell() print("I am looping~!!") time.sleep(1) def pause(self): # Acquire to lock worker self.paused = True self.pause_cond.acquire() # should just resume the thread def resume(self): self.paused = False # Notify so thread will wake after lock released self.pause_cond.notify() # Now release the lock self.pause_cond.release() Is this a good concept? How would I assign thread to the user? Maybe models methods? Would this actually be running when I log out or django will kill this process? -
Category links based on request.user.is_staff
I need some guide or help, how can I solve this problem. So I would like to generating category links based on request.user.is_staff Currently I can do this, but it's make some duplicated query. The current method is the next, I have a context processor which is generate the category links def blog_category_links(request): context = dict() queryset = Post.objects.select_related('category').distinct() context['categories'] = set([post.category for post in queryset if post.is_public or request.user.is_staff]) return context It works fine all of the cases except one, when I'm visiting the blog index page. The method nearly the same. queryset = Post.objects.select_related('category').select_related('author').prefetch_related('tags').distinct() ... posts = [post for post in queryset if post.is_public or request.user.is_staff] return posts With this solution if I didn't logged in I get 5 queries ~10ms time without duplication. If i logged in I get 7 queries ~12ms time with 2 duplicates (user query) So I know it's not the best design for this. This is the reason why I would like ask some help. Thanks -
Preference of Filedset vs change_view django?
In admin.py , I have added a field 'category' in fieldset in my ModelAdmin class InpAdmin fieldsets = ( ('About Source', { 'fields': ('category') }), Now I am overriding the change_view def change_view(self, request, object_id, extra_context=None): self.exclude = ('category', ) extra_context = extra_context or {} return super(InpAdmin, self).change_view(request, object_id, extra_context=extra_context) But I can still see this field 'category' in change view form of Django admin. If I am remving it from fieldset then only it disappears. Does fieldset have more preference over change_view ? -
How can i create a zipped file made of a choice of fields when i save my model object?
1) I have a model: class Book(models.Model): ... press_kit = models.FileField(upload_to='press_kit/', verbose_name="Dossier de presse", blank=True, null=True, default=None) high_res_cover = models.ImageField(upload_to='high_res_covers/', verbose_name="Couverture HD", blank=True) zip_press_kit = models.FileField(upload_to='zips/', blank=True, null=True) I just gave the fields i'm interested into. So when i save my new Book object in the django-admin i want to check if i have a high_res_cover OR a press_kit, and if so, create a zip_press_kit that would be a zip file containing the high_res_cover and/or the press_kit. 2) I have a save method: def save(self, *args, **kwargs): zip_file_name = f"{slugify(f'{self.title}-{self.id}')}.zip" if self.high_res_cover or self.press_kit: with ZipFile(f'{MEDIA_ROOT}zips/{zip_file_name}', 'w') as zip_file: if self.high_res_cover: zip_file.write(f'{MEDIA_ROOT}{self.high_res_cover}', os.path.basename(f'{MEDIA_ROOT}/{self.high_res_cover}')) if self.press_kit: zip_file.write(f'{MEDIA_ROOT}{self.press_kit}', os.path.basename(f'{MEDIA_ROOT}/{self.press_kit}')) self.zip_press_kit = File(open(f'{MEDIA_ROOT}/zips/{zip_file_name}', 'rb')) os.remove(f'{MEDIA_ROOT}/zips/{zip_file_name}') else: self.zip_press_kit = None super(Book, self).save(*args, **kwargs) This code works when my book already exists and I call save on it but when i want to get the URL of the file in my template i get something like 'localhost:8000/Users/me/Desktop/ProjectFIle.../' And it definitely doesn't work when i create a new book. First question here, hope i've been clear enough :) -
I installed Django version over 2.x but the command django-admin startproject(lowercase) make project with 1.x version
python3 -m venv venv source venv/bin/actvaite pip install --upgrade pip django-admin startproject temp # 1.x version Django-admin startproject temp # 2.x version django-admin vs Django-admin django-admin start with lowercase make project 1.x version Django-admin start with uppercase make project 2.x version offical docs - start with lowercase docs summary 1) whats wrong in my environment? 2) how can i make project with django-admin(lowercase) -
Reverse for 'contact' not found. 'contact' is not a valid view function or pattern name
I get this error django.urls.exceptions.NoReverseMatch: Reverse for 'contact' not found. 'contact' is not a valid view function or pattern name.. What could I be doing wrong, new to django urls.py urlpatterns = [ path(r'', views.firstpage, name='index'), path(r"contact/", views.contact, name='contact'), ] views.py def firstpage(request): return render(request, 'index.html') def contact(request): return render(request, 'contact.html') index.html <ul class="menu-list"> <li><a href="">Solution</a></li> <li><a href="">Features</a></li> <li><a href="">News</a></li> <li><a href="">About</a></li> <li><a href="{% url 'contact' %}" >Contact</a></li> </ul> -
While Trying to Upload Multiple Files Using Single Form Field with Django Model Form Why i am getting Error no 13.Permission Denied ...?
I am rendering Html form using Django Model Form to upload Mutliple Files, and written code by reading django docs to upload Mutliple Files but i am getting error of Permission Denied.I tried different ways to access directory by providing some permissions but i found those are buggy and unsafe methods. Where i am doing wrong.. i attached screenshot fyr... Error Screen Shot Here Forms.py Code class AddRoomForm(forms.ModelForm): class Meta: model = Rooms fields=['roomNo', 'floor', 'service','manager', 'bed', 'restaurant','roomPictures', 'washroom', 'amenities', ] widgets = { 'roomPictures': forms.ClearableFileInput(attrs={'multiple': True}), } Views.py Code class AddRoom(LoginRequiredMixin, LogoutIfNotAdminMixin, CreateView): login_url = reverse_lazy('alogin') permission_required = 'is_admin' def post(self, request, *args, **kwargs): context={} if request.method =='POST': form = AddRoomForm(request.POST, request.FILES) if form.is_valid(): for count, x in enumerate(request.FILES.getlist("roomPictures")): def process(f): with open('aapp/static/aapp/images/rooms/') as destination: for chunk in f.chunks(): destination.write(chunk) process(x) form.save() return redirect('roomsdata') else: form = AddRoomForm() return render(request, 'aapp/rooms/aroomdata.html', {'form':form,'context':context})