Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
No URL to redirect to provide a url or define a get_absolute_url method on the Model
I have the following class wherein I explicitly defined a redirect method which should prevent that above error. @method_decorator(login_required, name='dispatch') class PostUpdateView(UpdateView): model = Post fields = ('message',) template_name = 'board/edit_post.html' pk_url_kwarg = 'post_pk' context_object_name = 'post' def get_queryset(self): queryset = super().get_queryset() # ! queryset.objects.filter return queryset.filter(created_by=self.request.user) def form_valid(self, form): post = form.save(commit=False) post.updated_by = self.request.user post.updated_at = timezone.now() post.save() super(PostUpdateView, self).form_valid(form) return redirect('board:view_topic', pk=post.topic.board.pk, topic_pk=post.topic.pk) I then deleted super(PostUpdateView, self).form_valid(form) from here and everything worked fine. Don't know why it should be like this? Similar to below function, when I always call from_valid I always add super().form_valid() why I have to delete it here to make it work. def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) i hope you help me thank you. -
Getting all data out of models class, using views, onto a template
Coming out of the crash course book and trying to put things into practice. The problem is the Django instructional did not cover multiple data points per class. Below is the models, views, and the template. I know the problem is the class, but I'm not finding the best way to return all the class data in a way the views def will pull it in. (models.py) class PropData(models.Model): date_added = models.DateTimeField(auto_now_add=True) prop = models.ForeignKey(Prop, on_delete=models.CASCADE) date_purchased = models.DateField() city = models.TextField(max_length=75) state = models.TextField(max_length=25) purchase_price = models.DecimalField(max_digits=11, decimal_places=2) (views.py) def prop(request, prop_id): prop = Prop.objects.get(id=prop_id) propdata = prop.propdata_set.all() context = {'prop': prop, 'propdata': propdata} return render(request, 'propSheets/property.html', context) (property.html) <p>Property: {{ prop }}</p> <p>City: {{ propdata.city }}</p> Of course, propdata.city returns nothing. What do I need to add/change so I can output querysets to the page? -
Is there a way to retrieve a datetime field to a specific timezone by default in Django?
I've an attribute in a django model like : created_at = models.DateTimeField(auto_now_add=True) and in my settings.py I've configurations like : TIME_ZONE = 'Asia/Dhaka' USE_TZ = True create_at field is getting saved in UTC when I create an object. I want to retrieve this field in a specific timezone like Asia/Dhaka. Is there a way to retrieve queryset where created_at field will be in my desired timezone? Thank you -
Heroku Deployment Error: No matching distribution found for en-core-web-sm
I am trying to deploy my Django and spaCy project to Heroku. But I am getting an error: No matching distribution found for en-core-web-sm (It is an ML model downloadable via pip). How can I solve this problem? The model is installed locally in a virtual environment and working alright. I got the requirements file via pip freeze. I am using Python 3.6.4. -
How to write a django management command for download excel files and import them in django models
I'm new to management commands in django, I have read the documentation but did not understand well.. I need help in writing a management command for downloading excel file from a website and import that file in my django models. These are my models. class TimeOfMonth(models.Model): """ """ time_of_month = models.CharField(max_length=15) def __str__(self): return self.time_of_month class Details(models.Model): """ """ first_name = models.CharField(max_length=15) second_name = models.CharField(max_length=25) time = models.ForeignKey(TimeOfMonth, on_delete=models.CASCADE) def __str__(self): return self.first_name I need to import the file in Details along with the foreign key auto generate to the imported file somehow after I download the file using management command. Can someone help me how to write this command and how to import the data in models -
Extended registration form post, but doesn't save to DB
I've extended my signup form in Django, that's based on UserCreationForm. It will post the data but won't submit it to the DB. What did i misunderstand? I've added form validation, to check the form, I as well checked, that I can see what's posted. Under the network tab in chrome inspector I see this under my forms header: Form data: csrfmiddlewaretoken: 3GHtaasjvJ5Qbl3qvDB9loxCdgYdtZ0aRwG0g5n3sjlopGUZlNt1wEOaLNVLdIe7 first_name: dfhdsfh last_name: dfghfgh username: dfhg email: hdghgfh@sdg.dk password: lolleren123 password2: lolleren123 My files are as following below. I've cleaned the code so only the necessary code are shown here. urls.py from django.urls import path, re_path, reverse_lazy from . import views from django.contrib.auth import views as auth_views app_name = 'accounts' urlpatterns = [ path('login', views.login_view, name='login'), path('signup', views.signup_view, name='signup'), path('logout', views.logout_view, name='logout'), ] forms.py from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm class RegistrationForm(UserCreationForm): email = forms.EmailField(required=True) class Meta: model = User fields = ( 'username', 'first_name', 'last_name', 'email', 'password1', 'password2' ) def save(self, commit=True): user = super(RegistrationForm, self).save(commit=False) user.first_name = cleaned_data['first_name'] user.last_name = cleaned_data['last_name'] user.email = cleaned_data['email'] if commit: user.save() return user views.py from django.shortcuts import render, redirect from django.contrib.auth.forms import UserCreationForm, AuthenticationForm from django.contrib.auth import login, logout from accounts.forms import RegistrationForm … -
Authenticate always return None in Django
Authenticate always return None and i'm not find a answer that work with me I think that the problem are in my model or form model: class Employee(models.Model): nameuser = models.CharField(max_length=100) passworduser = models.CharField(max_length=6) class Meta: db_table = "employee" in the model code should't the passworduser be a password type? Forms: class EmployeeForm(forms.ModelForm): class Meta: model = Employee fields = "__all__" My View: from django.contrib.auth import authenticate, login as auth_login def login(request): form = EmployeeForm(request.POST) if request.method == 'POST' and form.is_valid(): username = form.cleaned_data['nameuser'] password = form.cleaned_data['passworduser'] user = authenticate(username=username, password=password) if user is not None: auth_login(request, user) return redirect("/index") else: print (username) #Return the input correctly print(password) #Return the input correctly print(user) #Return None print(form) else: form = EmployeeForm() return render(request, 'htmlfiles/login.html') I already added the module: AUTHENTICATION_BACKENDS=('django.contrib.auth.backends.ModelBackend',) and still doesn't work, thanks!! -
Problem with POST from fronside. Method does not support writable dotted-source fields by default
I create some dotted source field in my serializer. I did it cause have to display name value of foreign key not pk value. But when I trying to POST from frontend djang throws this : AssertionError at /api/my-api/ The .create() method does not support writable dotted-source fields by default. Write an explicit .create() method for serializer MySerializer, or set read_only=True on dotted-source serializer fields. So, when I set read_only = True my POST from frontend to request null for every field from dotted-source serializer fields. This is my serializer: class FcaWorksSerializer(serializers.ModelSerializer): fell_form = serializers.CharField(source="fell_form.name" ) #... main_type = serializers.CharField(source="main_type.name") class Meta: model = FcaWorks fields = ('id_fca','wkod', 'main_type','fell_form','fell_type','kind',\ 'sortiment','vol_drew','use_type','fca_res','ed_izm','vol_les','act_name',\ 'obj_type','use_area','indicator','comment','date_report') How I can to solve this problem? -
Django REST Framework: Transform value before validation
I have the following model: class Runner(Base): # ... progress = models.DecimalField( max_digits=5, decimal_places=4 ) I want that the user can enter 20 and the number is transformed to 0.20. I've already done this in a form before by using the clean method. def clean_progress(self): progress = self.cleaned_data.get('progress') if progress is not None: progress /= 100 return progress Does someone know how to do this in a REST API? I've only found the validate_progress method but it's not working with this method because there is some validation before that gives me the error "Ensure that there are no more than 1 digits before the decimal point." -
Django file assertion
I successfully PATCH my payload with postman app. In order to save up my time I wants to do it in code base not graphical base. def test_owner_patch_avatar_and_background(self): client = APIClient() client.force_authenticate(user=self.jc) url = reverse('mobile_me') with open('media/background.jpg', 'rb') as background: with open('media/default.png', 'rb') as avatar: data = { 'avatar': avatar, 'background': background, } res = client.patch(url, data=data, format='multipart') user_profile = UserProfile.objects.first() assert status.HTTP_202_ACCEPTED == res.status_code assert background == user_profile.background assert avatar == user_profile.avatar I stuck at in memory file assertion. I would like assert that saved files are the same as patched files. Currently I do assertion by name of them. Here is debug line in my testcase. In[4]: background Out[4]: <_io.BufferedReader name='media/background.jpg'> In[5]: user_profile.background Out[5]: <ImageFieldFile: backgrounds/background_b4gQ4BS.jpg> Question: How do I assert between uploaded file and saved file in Python/Django REST? -
Query objects by date range - Error - {TypeError}expected string or bytes-like object
I am trying to get all the data from tasklist table where due_data should be in between today's date and date passed via URL. Filter Query objects by date range in Django showing error - {TypeError}expected string or bytes-like object Models.py class TaskList(models.Model): id = models.AutoField(primary_key=True) tasks = models.CharField(max_length=1000) due_date = models.DateField(null=False) # e.g. 2019-01-15 task_state = models.ForeignKey(States, on_delete=models.CASCADE) class Meta: db_table = 'tasklist' Views.py today = date.today().isoformat() #task_due_date - say '2019-05-13' passing as a string via url task_obj = TaskList.objects.filter(due_date=[today, task_due_date]) # error in this line -
What does this line of code read in plain English?
I'm new to python and Django. I've been playing around with the Django polls tutorial and all is going well but I'm still getting used to the syntax. What does this line read in plain English? return now - datetime.timedelta(days=1) <= self.pub_date <= now The part I'm having trouble with is the <= operator. I'm aware this usually means less than or equal to but I've never seen them being used in succession such as above. -
Celery rate-limiting: Is it possible to rate-limit a celery task differently based on a run-time parameter?
I would like to rate-limit a Celery task based on certain parameters that are decided at runtime. Eg: If the parameter is 1, the rate limit might be 100. If the parameter is 2, the rate-limit might be 25. Moreover, I would like to be able to modify these rate-limits at run-time. Does celery provide a way of doing this? I could use a routing_key to send tasks to different queues based on a parameter, but celery doesn't appear to support queue-level rate-limiting. One possible solution would be to use eta while queueing up the task, but I was wondering if there was a better way of achieving this. -
Django DRF how to limit items created at a time in serializer
I'm setting POST API endpoint(in Django Rest Framework) to add offers for auction. Hovewer there are two constraints which Im not sure how to handle: 1) Bidder can have maximum of three offers per single auction 2) Offers from same bidder for same auction can't be the same(duplicated) The bidder can apply multi offers in one request, but I dont know how to validate that he doesn't send more than 3 offers, and how to check if he sends 2 new offers while he posted 2 offers before(so he exceeded the limit). The same applies for offers duplication, I tried to check for that in serializers "validate" method checking for already sent offers, but nothing is found when processing new offers. It looks like they are being commited to DB together, aren't they? Offer Viewset - Here I used code found on Stackoverflow for allowing list of items being created in single POST request class OfferViewSet(viewsets.GenericViewSet, mixins.CreateModelMixin): serializer_class = OfferSerializer permission_classes = (IsValidBidder,) def get_serializer(self, *args, **kwargs): if isinstance(kwargs.get('data', {}), list): kwargs['many'] = True return super(OfferViewSet, self).get_serializer(*args, **kwargs) Here are parts of OfferSerializer def validate(self, attrs): ... already_placed_offers_qs = Offer.objects.filter( bidder=attrs['bidder'], auction=attrs['auction'] ) if already_placed_offers_qs.count() >= 3: raise LimitExceededError() # … -
How do I validate a django form choicefield with dynamically generated choices?
I have a Django form with a ChoiceField using dynamically-generated choices. A movie_dict_list is generated by an API (themoivedb) when another form is submitted with a movie title to search. Movie_dict_list is then passed to MovieChoiceForm as a kwarg during initialization and used to create the choices list. class MovieChoiceForm(forms.Form): def __init__(self, *args, **kwargs): if 'movie_dict_list' in kwargs: # movie_dict_list is list of objects of form {'title': 'movie_title', 'release_year': 'year', 'id': 'movie_db_id'} movie_dict_list = kwargs.pop('movie_dict_list') if movie_dict_list: # create choice list with form [(object, display_string), ...] movie_choice_list = [(movie_dict, "{} ({})".format(movie_dict['title'], movie_dict['release_year'])) for movie_dict in movie_dict_list] else: movie_choice_list = [(None, 'No Results')] else: movie_choice_list = [(None, 'No Results')] super(MovieChoiceForm, self).__init__(*args, **kwargs) #create field print(movie_choice_list) self.movie_choice_list = movie_choice_list self.fields['select_movie'] = forms.ChoiceField(required=False, choices=movie_choice_list, widget=forms.Select, label='Select Result') The problem comes when validating the form by calling .is_valid() on a new form instantiated from the request.POST data. Since the new form isn't passed the previously generated movie_dict_list as a keyword argument, it doesn't have the same list of choices to validate against and returns the error "Select a valid choice. {'title': 'Star Wars', 'release_year': '1977', 'id': 11} is not one of the available choices." The only thing I can think of would be to … -
How to select a specific data from the database and render it to a django template?
I am trying to build a website using Django 2.2.1,So the problem I currently have is I have a model named "Product". I also have a template named "product_list.html". My "views.py" file is:- from .models import Product from .forms import ProductForm # Create your views here. def product_detail_view(request): obj = Product.objects.all() context = { "title": obj, "description": obj, "price": obj #context = { # 'object': obj } return render_to_response("product_list.html",context) My models.py file :- from django.db import models # Create your models here. class Product(models.Model): title = models.CharField(max_length=50) description = models.TextField(null=True) price = models.DecimalField(max_digits=100, decimal_places=2) My product_list.html file :- {% extends 'base.html' %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Product List</title> </head> <body> {% block content %} <ul> <li> {{ title }} </li> <li> {{ obj.title }} </li> </ul> <ul> {% for prod in title %} <li> {{ prod.title | upper }} </li> {% endfor %} </ul> <ul> {% for prod in description %} <li> {{ prod.description|default:"nothing" }} </li> {% endfor %} </ul> <ul> {% for prod in price %} <li> {{ prod.price }} </li> {% endfor %} </ul> <ul> {% for prod in price %} <li> {{ prod.title }} {{ prod.description }} {{ prod.price }} </li> {% endfor %} … -
Redirect Output of Logger to File
I am performing a simple Python Django TestCase. The question is simple: I want to use loggers to redirect information (stdout) to one file and failures/errors (stderr) to another. I know I can print stdout to a file simply by defining the logger and using it to print the messages (i.e. logger.info('my debug message')); however, I have not found a way to log a failure/error. I can redirect the output of the entire test run using Bash (of which I am semi-successful), but I know there is a way to simplify it and use loggers to do all that backend work for me. Here is an example of my logger: LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'verbose': { 'format': '%(levelname)s %(asctime)s, %(module)s at line %(lineno)d:\n%(message)s' }, }, 'handlers': { 'app': { 'level': 'DEBUG', 'class': 'logging.FileHandler', 'filename': 'logs/app.log', 'formatter': 'verbose' }, 'test': { 'level': 'DEBUG', 'class': 'logging.FileHandler', 'filename': 'logs/test.log', 'formatter': 'verbose' }, 'test-fail': { 'level': 'ERROR', 'class': 'logging.FileHandler', 'filename': 'logs/test-fail.log', 'formatter': 'verbose', } }, 'loggers': { 'app': { 'handlers': ['app'], 'level': 'DEBUG', 'propagate': True, }, 'test': { 'handlers': ['test', 'test-fail'], 'level': 'DEBUG', 'propagate': True, }, }, } And let's just say I'm trying to log the following test … -
django admin save dosent work after starting new app
after starting a new app on existing django project, all models that contains files or img fields result to 404 page not found.. when trying to create a new object. Page not found (404) Request Method: POST Request URL: https://mysite.mysite.me/admin/checkout/pics/add/ Raised by: django.contrib.admin.options.add_view Using the URLconf defined in wstore.urls, Django tried these URL patterns, in this order: admin/ admin/ [name='home'] graphics/ [name='graphics'] video/ [name='video'] articles/ [name='articels'] dashboard/ [name='dashboard'] h [name='homeh'] graphicsh/ [name='graphicsh'] api/ checkout/ [name='checkout'] products/ [name='products'] product/ [name='product'] addcart/ [name='addcart'] removecart/ [name='removecart'] cart/ [name='viewcart'] onsale/ [name='onsale'] test// checktest/ [name='checktest'] leaders/ [name='leaders'] about/ [name='about'] plans/ [name='plans'] accounts/ ^media/(?P.*)$ ^static/(?P.*)$ The current path, checkout/pics/add/, didn't match any of these. You're seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page. -
AttributeError: 'tuple' object has no attribute '_meta' error in Django
I'm trying to make a webpage for signing up in django, but I can't get around this error: from accounts.forms.forms import AuthForm, SignUpForm File "C:\Users\tonik\OneDrive\Plocha\Python projects\chytry-lock-master\smartlock\accounts\forms\forms.py", line 7, in class SignUpForm(UserCreationForm): File "C:\Users\tonik\AppData\Local\Programs\Python\Python36\lib\site-packages\django\forms\models.py", line 256, in new apply_limit_choices_to=False, File "C:\Users\tonik\AppData\Local\Programs\Python\Python36\lib\site-packages\django\forms\models.py", line 139, in fields_for_model opts = model._meta AttributeError: 'tuple' object has no attribute '_meta' my forms.py: from django import forms from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.forms import AuthenticationForm from django.forms.widgets import PasswordInput, TextInput class SignUpForm(UserCreationForm): email = forms.EmailField(required=True, help_text='Required. Please enter a valid e-mail address.') email = forms.EmailField(required=True, widget=TextInput(attrs={'class': 'span2', 'placeholder': 'e-mail'}), help_text='Required. Please enter a valid e-mail address.') class Meta: model = UserCreationFormFields = ('username', 'email', 'password1', 'password2') fields = "__all__" class AuthForm(AuthenticationForm): class Meta: model = AuthenticationForm def __init__(self, *args, **kwargs): super(AuthenticationForm, self).__init__(*args, **kwargs) for field in self.fields.values(): field.error_messages = {'required': '{fieldname} is required'.format(fieldname=field.label)} username = forms.CharField(widget=TextInput(attrs={'placeholder': 'nickname'})), email = forms.CharField(widget=TextInput(attrs={'placeholder': 'e-mail'})), password = forms.CharField(widget=PasswordInput(attrs={'placeholder':'password'})) my views: from django.shortcuts import render, redirect from django.contrib.auth.forms import UserCreationForm from django.contrib.auth import login, authenticate from smartlock.forms import SignUpForm def signup(request): if request.method == 'POST': form = UserCreationForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data.get('username') first_password = form.cleaned_data.get('password1') user = authenticate(username=username, password=first_password) login(request, user) return redirect('home') else: form = UserCreationForm() return render(request, 'signup.html', … -
Can't use DjangoRestFramework with Requests because of self-signed-cert in chain
I've got 2 Django applications that I need to be talking to each other via the DjangoRestFramework. The apps live on Windows Servers that run Apache to serve the data. They live on separate boxes within my infrastructure and here we use a self-signed cert for internal things because that's a requirement. When I try to make the request, it's upset with the self-signed-certificate in the chain and doesn't finish the request. I made a little utility function that reaches out to the API: def get_future_assignments(user_id): """gets a users data from the API Arguments: user_id {int} -- user_id for a User """ headers = { 'User-Agent': 'Mozilla/5.0', 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8', 'X-Requested-With': 'XMLHttpRequest' } api_app = settings.MY_API api_model = 'api_endpoint/' api_query = '?user_id='+str(user_id) json_response = requests.get( api_app+api_model+api_query, headers=headers, verify=False ) return json.loads(json_response.content) using verify=False allows the endpoint to run and give back appropriate data. If I remove that it will fail saying there is a self-signed-cert in the chain and not finish the call. The overall layout is like this: Server1: https - self-signed (server1.cer (making the call)) Server2: https - self-signed (server2.cer (api lives on this server)) I have the root certificate we install on browsers and such within the … -
How to fix "isinstance() arg 2 must be a type or tuple of types" error in Django
I created a Django (v. 2.1.5) model called Metric that has itself as an embed model, as you can see below: from djongo import models class Metric(models.Model): _id = models.ObjectIdField() ... dependencies = models.ArrayModelField( model_container='Metric', blank=True, ) def __str__(self): return self.name class Meta: db_table = 'metric' But, when I try to execute the code: for metric in Metric.objects.all(): I get the following error: File "/.../python3.6/site-packages/djongo/models/fields.py", line 235, in to_python if isinstance(mdl_dict, self.model_container): TypeError: isinstance() arg 2 must be a type or tuple of types I imagine that this error was caused by the use of single quotation marks on model_container assignment, but I can't remove it, since the model_container is the class itself. Also, I'm not sure if that is the reason. In any case, what I can do to fix this error? -
How to override field in create method only if it is provided
I have overridden the save method to inherit from a field of a different model. However, I want to inherit only if I am not passing the value of that field while creating the object. If the value is passed while creating the object, I don't want it to inherit. I have two models: Product having fields type (foreign key) and should_remove Type having fields name and should_remove When I create a new Product entry without passing should_remove it automatically inherits from the Type which is correct. type = Type.objects.create(name="open", should_remove=False) product = Product.objects.create(type=type) product.should_remove # False However, if I pass the should_remove field it still inherits from the Type type = Type.objects.create(name="open", should_remove=False) product = Product.objects.create(type=type, should_remove=True) product.should_remove # False My idea is to access the value of passed should_remove inside the save() method and set it only if it is passed. How do I access the passed value in the save method? def save(self, *args, **kwargs): # How do I access the passed should_remove here?? if not self.id: self.should_remove = self.type.should_remove super(Product, self).save(*args, **kwargs) -
Python/Django: on models.SET_NULL Cascade on_delete(), how to set other attribute value
I feel like this should be easy but I cannot seem to find a reference in the docs. I have a Django Model Resident that has a ForeignKey Property, when/if a user deletes that Property I have set the cascade to SET_NULL just because I feel it is best to not destroy this data. My issue is that there is a Resident Search feature to where I have active and inactive Residents, when a Property is deleted I need to be able to set the Resident.active attribute to 0 as well so those residents cannot login to the system anymore, or show up in my Search Feature, how do I do this? Here is the relevant portion of my Model in the event you need it: class Resident(models.Model): property_id = models.ForeignKey('Property', null=True, on_delete=models.SET_NULL, db_column='property_id') active = models.IntegerField(default=1) -
How to pass values with POST on Django?
I try to do a simple database interaction/crud thing with Django. For now, I just did a simple view to display the information from the database on an html table, and I'm trying to add a functionality that would add new informations to the database. For this, I have an input field for every table column present in the table, and an add button to add in the database. I wanted to make it work with a POST method. The POST request would be computed on the view that would add the new values on the database, and redirect on the page with the html table that will then display the added information. However, I didn't quite managed to find a solution to what I need to do. This is the views.py I have at the moment: from orders.models import Order #my model class OrdersList(TemplateView): template_name = "orderlist.html" def get_context_data(self, **kwargs): context = super(OrdersList, self).get_context_data(**kwargs) orders = Order.objects.all() #adding values from the model to the context context['orders'] = [] i = 0 for order in orders: context['orders'].append(i) context['orders'][i] = {} context['orders'][i]['id'] = i+1 context['orders'][i]['market_place'] = order.market_place context['orders'][i]['purchase_date'] = order.purchase_date context['orders'][i]['purchase_time'] = order.purchase_time context['orders'][i]['amount'] = order.amount context['orders'][i]['currency'] = order.currency i = … -
How to send server messages to dropzone
I am using Dropzone.js and Django to upload files and process it and show messages based on processes which are done in the server side, How I can send the messages from Django view to my dropzone component, I can see that there is a red cross when the server generates an error, how I can put my own message on that? This is my view: @login_required def upload_file(request): error='' if request.method == 'POST' and request.FILES['file'] : ##doing something and based on that generate error error='My message.....' return render(request,'app/inputFile_pannel.html', { 'error':error}) return render(request,'app/inputFile_pannel.html', { 'error':error}) and this is the dropzone options in the template file: Dropzone.options.myDropzone = { clickable:true, method:"post", withCredentials:true, paramName: 'file', autoProcessQueue :false, uploadMultiple:false, forceFallback:false } and this is the form in my template: <form method="POST" action="{% url 'upload_file' %}" enctype="multipart/form-data" class="dropzone" id="myDropzone" > {% csrf_token %} when I want to show the error using {{error}} in the template it doesn't work, when I change the forceFallback to true everything is working well and the errors are shown properly, but the form changes to simple file input and is not a dropzone any more. How I can send my messages from view to this template? could anybody help?