Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Reverse for 'about_abc' with arguments '('',)' not found
I am trying to set up web app. I am having issues with passing host_id to template .html file i get: Reverse for 'about_abc' with arguments '('',)' not found. 1 pattern(s) tried: ['itpassed\\/(?P<host_id>[0-9]+)\\/about\\/$'] inter.html <li><a href="{% url 'about_abc' host_id %}">about</a></li> When i use "1" instead of "host_id" its working, but it can't stay hardcoded like this. views.py from django.shortcuts import render import warnings import requests import json from django.http import HttpResponse from django.template import loader from .models import Host [...] def inter(request, host_id): return render(request, 'itpassed/inter.html') def about_abc(request, host_id): response = requests.get( 'abc.net:1768/abc/api/v1/about', verify='/cert/cacerts.pem', headers={'Accept': 'application/json', 'Authorization': 'Basic xxxxxxxxxxxxxxxxxxxxxx'}, ) return HttpResponse(response.content) urls.py from django.urls import path from .models import Host from . import views urlpatterns = [ path('', views.index, name='index'), path('<int:host_id>/', views.inter, name='inter'), path('<int:host_id>/about/', views.about_abc, name='about_abc'), ] How to fix this? As far as i can see views.py should pass host_id to template. Why hardcoded "1" works but, host_id don't? thanks -
Custom writable field in ModelSerializer
I'd like to add a custom field to a serializer that's used when creating resources. It's not a model field. I tried the following: class CampaignSerializer(ModelSerializer): class Meta: model = Campaign fields = ("groups",) write_only_fields = ("groups",) groups = ListField(IntegerField(), min_length=1) def validate(self, data): # ... return data However groups doesn't exist in data in the validate() function. I found out that DRF sets read_only=True for the field, which is definitely not what I want. Is there a way to specify a writable field, or do I have to resort to the view set's perform_create() method? -
How to use different language for date_trunc by month in Django using Postgresql?
How do I print month names using different language? to_char(date_trunc( 'month', date) , 'MON-YYYY') AS date -
Why does Javascript keeps changing my data?
I need to plot data using chart.js but the data keeps on changing from the original data from python. At this point, I don't know what to do because my charts don't look anything alike between python and chart.js. Quick context: I have a python script that's generating data that I want to plot using chart.js on a site. For this, I use Django to pass the data as context to an HTML template where I plot it using chart.js. However, I noticed a significant difference between plots displayed by python and javascript. I took a quick look at the data itself and noticed that it changed. So I pass the data like that : var X = {{ X }} var F = {{ F }} console.log(F) var F_ridge = {{ F_ridge }} var F_lasso = {{ F_lasso }} var F_elastic = {{ F_elastic }} Here's the output for the first item of my python array : >>> 1.00024861720107 and here's the output of the first item of my javascript array : 1.0002486171243539 I know that it is a very little difference but it is enough to cause discrepancies in the plots. Do you know what causes the change … -
Django CSRF Failed: CSRF token missing or incorrect
I'm using Django Rest Framework and also django-rest-auth. I've the standard API endpoints (/login, /logout, /registration...) With my browser, I can login/list my users/logout. With Insomnia (a API requester), I can't login/logout, I've the error "CSRF Failed: CSRF token missing or incorrect" Maybe I need to add the CSRF header, but honestly I don't know where to find this CSRF token... Maybe I need to add some things (@csrf_protect ?) to login endpoint, but am I forced to rewrite completely the default view ? -
Django - post_delete signal for every single model in my app
I have a Notification model which makes use of Django generic foreign keys so I can notify users. class Notification(models.Model): target_ct = models.ForeignKey(ContentType, on_delete=models.CASCADE) target_id = models.CharField(max_length=36) target = GenericForeignKey('target_ct', 'target_id') target_user = models.ForeignKey(User, on_delete=models.CASCADE) I'd like to delete all the related notifications when the object that generates such notifications is deleted. So far, I've achieved that using a post_delete signal for each model, such as. @receiver(post_delete, sender=Model1) def delete(sender, instance, *args, **kwargs): Notification.objects.filter(target_id=instance.id, target_ct=ContentType.objects.get_for_model(instance)).delete() @receiver(post_delete, sender=Model2) def delete(sender, instance, *args, **kwargs): Notification.objects.filter(target_id=instance.id, target_ct=ContentType.objects.get_for_model(instance)).delete() I have around 20 models, is there a way of generating a post_delete signal that works for every single model? -
Django: List items in database not displaying on the html template
As part of a Django project, I have the following code (html template) and views.py file, but the items that are in the database are not being displayed in the browser when I run the server. It simply displays an empty list with three items in it. I definitely have at least three items in the database as shown below: >>> from worldguestbook.models import GuestBookItem >>> GuestBookItem.objects.all() <QuerySet [<GuestBookItem: GuestBookItem object (1)>, <GuestBookItem: GuestBookItem object (2)>, <GuestBookItem: GuestBookItem object (3)>]> >>> html file code (this shows the bottom part of the html template code. Could the error be in the way the html is arranged?) <div id="mce-responses" class="clear"> <div class="response" id="mce-error-response" style="display:none"></div> <div class="response" id="mce-success-response" style="display:none"></div> </div> <div class="" style="position: absolute; left: -5000px;"><input type="text" name="b_410ed4e009d15301d90f6492b_753384883a" value=""></div> </form> <span class="form_nospam">Warning: The world will see your message</span> </div> <!--End mc_embed_signup--> </div> </div> <!-- /end of Row--> </div> <!-- End of container--> <ul> {% for guestbookitem in all_items %} <li> {{ GuestBookItem.content }} </li> {% endfor %} </ul> </body> </html> views.py code from django.shortcuts import render from django.http import HttpResponse from .models import GuestBookItem # Create your views here. def worldguestbookView(request): allguestbookitems=GuestBookItem.objects.all() return render(request, 'worldguestbook\worldguestbook.html',{'all_items' : allguestbookitems}) def loginView(request): return render(request, 'worldguestbook\login.html') models.py … -
How to make matrix like forms in Django
I want to make a matrix like data entry form in my Django app. Let's say the following are my models class Student(models.Model): name = models.CharField(max_length=100) def __str__(self): return self.name class Subject(models.Model): name = models.CharField(max_length=100) def __str__(self): return self.name class Mark(models.Model): student = models.ForeignKey(Student, on_delete=models.CASCADE) subject = models.ForeignKey(Subject, on_delete=models.CASCADE) mark = models.DecimalField(max_digits=4, decimal_places=1) Now I need to make a data entry form for Marks table in which all Student names to be prepopulated in rows (in the first column) and all Subjects to be prepopulated in columns (in the first row). Then the user should be able to update the marks of each student for each subject in the form table. The form should look something like this image. https://cloud.addictivetips.com/wp-content/uploads/2010/03/datasheet2.jpg How can this be made using Django? -
connection to ('/webapps/hello_django/hello/gunicorn.sock', 8000) failed: [Errno -2] Name or service not known
Hey folks i installed django gunicorn supervisor by following Michał Karzyński installation guide when i'm running gunicorn_start.bash script it showing below error. [2019-04-25 06:05:07 +0000] [9312] [DEBUG] connection to ('/webapps/hello_django/hello/gunicorn.sock', 8000) failed: [Errno -2] Name or service not known please help me guys thanks in advance. -
Django Channels chat application doesn't open thread if the user is same as the logged in admin
I am new to Django channels and I am following this tutorial on youtube https://www.youtube.com/watch?v=RVH05S1qab8 All the setup is working great, but now I have been bowled by a conflict in the video and the shared git hub code. In the video if you exactly freez on 47:44 it will show you a screen where 2 browser windows are open with the following urls, 127.0.0.1:8000/messages/jmitchell3/ 127.0.0.1:8000/messages/cfe/ Here note that cfe is the user logged into the django admin. Now the model manager code says the following, class ThreadManager(models.Manager): def by_user(self, user): qlookup = Q(first=user) | Q(second=user) qlookup2 = Q(first=user) & Q(second=user) qs = self.get_queryset().filter(qlookup).exclude(qlookup2).distinct() return qs def get_or_new(self, user, other_username): # get_or_create username = user.username if username == other_username: return None, False qlookup1 = Q(first__username=username) & Q(second__username=other_username) qlookup2 = Q(first__username=other_username) & Q(second__username=username) qs = self.get_queryset().filter(qlookup1 | qlookup2).distinct() if qs.count() == 1: return qs.first(), False elif qs.count() > 1: return qs.order_by('timestamp').first(), False else: Klass = user.__class__ user2 = Klass.objects.get(username=other_username) if user != user2: obj = self.model( first=user, second=user2 ) obj.save() return obj, True return None, False The view uses the method in the above manager like so, def get_object(self): other_username = self.kwargs.get("username") print(other_username) print(self.request.user) obj, created = Thread.objects.get_or_new(self.request.user, other_username) if obj … -
how to show, set the value for input filed in django form using forms in html <input value={{ value}} disabled> how to do it in django forms
i'm taking values from database table in views file and has to render those values to a form in template file which is created by using the forms class and i have to show those values for some fields and make them immutable. class OrderForm(forms.Form): pid=forms.IntegerField() pname=forms.CharField() pprice=forms.FloatField() person_name=forms.CharField(max_length=40) emailid=forms.EmailField() address=forms.CharField(max_length=40) city=forms.CharField(max_length=20) state=forms.CharField(max_length=20) zip=forms.IntegerField() card=forms.IntegerField() exp= forms.DateField() cvv=forms.IntegerField() def order(request,pk): pid=pk user_name=request.user.username qs=Product.objects.get(pid=pid) pname=qs.pname.format() list={'username':user_name,'pid':pid,'pname':pname} return render(request,'order.html',{'data':list}) i expect input filed with value that i passed by default which is immutable and when i submit i have to get same value i passed -
Serialize multiple InMemoryUploadedFile using ListField : Django REST Framework
How can I serialize multiple InMemoryUploadedFile using serializers.ListField() ?? code snippet #views.py @api_view(['POST', 'GET']) def create_post(request): if request.method == 'POST': altered_request_data = request.data.copy() in_memory_upload_files_list = [value for value in request.FILES.values()] altered_request_data['files'] = in_memory_upload_files_list serializer = PostSerializer(data=altered_request_data) serializer.is_valid(raise_exception=True) serializer.save() return Response(data=serializer.data, status=201) else: qs = Post.objects.all() serializer = PostSerializer(qs, many=True) return Response(serializer.data) #serilizers.py class PostSerializer(serializers.ModelSerializer): files = serializers.ListField(child=serializers.FileField(), write_only=True) class Meta: fields = '__all__' model = Post current response { "files": { "0": [ "The submitted data was not a file. Check the encoding type on the form." ] } } -
How to save array in django caches?
I am facing issues with saving arrays in django cache. When I retrieve the array [['hello',1],[2,3]] from django cache, it gets converted to [['hello', 1], [2, 3]]. Essentially, the single quotes get changed to ascii character code. This issue doesn't happen with simple strings. How can I avoid this issue? -
django easy thumbnails library installation problem
i installed Django easy_thumbnails package by pip but i still got error when i run the server using python manage.py runserver the error which appear apppat/hvenv/local/lib/python2.7/site-packages/easy_thumbnails/conf.py", line 21, in __init__ super(AppSettings, self).__init__(*args, **kwargs) TypeError: __init__() takes exactly 2 arguments (1 given what is should be the proble? -
Django pip install mysql client giving this error in pycharm
am getting this error when i run python install mysql ERROR: Complete output from command /Users/edwardnaftaly/testa1/bin/python -u -c 'import setuptools, tokenize;__file__='"'"'/private/var/folders/8g/kctpxnyj6tv2msksrnkfkhz40000gp/T/pip-install-k7y8vr8k/mysqlclient/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' install --record /private/var/folders/8g/kctpxnyj6tv2msksrnkfkhz40000gp/T/pip-record-127mgnt8/install-record.txt --single-version-externally-managed --compile --install-headers /Users/edwardnaftaly/testa1/include/site/python3.7/mysqlclient: ERROR: running install running build running build_py creating build creating build/lib.macosx-10.13-x86_64-3.7 creating build/lib.macosx-10.13-x86_64-3.7/MySQLdb copying MySQLdb/__init__.py -> build/lib.macosx-10.13-x86_64-3.7/MySQLdb copying MySQLdb/_exceptions.py -> build/lib.macosx-10.13-x86_64-3.7/MySQLdb copying MySQLdb/compat.py -> build/lib.macosx-10.13-x86_64-3.7/MySQLdb copying MySQLdb/connections.py -> build/lib.macosx-10.13-x86_64-3.7/MySQLdb copying MySQLdb/converters.py -> build/lib.macosx-10.13-x86_64-3.7/MySQLdb copying MySQLdb/cursors.py -> build/lib.macosx-10.13-x86_64-3.7/MySQLdb copying MySQLdb/release.py -> build/lib.macosx-10.13-x86_64-3.7/MySQLdb copying MySQLdb/times.py -> build/lib.macosx-10.13-x86_64-3.7/MySQLdb creating build/lib.macosx-10.13-x86_64-3.7/MySQLdb/constants copying MySQLdb/constants/__init__.py -> build/lib.macosx-10.13-x86_64-3.7/MySQLdb/constants copying MySQLdb/constants/CLIENT.py -> build/lib.macosx-10.13-x86_64-3.7/MySQLdb/constants copying MySQLdb/constants/CR.py -> build/lib.macosx-10.13-x86_64-3.7/MySQLdb/constants copying MySQLdb/constants/ER.py -> build/lib.macosx-10.13-x86_64-3.7/MySQLdb/constants copying MySQLdb/constants/FIELD_TYPE.py -> build/lib.macosx-10.13-x86_64-3.7/MySQLdb/constants copying MySQLdb/constants/FLAG.py -> build/lib.macosx-10.13-x86_64-3.7/MySQLdb/constants running build_ext building 'MySQLdb._mysql' extension creating build/temp.macosx-10.13-x86_64-3.7 creating build/temp.macosx-10.13-x86_64-3.7/MySQLdb clang -DNDEBUG -g -fwrapv -O3 -Wall -Qunused-arguments -Qunused-arguments -Dversion_info=(1,4,2,'post',1) -D__version__=1.4.2.post1 -I/usr/local/mysql/include -I/usr/local/include -I/usr/local/opt/openssl/include -I/usr/local/opt/sqlite/include -I/Users/edwardnaftaly/testa1/include -I/usr/local/Cellar/python/3.7.3/Frameworks/Python.framework/Versions/3.7/include/python3.7m -c MySQLdb/_mysql.c -o build/temp.macosx-10.13-x86_64-3.7/MySQLdb/_mysql.o xcrun: error: invalid active developer path (/Applications/Xcode.app/Contents/Developer), missing xcrun at: /Applications/Xcode.app/Contents/Developer/usr/bin/xcrun error: command 'clang' failed with exit status 1 ---------------------------------------- ERROR: Command "/Users/edwardnaftaly/testa1/bin/python -u -c 'import setuptools, tokenize;__file__='"'"'/private/var/folders/8g/kctpxnyj6tv2msksrnkfkhz40000gp/T/pip-install-k7y8vr8k/mysqlclient/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' install --record /private/var/folders/8g/kctpxnyj6tv2msksrnkfkhz40000gp/T/pip-record-127mgnt8/install-record.txt --single-version-externally-managed --compile --install-headers /Users/edwardnaftaly/testa1/include/site/python3.7/mysqlclient" failed with error code 1 in /private/var/folders/8g/kctpxnyj6tv2msksrnkfkhz40000gp/T/pip-install-k7y8vr8k/mysqlclient/ -
sending entire form in ajax and want to read entire form data in django
I am sending entire form in ajax and want to read entire form data in django $(document).ready(function(evt){ var frm = $('#myform'); $(document).on('submit','#myform',function(e){ e.preventDefault(); var thisForm=frm.serialize(); var action=frm.attr('action'); var method=frm.attr('method'); //var formData = new FormData($('#myform')[0]); // console.log("val is"+action); alert("vvvv"+action); //console.log("redmi rowef3grfwefwefjkfeo fem omfe owefm wepocm wpcm wocdm"+formData); $.ajax({ url: action, type: method, data: thisForm, success: function(data){ console.log('upload success!') alert(data) }, cache: false, enctype: 'multipart/form-data', processData: false }); }); }); i Am trying TO Get The data But Its Display Nothing on Page @csrf_exempt def process_file(request): if request.method == 'POST' and request.FILES.getlist('filename'): print (request.POST) cat_id = json.loads(request.body).get('path') print("RESULT: " + str(cat_id)) I want to read data in process_file function -
How to remove backslash in Django DB settings
I have been trying to link my mssql database to Django. When I run the Django server I get the error below. For normal query out of Django, it works fine, however, the Django doesnt even connect. My normal username when login into windows is kmoh from EMEA domain, when I normaly login into my windows account it looks like this: EMEA\kmoh but as you can see in the error it looks like this EMEA\kmoh. So How can I remove this another backslash? File "C:\ProgramData\Anaconda3\lib\site-packages\sql_server\pyodbc\base.py", line 307, in get_new_connection timeout=timeout) django.db.utils.InterfaceError: ('28000', "[28000] [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Login failed for user 'EMEA\\kmoh'. (18456) (SQLDriverConnect); [28000] [Microsoft][ODBC Driver 17 for SQL Server]Invalid connection string attribute (0); [28000] [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Login failed for user 'EMEA\\kmoh'. (18456); [28000] [Microsoft][ODBC Driver 17 for SQL Server]Invalid connection string attribute (0)") I am using these: Windows 10 django-pyodbc-azure: version 2.1 Django 2.1 Pyodbc: 4.0.25 my Django settings.py looks like this: DATABASES = { 'default': { 'ENGINE': 'sql_server.pyodbc', 'HOST': 'xxx', #has been hide for this post 'PORT': '1433', 'NAME': 'BBL_Result', 'OPTIONS': { 'driver': 'ODBC Driver 17 for SQL Server', }, }, } -
deadlock detected when trying to start server
I have a simple application where I am using both django and django-rest-framework. Quite often, when I try to start the local server (python manage.py runserver), I get the following exception: Watching for file changes with StatReloader Exception in thread Thread-1: Traceback (most recent call last): File "/project/venv/lib/python3.7/site-packages/django/template/utils.py", line 66, in __getitem__ return self._engines[alias] KeyError: 'django' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/usr/local/Cellar/python/3.7.2_2/Frameworks/Python.framework/Versions/3.7/lib/python3.7/threading.py", line 917, in _bootstrap_inner self.run() File "/usr/local/Cellar/python/3.7.2_2/Frameworks/Python.framework/Versions/3.7/lib/python3.7/threading.py", line 865, in run self._target(*self._args, **self._kwargs) File "/project/venv/lib/python3.7/site-packages/django/utils/autoreload.py", line 54, in wrapper fn(*args, **kwargs) File "/project/venv/lib/python3.7/site-packages/django/core/management/commands/runserver.py", line 117, in inner_run self.check(display_num_errors=True) File "/project/venv/lib/python3.7/site-packages/django/core/management/base.py", line 390, in check include_deployment_checks=include_deployment_checks, File "/project/venv/lib/python3.7/site-packages/django/core/management/base.py", line 377, in _run_checks return checks.run_checks(**kwargs) File "/project/venv/lib/python3.7/site-packages/django/core/checks/registry.py", line 72, in run_checks new_errors = check(app_configs=app_configs) File "/project/venv/lib/python3.7/site-packages/django/contrib/admin/checks.py", line 80, in check_dependencies for engine in engines.all(): File "/project/venv/lib/python3.7/site-packages/django/template/utils.py", line 90, in all return [self[alias] for alias in self] File "/project/venv/lib/python3.7/site-packages/django/template/utils.py", line 90, in <listcomp> return [self[alias] for alias in self] File "/project/venv/lib/python3.7/site-packages/django/template/utils.py", line 81, in __getitem__ engine = engine_cls(params) File "/project/venv/lib/python3.7/site-packages/django/template/backends/django.py", line 25, in __init__ options['libraries'] = self.get_templatetag_libraries(libraries) File "/project/venv/lib/python3.7/site-packages/django/template/backends/django.py", line 43, in get_templatetag_libraries libraries = get_installed_libraries() File "/project/venv/lib/python3.7/site-packages/django/template/backends/django.py", line 108, in get_installed_libraries for name in get_package_libraries(pkg): File "/project/venv/lib/python3.7/site-packages/django/template/backends/django.py", line 121, in … -
restful API using Django framework [on hold]
what is the best source of learning "restful API using Django".I have tried some tutorials available on youtube but it's not really helping. -
How to fix pagination after making a search for specific data in django_tables2
In my project I am using with success django_tables2 in order to achieve server side processing. The only thing that I do not know how to handle is that after searching, for example by name in a template rendering clients for my application, the search despite the fact that gives some returned results based on the name, it is not working properly if the result records are spread in more than one page based on my pagination. In other words, when I am clicking the 2(second page of my returned results), the app is showing all the pages concerning the clients 1 2 3 ...45 next (as i want to reach the /clients/ url, and not the 1 2 next structure for only the custom search data. This happening also when I am clicking the next and previous buttons. One easy solution It could be to increase my pagination limit in order to show all the possible results in one page, but this solution is not proper for big result sets. Is there any solution to avoid loading and showing all the pages in the search bar and only keeping the results of my custom search? url.py url(r'^clients/$', views.client_list, name='client_list'), … -
How to login user if specified cookie exists?
How to login user if specified cookie exists? for example: if user have cookie "auth_allowed=true" then make user logged into our website User id is the same for all requests, code should works for every request I have already tried this approach here but have no results with that. -
how to write a use defined function inside django models.py?
I had written a function inside models.py which will calculate percentage. But it not showing the calculated values. I have written a function called 'cal_amount' in models.py performed the calculation. return the value to the model field. But it showing None when i called. class Course(models.Model): price = models.FloatField("Price", blank=True, null=True) voucher_id = models.CharField(max_length=255,blank=True, null=True) voucher_amount = models.IntegerField(blank=True, null=True) discounted_amount = models.IntegerField(blank=True, null=True) def __str__(self): return self.course_name def cal_amount(self): self.discounted_amount = (self.voucher_amount/100)*self.price return self.discounted_amount What i want is calculated amount to be stored in discounted_amount. so i can use {{ obj.discounted_amount }} in html to view it along with actual price. Please suggest me a way. -
DRF APIView - How can I add help text to auto generated form?
I am working with Django Rest Framework and using APIView and serializer form to add new data. I want to add some help text to the form as tooltip. Since the form is auto generated, I need some help on how can I add this to the form. I am using ModelSerializer. This is how my serializer looks like class MySerializer(serializers.ModelSerializer): class Meta: Model = MyModel fields = ('id','name', ...) My form fields should have help texts. How can I add them? Thanks! -
connecting SQL server 2016 with django but getting error of Login failed for user username odbc azure
I am trying to connect sql-server version 2016 with django framework and when connecting SQL server management studio with right credentials then showing all database in it but when trying to do all this with django getting error and I have install pyodbc using pip and also install pyodbc-azure then setting database connectivity Tried to make new user and gave access to everything but getting same error 'default': { 'ENGINE': 'sql_server.pyodbc', 'NAME': 'oms', 'PORT': '1433', 'HOST': 'ADMINRG-EDOFT5N', 'USER': 'vikas', 'PASSWORD': '111111', 'DRIVER': 'ODBC Driver 13 for SQL Server' } But getting error [Microsoft][ODBC Driver 13 for SQL Server][SQL Server]Login failed for user 'deepak' odbc-azure -
How to handle Django messages middleware while testing post
I'm trying to test an UpdateView that add a message to the redirected success page. It seems my issue comes from messages because pytest returns: django.contrib.messages.api.MessageFailure: You cannot add messages without installing django.contrib.messages.middleware.MessageMiddleware My test code is: def test_authenticated_staff(self, rf): langues = LanguageCatalog.objects.create( lang_src='wz', lang_dest='en', percent='4' ) req = rf.get(reverse("dashboard.staff:lang-update", kwargs={'pk': langues.pk})) data = {'lang_src': 'it', 'lang_dest': 'en', 'percent': '34'} req = rf.post(reverse( "dashboard.staff:lang-update", kwargs={'pk': langues.pk}), data=data) req.user = UserFactory() resp = views.LangUpdateView.as_view()(req, pk=langues.pk) I precise that the MessageMiddleware is present in MIDDLEWARE settings. I use Django==2.0.13.