Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - how to sum two Fields of a model? [duplicate]
This question already has an answer here: Django Aggregation: Summation of Multiplication of two fields 4 answers Here's a quick example class Invoice(models.Model): (...) net_amount = models.DecimalField(decimal_places = 2, max_digits=8) tax = models.DecimalField(decimal_places = 2, max_digits=8) @property def gross_amount(self): return self.net_amount + self.tax Then I want to query for chosen Invoices in my ListView using a form and GET: class ListInvoicesView(ListView, FormMixin): (...) def get_queryset(self): (...) return self.model.objects.filter(gross_amount__lte = self.kwargs.get('max_gross_amount')) (I skip some code for the sake of readability) This yields FieldError: Cannot resolve keyword 'gross_amount' into field. What is the proper way to sum two fields of a model? -
Backend endpoints to frontend
Here's the situation: We have a large django application, not on REST structure, our front-end was build with React. What we want to do is find an easy way to tell our front-end which are the URL's that our backend has. For example: Our backend has a "active plan" endpoint which is "plans/active", what we are doing in present days is build a file with django templates that builds an JS object with that endpoints, something like: const urls = {plans: {active: {% url "active_plan" %}}}; The problem here is that it's growing like hell and slowly becoming unorganized and with repeated urls. We had 2 ideas: First one was to parse these urls on python build to generate a file with similar structure as I said before, reflecting exactly what we desire Second one was to have something like a store to make an initial request that is gonna return some area (or all) urls and store these in an object. First one problem is that with an international application, we're gonna have all languages urls in one file, it doesnt not seen nice. Second problem is that we think it can become a big payload if not broken … -
TypeError : encode() missing 1 required positional argument: 'iterations'
i dont know what is triggering this error. i dont know why i keep getting this error . i already change a few parts of code and still i get this error . i have been trying to fix it for 2 days . Traceback: File "C:\Users\Adila\AppData\Local\Programs\Python\Python35\lib\site-packages\django\core\handlers\exception.py" in inner 41. response = get_response(request) File "C:\Users\Adila\AppData\Local\Programs\Python\Python35\lib\site-packages\django\core\handlers\base.py" in _get_response 187. response = self.process_exception_by_middleware(e, request) File "C:\Users\Adila\AppData\Local\Programs\Python\Python35\lib\site-packages\django\core\handlers\base.py" in _get_response 185. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\Adila\Documents\tryFOUR\src\register\views.py" in register 13. user = form.save() File "C:\Users\Adila\Documents\tryFOUR\src\custom_user\forms.py" in save 50. user.set_password(self.cleaned_data["password2"]) File "C:\Users\Adila\AppData\Local\Programs\Python\Python35\lib\site-packages\django\contrib\auth\base_user.py" in set_password 105. self.password = make_password(raw_password) File "C:\Users\Adila\AppData\Local\Programs\Python\Python35\lib\site-packages\django\contrib\auth\hashers.py" in make_password 84. return hasher.encode(password, salt) Exception Type: TypeError at /accounts/register/ Exception Value: encode() missing 1 required positional argument: 'iterations' hashers.py : from django.contrib.auth.hashers import PBKDF2PasswordHasher from django.utils.crypto import (get_random_string, pbkdf2) from honeywordHasher.models import Sweetwords class MyHoneywordHasher(PBKDF2PasswordHasher): algorithm = "honeyword_base9_tweak3_pbkdf2_sha256" iterations = PBKDF2PasswordHasher.iterations*3 def hash(self, password, salt, iterations): hash = pbkdf2(password, salt, iterations, digest=self.digest) return base64.b64encode(hash).decode('ascii').strip() def salt(self): salt = get_random_string() while Sweetwords.objects.filter(salt=salt).exists(): salt = get_random_string() return salt def verify(self, password, encoded): algorithm, iterations, salt, dummy=encoded.split('$',3) hashes = pickle.loads(Sweetwords.objects.get(salt=salt).sweetwords) hash = self.hash(password, salt, int(iterations)) if hash in hashes: return honeychecker.check_index(salt, hashes.index(hash)) return False def encode(self, password, salt, iterations): sweetwords = ['hilman95'] sweetwords.extend(honey_gen.gen(password, base64, ["passfiles.txt"])) … -
How to create a download button/option for image/filefield in Django
Working fine. But whenever i am hitting the file download link download option appears but after i download the file it's no longer the same file that i have uploaded. rather it becomes 9 bytes small file and can't be opened. views.py def download_file(request, path): response = HttpResponse('image/png') response['Content- Type']='image/png' response['Content-Disposition'] = "attachment; filename="+path response['X-Sendfile']= smart_str(os.path.join(settings.MEDIA_ROOT, path)) return response urls.py url(r'^get\/(?P<path>.*)$', download_file), -
Redirect after POST django rest framework
I am submitting a POST request via django form to my Django Rest Framework api. Here is a snippet of my form: <form action="{% url 'entry-list' %}" method="POST" class="form" role="form"> {% csrf_token %} {{form.as_p}} <div class = "form-group"> <button type="submit" class="save btn btn-default btn-block">Save</button> </div> views.py: class entry_ViewSet(viewsets.ModelViewSet): queryset = Entry.objects.all() serializer_class= EntrySerializer permission_classes = (permissions.IsAuthenticatedOrReadOnly,IsOwnerOrReadOnly,) def perform_create(self, serializer): serializer.partial = True serializer.save(created_by=self.request.user) I am making a successful POST (and item is created in database), however once I save I go to the url /api/entry/ which shows my api w/Markdown. I'd like to have it go back to a specific url. Is there a way to customize where the POST redirect to if successful? -
Django : several models returns in queryset
Yeah I know, it's not possible. Or maybe I didn't see. But, I'm gonna explain why I need this. Let's do some dummy classes: class A(models.Model): content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.PositiveIntegerField() lvl_struct = GenericForeignKey('content_type', 'object_id') Let's say A can be attached to a struct (logical struct, like department in jobs). An A instance can be attached to only one struct, but there're 4 disctinct type of struct, and that's where I discovered generic foreign key (instead of a polymorphism on A). But now, my problem is, in my form, I want to attach the actual struct when I create a A instance : class CreateAForm(forms.ModelForm) lvl_struct = forms.ModelChoiceField( queryset=None, #here is my problem required=True ) So here I would like to have a unique select with all possibilities (all instances of first struct type, all instances of second struct type and so on). So is there any way to do this, or will I have to do like four select with some js to check at least one and only one select has a value? Or of course a third solution which I didn't see. Tell me. Thank you in advance for your time. -
How to introduce a model class method in Django admin
I have a model that has class methods. In testing the class methods work and alter the model instances according to my needs. The issue is using this class method in the admin. When an application cannot pay a late payment fee is applied creating another transaction altering the balance. The method in models is decorated with a @classmethod decorator. I need to get it so when status is altered, or when a tickbox is checked in the admin for an application it fires the class method. I have Googled overriding models in admin but cannot find anything. Many thanks for reading this. -
Replace string with other string python django
Hi guys i want to convert link into proper format for example i have text like This is google link https://www.google.com This is gmail link https://www.gmail.com And what i want is This is google link <a href="https://www.google.com">https://www.google.com</a> This is gmail link <a href="https://www.gmail.com">https://www.gmail.com</a> and here is code that i have written body_without_quotes = request.POST.get('stripped-text', '') data1 = re.findall('http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+', body_without_quotes) for da in data1: link = "<a href="+da+">"+da+"</a>" body_without_quote = body_without_quotes.replace(da, link) print body_without_quotes but it does not print required output can anyone tell me what i am doing wrong here. Thanks -
Django: How to return with context from UpdateView (CBV)?
The following view works as expected class BrandEditView(PermissionRequiredMixin ,generic.UpdateView): permission_required = 'change_brand' template_name = 'brand_update_form.pug' model = Brand fields = ['name'] def get_object(self, queryset=None): print(self.request.user) self.object = Brand.objects.get(id=self.kwargs['pk']) obj = Brand.objects.get(id=self.kwargs['pk']) return obj After form submission, how do I return to the same view (with the same object), but with a message like "brand edited successfully"/"you can't do that"? I've found a way to redirect to the same view, but not with context. -
Performance, load and stress testing in Django
I am studying the different types of testing for a Django application. I know how to do functional and unit testing in Django and how to apply different methodologies, but now I am facing a new challenge, I need to know how to do: Performance testing Load testing Stress testing I know the difference between them but I dont know which is the best methodology to follow,which are the best packages for do it or simply where I can get some documentation about it. So my question is, how can I start to do these types of tests in a Django app or where can I get some good documentation about it? Thanks -
Django models.DecimalField issues with type and value conversion
Let's say you have a model like this: class Example(models.Model): amount = models.DecimalField(max_digits=8, decimal_places=2) I can do the following with no issue: x = Example() x.amount = 1.23456 x.save() print(x.amount, type(x.amount)) # outputs '1.23456 <type 'float'>' If I load back the object I find that x.amount is now equal to Decimal('1.23'). So, my issue is, at any given moment with any given instance of Example the amount attribute may contain a Decimal, a float, an integer, or something else that can be coerced into a Decimal. Also, the value may not yet be rounded to 2 decimal places so the value may change after saving and loading back from the database. As well, a statement like x.amount + Decimal('1') may work or may throw an exception about combining float with Decimal. Has anyone developed a replacement for models.DecimalField that mitigates these issues by immediately performing conversions and rounding when assigning a value instead of how it currently functions? Or, alternatively, a model that throws an error if an improper type is assigned or one that would be rounded on save? (I suspect I could write my own, but I was hoping I could find someone else's work that's already been … -
Django how to merge multiple query results
I have an ArrayField with choices and i'm trying to filter the choices: When i use Location.objects.filter(city__id='683506').values_list('options', flat=True) and it returns me <QuerySet [['0'], ['0', '1', '2', '3'], ['0', '1', '2'], ['0', '1'], ['0', '1', '2', '3']]> How can i merge the query or make them into a list and merge them? This is what i wish to get ['0', '1', '2', '3'] -
DjangoRestFramework serializer filter and limit related
Thats my models: class Org: name = CharField() owner = ForeignKey(User) class Cafe: name = CharField() org = ForeignKey(Org) class Product: name = CharField() class Assortment: cafe = ForeignKey(Cafe) product = ForeignKey(Product) price = IntegerField So the deal is - i need to search products with very specific way. It should looks like this: /assortment/search/?searh=cola 'cafe':{ 'id:1, 'name': 'Foo', 'assortment': [ { 'product': { 'id': 1, 'name': 'Cola' }, 'price': 100 }, { 'product': { 'id': 2, 'name': 'Coca-cola' }, 'price': 200, } ], 'search_count': 5, }, 'cafe': { 'id':2, 'name': 'Bar', 'assortment': [ { 'product': { 'id': 3, 'name': 'Sprite-cola', }, 'price': 150, }, ] 'search_count': 1, } So the problem is - when i search like Cafe.objects.filter(assortment__product__name='cola') It works, it shows all Cafes where product with name 'cola' exists, but problem is DJF serializer class CafeSerialzier: assortments = AssortmentSerializer(source='assortment_set') search_count = IntegerField(source='assortment_set.count') assortments and search_count shows all assortment and count of it, and does not consider search arguments, which is expected. So the question is - how to pass search parameters into source='assortment_set' (Also i need to limit results to 3) and how to count all search results. I've tried SerializerMethodField for assrotments, it solves a part of … -
django-simple-history, displaying changed fields in admin
When I inherit from admin.ModelAdmin, in history on admin page I can see what fields has been changed. However, now I need to use django-simple-history to track all my model changes. Now, for admin, I inherit for simple_history.SimpleHistoryAdmin. Whilst I can see all of the model changes and revert them, I cannot see, which fields were changed. Is it possible to add that handy functionality to SimpleHistoryAdmin? -
Type-error - django python
from django.conf.urls import * from django.contrib import admin from payments import views admin.autodiscover() urlpatterns = [ # Examples: # url(r'^$', 'ecommerce_project.views.home', name='home'), # url(r'^ecommerce_project/', include('ecommerce_project.foo.urls')), # Uncomment the admin/doc line below to enable admin documentation: # url(r'^admin/doc/', include('django.contrib.admindocs.urls')), # Uncomment the next line to enable the admin: url(r'^admin/', include(admin.site.urls)), url(r'^$', 'main.views.index', name='home'), url(r'^pages/', include('django.contrib.flatpages.urls')), url(r'^contact/', 'contact.views.contact', name='contact'), url(r'^sign_in$', views.sign_in, name='sign_in'), url(r'^sign_out$', views.sign_out, name='sign_out'), url(r'^register$', views.register, name='register'), url(r'^edit$', views.edit, name='edit')] Issue in this code - type error - view must be callable I do not understand what is wrong with my urls.py file, here is a copy of it: Type error -
inline form with django crispy form
I'm sorry but I just don't get it, the docs here are pretty awesome, and I'm using practically the same example, I just have two fields, that I want do display inline, but it's just does not work, My form: from django import forms from crispy_forms.helper import FormHelper from crispy_forms import layout, bootstrap from crispy_forms.bootstrap import InlineField, FormActions, StrictButton from crispy_forms.layout import Layout from ..models import EmployeeModel class EmployeeCreateForm(forms.ModelForm): """ TODO: Extend CompanyModel into Form :returns: TODO """ def __init__(self, *args, **kwargs): super(EmployeeCreateForm, self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_tag = False self.helper.method = "POST" self.helper.form_class = 'form-inline' self.helper.field_template = 'bootstrap3/layout/inline_field.html' self.helper.form_action = "company:create-employee" self.helper.layout = Layout( 'first_name', 'last_name', StrictButton('Add', css_class='btn-default'), ) class Meta: model = EmployeeModel fields = ["first_name", "last_name"] and my template: {% extends "base.html" %} {% load i18n static %} {% load crispy_forms_tags %} {% block content %} <nav class="navbar fixed-top navbar-light bg-faded"> <ul class="nav justify-content-center"> <li class="nav-item"> <a class="nav-link" href="{% url 'why' %}">WHY SCREEN?</a> </li> <li class="nav-item"> <a class="nav-link" href="#">BLOG</a> </li> <li class="nav-item"> <a class="nav-link" href="{% url 'faq' %}">FAQ</a> </li> <li class="nav-item"> <a class="nav-link" href="{% url 'about' %}">ABOUT</a> </li> </ul> </nav> <div class="container"> <div class="row"> <p style="padding:60px;"></p> </div> </div> <div class="container"> <div class="row"> <div class="col-sm-4 col-sm-offset-2"> <form … -
Django: cannot decode unicode characters from StreamingHttpResponse streaming_content
I'm trying to test a django admin action method streaming a large CSV file . I'm using StreamingHttpResponse object since I'm dealing with a large number of rows as suggested by official documentation. The only difference from the implementation above is that my csv output may contain unicode strings. Export function is working fine since is streaming huge numbers of rows in seconds. Here's how I'm formatting every single line before sending them to writerow function [u'{}'.format(field_1), u'{}'.format(field_2)] I'm having a very hard time to test StreamingHttpResponse object on python 2. Say my_streaming_http_response is the StreamingHttpResponse object I want to test, here's my test: reader = csv.reader( [i.decode('utf-8') for i in my_streaming_http_response.streaming_content] ) self.assertEqual( list(reader), [ ['Row-1-col-1', 'Row-1-col-2'], ['Row-2-col-1', 'Row-2-col-2'], ] ) this works with python2 and python3 when no unicode strings are provided python3 when containing unicode When I try to run this test on python 2 I get this error UnicodeEncodeError: 'ascii' codec can't encode character [UNICODE CODE] in position [POSITION]: ordinal not in range(128) and I just cannot figure out how to test this on python2, any suggestion? Thanx in advance! -
How to "group by" in django serializers for same model
I am new to Django-Python and learning to build serializers. I understand the basic implementation of Serializers but stuck with this following particular requirement. This is my Customer Events model - class CustomerEvents(models.Model): account_number = models.BigIntegerField(blank=False) event_type = models.CharField(max_length=255, blank=False, null=False) Sample records in CustomerEvents: Account Number Event Type A12345 Billing Issues A12345 Video Services A12345 Sales I want to create a CustomerEventsSerializer which will return values as below: { "account_number" : A12345, "event_types" : ['Billing Issues', 'Video Services', 'Sales'] } -
How to add an OrderingFilter to existing filters and render them as links
I'm using django-filter for filtering posts of a Django wagtail index page via the django-filter's LinkWidget. That works fine, just like in the django admin interface with list_filter. Now I would like to expose the functionality to sort/order the queryset by some criteria. Django-filter does provide an OrderingFilter (ref) - but I do not know how to implement this filter and achieve a LinkWidget-like rendering. My current approach: # filters.py class PostFilter(django_filters.FilterSet): categories = PatchedAllValuesFilter( name="categories__slug", label="Categories", widget=LinkWidget(), choice_name="categories__name", ) ordering = django_filters.OrderingFilter( widget=LinkWidget, fields=( ('title', 'title') ) ) class Meta: model = PostPage fields = ['categories'] # views.py from .models import PostPage from .filters import PostFilter filter = PostFilter(request.GET, queryset=all_posts) filter_ordering = PostFilter(request.GET, queryset=all_posts).filters['ordering'] context = self.get_context(request) context['filter'] = filter context['filter_ordering'] = filter_ordering return render(request, self.template, context, *args, **kwargs) # template.html <ul> {% for choice in filter_ordering.field.choices %} <li>{{ choice }}</li> {% endfor %} </ul> ... but this does not work. I do get something from my OrderingFilter: ('', '---------') ('title', <django.utils.functional.lazy.<locals>.__proxy__ object at 0x7f0d3e021cc0>) ('-title', 'Title (descending)') ... and how to render this as links in my template? Grateful for any help -
Django one to one filed with User in form
I try to update number_of tokens and amount, but it doesn't work, can some one tell me what's the problem models.py class ConfiTCL(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) number_of_tokens = models.IntegerField(blank=True, null=True) amount = models.IntegerField(blank=True, null=True) forms.py class ConfigPCLForm(forms.ModelForm): """This class represents the Config PCL form""" class Meta: model = ConfiTCL fields = ('number_of_tokens', 'amount',) widgets = { 'number_of_tokens': forms.TextInput(attrs={'class': 'form-control'}), 'amount': forms.TextInput(attrs={'class': 'form-control'}), } views.py class UpdateAdminView(TemplateView): template_name = "admin.html" @method_decorator(user_passes_test(lambda u: u.is_superuser)) @method_decorator(login_required) def dispatch(self, *args, **kwargs): return super().dispatch(*args, **kwargs) def post(self, request): form = ConfigPCLForm(request.POST, instance=request.user) if form.is_valid(): form.save() return TemplateResponse(request, self.template_name, {'form': form,'user':self.request.user}) def get(self, request, *args, **kwargs): user = User.objects.get(username=request.user) form=ConfigPCLForm(instance=user) context = {'form': form,'user':self.request.user} return TemplateResponse(request, self.template_name, context) -
Django: FormView not execute the form_valid() method
I am using Braintree as a Payment solution (Sandbox). When I use a fill the form it redirect me to the same page. My error is that the Form doesn't get process. On the FormView only the get_context_data() were execute but not form_valid() html <script src="https://js.braintreegateway.com/web/dropin/1.6.1/js/dropin.min.js"></script> <form action="{% url 'checkout_braintree' %}" method="POST" id="payment-form"> {% csrf_token %} <h3>Method of Payment</h3> <p>378282246310005</p> <input type="hidden" id="nonce" name="payment_method_nonce" /> <div class="bt-drop-in-wrapper"> <div id="bt-dropin"></div> </div> <button class="button" type="submit" id="submit-button"><span>Test Transaction</span></button> </form> var form = document.querySelector('#payment-form'); braintree.dropin.create({ authorization: '{{ client_token }}', container: '#bt-dropin', paypal: { flow: 'vault' } }, function (createErr, instance) { form.addEventListener('submit', function (event) { event.preventDefault(); instance.requestPaymentMethod(function (err, payload) { if (err) { console.log('Error', err); return; } // Add the nonce to the form and submit document.querySelector('#nonce').value = payload.nonce; form.submit(); }); }); }); urls.py url(r'^checkout/$', BraintreePaymentProcessFormView.as_view(), name='checkout_braintree'), views.py class BraintreePaymentProcessFormView(FormView): template_name = 'startupconfort/cart.html' success_url = '/' form_class = BraintreeSaleForm http_method_names = ['post'] def get_context_data(self, **kwargs): # import ipdb; ipdb.set_trace() context = super().get_context_data(**kwargs) context['client_token'] = get_braintree_client_token() return context def form_valid(self, form): # import ipdb; ipdb.set_trace() user = self.request.user nonce = form.cleaned_data['payment_method_nonce'] result = braintree.Transaction.sale({ "amount": get_total_price_of_the_shipping_cart(user), "payment_method_nonce": nonce, "options": { "submit_for_settlement": True } }) # import ipdb; ipdb.set_trace() if result.is_success or result.transaction: print(result.transaction) messages.success(self.request, 'Payment … -
Django - How to save user activity log to log table
I've searched many times through Google. because I can't find my question answer and I'm ask for help. I am not familiar with Django, i should not use third-party module For example, django-user-activity-log. i need help with the principle and method configuring and recording log tables to log user activity logs in log table. to sum up, First, I need to count users who have completed membership and those who have not. Next, I need to configure and record the table to record the user activity log. log table is content who, when, what, how do. form is to string. because if i have a problem with my customer, i should use the log to respond. Ultimately, i need to count member, non-member, analyzing user activity. For example, Google Analytics. i ask help in other world developers. How can I log user activity logs into a log table in string format? -
Using a User uploaded file as an email template in django
I have the following Python code within a Django model to send emails to the 'owner' of the model. I want admin to be able to upload files which will be used (if uploaded) or the default template files will be used if it has not be loaded. This is the code: def send_invitation(self): ''' sends an invitation from admin to accept a listing ''' try: if self.user or not self.email : return False except : try: email_body_template = Parameter.objects.get(name='send_invitation_email.txt').f except: email_body_template = 'listing_cms_integration/email/send_invitation_email.txt' try: email_subject_template = Parameter.objects.get(name='send_invitation_email_subject.txt').f except: email_subject_template = 'listing_cms_integration/email/send_invitation_email_subject.txt' context = Context() context['listing'] = self context['site'] = Site.objects.get_current().domain subject = render_to_string(email_subject_template, context) message = render_to_string(email_body_template, context) email = EmailMessage(subject, message, to=[self.email]) email.send() return True If I do not have a Parameter named 'send_invitation_email.txt' then it works fine. When picking up Parameter as specified I get the following error. coercing to Unicode: need string or buffer, FieldFile found How do I convert my user uploaded file into one I can use as an email template? -
django: Setting environment variables in /etc/apache2/envvar is not working
I have a Django (v1.11.6) app on my Ubuntu server having Python 3.5 (not using virtualenv). However, I want to set environment variables in mod_wsgi for Django. Since I'm not using virtualenv I set then in /etc/apache2/envvar. But apache2 service can't get them. In settings.py I have SECRET_KEY = get_env_variable("GA_SECRET_KEY") but apache raises the following error: [Mon Oct 23 14:03:29.180611 2017] [wsgi:error] [pid 30062] [client 194.42.16.145:13576] SECRET_KEY = os.environ("GA_SECRET_KEY") [Mon Oct 23 14:03:29.180630 2017] [wsgi:error] [pid 30062] [client 194.42.16.145:13576] TypeError: '_Environ' object is not callable Do you know how to fix this? -
AttributeError at /accounts/upload_save/ 'WSGIRequest' object has no attribute 'cleaned_data'
I got an error,AttributeError at /accounts/upload_save/ 'WSGIRequest' object has no attribute 'cleaned_data' .I am making file upload system.It is that if i select file and put "SEND" button,selected image is sent to model.But now,when i select images and put "SEND" button,the error happens. I wrote in views.py @login_required @csrf_exempt def upload_save(request): form = UserImageForm(request.POST, request.FILES) if request.method == "POST" and form.is_valid(): data = form.save(commit=False) data.user = request.user data.image = request.cleaned_data['image'] data.save() return render(request, 'photo.html') else: form = UserImageForm() return render(request, 'profile.html', {'form': form}) in index.html <main> <div class="detailimg col-xs-8"> <div class="relative_ele"> <div class="container" id="photoform"> {% if form.errors %} <div class="alert alert-danger" role="alert"> <p>At least 1 picture should be selected</p> </div> {% endif %} <form action="/accounts/upload_save/" method="POST" enctype="multipart/form-data"> {% csrf_token %} <div class="input-group"> <label class="input-group-btn" style="width: 80px;"> <span class="file_select btn-lg"> File Select1 <input type="file" name="image"> </span> </label> <input type="text" class="form-control" readonly=""> </div> <div class="input-group"> <label class="input-group-btn" style="width: 80px;"> <span class="btn-lg file_select"> File Select2 <input type="file" name="image2"> </span> </label> <input type="text" class="form-control" readonly=""> </div> <div class="form-group"> <input type="hidden" value="{{ p_id }}" name="p_id" class="form-control"> </div> <div class="col-xs-offset-2"> <div class="form-group"> <input type="submit" value="SEND" class="form-control"> </div> </div> </form> </div> </div> </div> </main> I really cannot understand why this error happens.I reworte in views.py like @login_required …