Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Command errored out with exit status 1: python setup.py egg_info Check the logs for full command output. Can anyone asssist
Hello how to resolve this ERROR: Command errored out with exit status 1: command: /usr/bin/python2.7 -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/tmp/pip-install-3zeNQM/mysqlclient/setup.py'"'"'; file='"'"'/tmp/pip-install-3zeNQM/mysqlclient/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(file);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, file, '"'"'exec'"'"'))' egg_info --egg-base /tmp/pip-pip-egg-info-41RbUT cwd: /tmp/pip-install-3zeNQM/mysqlclient/ Complete output (10 lines): sh: 1: mysql_config: not found Traceback (most recent call last): File "", line 1, in File "/tmp/pip-install-3zeNQM/mysqlclient/setup.py", line 17, in metadata, options = get_config() File "setup_posix.py", line 44, in get_config libs = mysql_config("libs_r") File "setup_posix.py", line 26, in mysql_config raise EnvironmentError("%s not found" % (mysql_config.path,)) EnvironmentError: mysql_config not found ---------------------------------------- ERROR: Command errored out with exit status 1: python setup.py egg_info Check the logs for full command output. -
How do I ensure my Profile Image is uploaded during registration?
I am trying to implement a simple Custom-User-Registration using django-rest-framework, django-allauth and dj-rest-auth. When I update my user details and add an Image the Image gets uploaded to the correct folder, but when I select the image during registration, the image is not uploaded. What am I doing wrong? This is my models.py from django.db import models from django.contrib.auth.models import AbstractUser GENDER_SELECTION = [ ('M', 'Male'), ('F', 'Female'), ] class CustomUser(AbstractUser): # email attribute is inherited from AbstractUser gender = models.CharField(max_length=20, choices=GENDER_SELECTION) phone_number = models.CharField(max_length=30) image = models.ImageField(upload_to='profile/', blank=True) This is my forms.py from django.contrib.auth import get_user_model from django.contrib.auth.forms import UserCreationForm, UserChangeForm class CustomUserCreationForm(UserCreationForm): class Meta: model = get_user_model() fields = ('email', 'username', 'phone_number', 'gender', 'image',) class CustomUserChangeForm(UserChangeForm): class Meta: model = get_user_model() fields = ('email', 'username', 'phone_number', 'gender', 'image',) This is my serializers.py from django.db import transaction from rest_framework import serializers from dj_rest_auth.registration.serializers import RegisterSerializer from dj_rest_auth.serializers import LoginSerializer as RestAuthLoginSerializer from users.models import GENDER_SELECTION from users.models import CustomUser class CustomRegisterSerializer(RegisterSerializer): gender = serializers.ChoiceField(choices=GENDER_SELECTION) phone_number = serializers.CharField(max_length=30) image = serializers.ImageField(max_length=None, use_url=True, allow_null=True, required=False) # Define transaction.atomic to rollback the save operation in case of error @transaction.atomic def save(self, request): user = super().save(request) user.gender = self.data.get('gender') user.phone_number = self.data.get('phone_number') user.image … -
How to login to Web Application with Golang
I'm a newbie go developer. I want to login into my django web application, here's my code for login into my web app (writen in Python): import requests from sys import argv as sys_argv from sys import exit as sys_exit from json import dumps as json_dumps def print_response(response): print("URL: %s\nStatus Code: %s\nCookies: %s\nHTTP Header:\n%s\n%s\n%s\nResponse:\n%s" %(response.url, response.status_code, response.cookies.get_dict(), "-"*20, json_dumps(response.headers.__dict__["_store"], indent=4), "-"*20, response.text)) # The URL try: url = sys_argv[1] except IndexError: print("Usage: %s <url>" %(sys_argv[0])) sys_exit(1) # Session session = requests.Session() # Form-Based Authentication if len(sys_argv) > 2: response = session.get(url) print_response(response) username = sys_argv[2] password = sys_argv[3] # Authentication header auth_header = {"user": username, "pass": password, "submit": "submit"} try: # Adding csrftoken required by django auth_header["csrfmiddlewaretoken"] = response.cookies["csrftoken"] except KeyError: pass response = session.post(url, data=auth_header) else: response = session.get(url) print_response(response) That code works fine. I've recreate that code in go. Here's the problem if i use the go application, when I login into my flask application it works fine, but if I login into my django application, it fails by sending me django RuntimeError (it doesn't happen if I login with my browser or my python application). So I think I have to add csrftoken just like in my … -
How to print data in template django of a diffrent table joined by foreign key?
Hello Everyone i have Two model first one is as following: class Item(models.Model): title = models.CharField(max_length=100) price = models.FloatField() bargainprice = models.FloatField(default=0) discount_price = models.FloatField(blank=True, null=True) category = models.CharField(choices=CATEGORY_CHOICES, max_length=2) label = models.CharField(choices=LABEL_CHOICES, max_length=1) slug = models.SlugField() description = models.TextField() image = models.ImageField() and i am getting this model data using the following view: class ItemDetailView(DetailView): model = Item template_name = "product.html" and in product.html i am accessing Item objects like this: <span class="mr-1"> <del>₹ {{ object.price }}</del> </span> <span>₹ {{ object.discount_price }}</span> {% else %} <span> ₹ <span id="pp">{{ object.price }}</span></span> and so on.. everything working fine up here. but problem arises when i created the following model: class BargainModel(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) itemId = models.IntegerField() bprice = models.FloatField() i joined this with foreign key as mentioned. **what i want to do is print the " bprice " in the product.html of the same user but i am not able to do it ** can anyone help me with this i am new to Django. Thanks in advance -
Django which template to extends with if block
I have two distincts template which must be extended in three diffrents page. Is there a solution to extends a template with if block? I tried this without success. {% if 'project' in request.get_full_path %} {% extends 'index.html' %} {% elif 'network' in request.get_full_path %} {% extends 'base.html' %} {% elif 'zoneset' in request.get_full_path %} {% extends 'base.html' %} {% endif %} -
'AnonymousUser' object has no attribute 'company'
Greeting, I am trying to add to User form a new CharField named company but even when the field is filled the data are not saved... I tried the following with no success as I got the error in the title. views.py def register(request): if request.method == "POST": form = NewUserForm(request.POST) if form.is_valid(): user_frm = form.save(commit = False) user_frm.company = request.user.company user_frm.save() username = form.cleaned_data.get('username') messages.success(request, f"Registration Complete! User: {username}") username = form.cleaned_data.get('username') login(request, user_frm) return redirect("main:homepage") else: for msg in form.error_messages: messages.error(request, f"{msg}:{form.error_messages[msg]}") return render(request = request, template_name = "main/register.html", context={"form":form}) form = NewUserForm return render(request, "main/register.html", context={"form":form}) forms.py class NewUserForm(UserCreationForm): email = forms.EmailField(required=True) company = forms.CharField( max_length= 500) class Meta: model = User fields = ("username", "email", "company", "password1", "password2") def save(self, commit=True): user = super(NewUserForm, self).save(commit=False) user.email = self.cleaned_data["email"] user.company = self.cleaned_data["company"] if commit: user.save() return user -
django -celery worker not receiving tasks
I am trying to send emails via Django celery but the tasks are not getting received by the celery. settings.py CELERY_BROKER_URL = 'redis://127.0.0.1:6379' CELERY_RESULT_BACKEND = 'redis://127.0.0.1:6379' CELERY_ACCEPT_CONTENT = ['application/json'] CELERY_RESULT_SERIALIZER = 'json' CELERY_TASK_SERIALIZER = 'json' CELERY_TIMEZONE = "UTC" tasks.py @app.task(name="send_activation_email") def send_activation_email(user): to = user.email user_id = user.id subject = 'Activate Your %s Account' % user.get_user_role_display() text_content = '' uid = urlsafe_base64_encode( force_bytes(user_id)) token = account_activation_token.make_token(user) c = ({'user': user, 'user_type': user.user_role, 'base_url': base_url, 'token': token, 'uid': uid, 'text_content': text_content}) html_content = get_template('mail/user/invite.html').render(c) msg = EmailMultiAlternatives( subject, text_content, from_email, [to]) msg.attach_alternative(html_content, "text/html") msg.send() views.py class SignUpView(generics.ListAPIView): authentication_classes = () permission_classes = () renderer_classes = (JSONRenderer, ) def post(self, request, user_role="employee",format=None, version=None): user = UsersSerializer(data=request.data,context={"user_role": user_role}) if user.is_valid(): t_user = user.save() send_activation_email.delay(t_user) message_data = custom_http_messages( code=200, message='You have successfully created your account.,data=user.data) return Response(message_data, status=message_data['code']) else: message_data = custom_http_messages( code=400, message='', data=user.errors) return Response(message_data, status=message_data['code']) Getting error it is working without the .delay function ie without celery. also the celery terminal is not receiving any tasks. -
billiard.exceptions.WorkerLostError: Worker exited prematurely: signal 9 (SIGKILL) without Docker
[2021-10-27 02:05:09,365: ERROR/MainProcess] Process 'ForkPoolWorker-5' pid:12871 exited with 'signal 9 (SIGKILL)' [2021-10-27 02:05:09,412: ERROR/MainProcess] Task handler raised error: WorkerLostError('Worker exited prematurely: signal 9 (SIGKILL).',) Traceback (most recent call last): File "/home/eps88-epixel/.local/share/virtualenvs/multi-purpose-platform-v-13-mfAjRgrr/lib/python3.6/site-packages/billiard/pool.py", line 1267, in mark_as_worker_lost human_status(exitcode)), billiard.exceptions.WorkerLostError: Worker exited prematurely: signal 9 (SIGKILL). Why does Django Celery show this error in the log? -
Make django auto convert to setting timezone
I've enabled USE_TZ as True and added TIME_ZONE as Asia/Calcutta in settings.py So when I am inputting a date like datetime(24, 11, 2021) it is stored in db as 2021-11-23T18:30:00+00:00 which is fine. But when I am getting the date in shell, it is not converting back in IST and just giving me datetime.datetime(2021, 11, 23, 18, 30, tzinfo=<UTC>) and whenever I have to display the date, it is showing 23 instead of 24 and I have to convert it manually everywhere. But strangely in django admin it is showing me IST dates but not in django shell or anywhere else. Is this the only way or I can have auto IST converted dates somehow? -
Django email: was connection to SMTP server established?
What I try to check if the connection was already opened, and if not, open it. I do connection = mail.get_connection() connection.open() to get the connection and open it. Then I send the emails and close it under some condition. Is there a way to check if the connection has already been opened? -
Difference between 'python -m pip install <package-name>' and 'pip install <package-name>'
I'm running into an issue where I'm trying to run a Django application within a virtual environment but it kept showing me errors regarding missing packages that need installation although I did install them previously using pip install <package-name>. The issues couldn't be resolved until I used python -m pip install <package-name> to install the missing packages. My question is what is the difference between the two commands? Does one of the commands install packages to the virtual environment and the other one does that globally? I'm confused. Side Note: Also when running pip freeze shows different installed packages than those showing when I run python -m pip freeze. -
Does it make sense to use django and npm in the same project?
I'm learning Django, I'm using Bootstrap etc. but I want to more customize for my website which build is bootstrap. I keep search and I saw that, if I want to customize bootstrap I should use bootstap-sass downloaded with npm. Well, my question is "Does it make sense to use django and npm in the same project?" or "Should I use a different method?" -
Django Database giving empty column where data is present in excel on uploading?
I am uploading an excel, where data is present. All the columns are filled in excel. But when I am uploading it in django, for multiple columns no data is coming in the django database. Here is my model.py class data(models.Model): sno = models.IntegerField(null=True) Date = models.DateField(null=True) Premium = models.FloatField(null=True) Count = models.IntegerField(null=True) Time = models.TimeField(null=True) Date_time = models.CharField(max_length = 100,null=True) Close = models.IntegerField(null=True) Premium_percentage = models.FloatField(null=True) Day = models.CharField(max_length=100) Here is the excel which I am trying to upload Sno Date Total_premium Count Time Date_time Close Premium% Day 479544 2021-10-13 360.65 2 14:22:00 2021-10-13 14:22:00 38735.25 0.93% Wednesday 479545 2021-10-13 357.7 2 14:23:00 2021-10-13 14:23:00 38727.3 0.92% Wednesday 479546 2021-10-13 356.35 2 14:24:00 2021-10-13 14:24:00 38739.7 0.92% Wednesday 479547 2021-10-13 353.85 2 14:25:00 2021-10-13 14:25:00 38750.4 0.91% Wednesday 479548 2021-10-13 355.65 2 14:26:00 2021-10-13 14:26:00 38730.25 0.92% Wednesday 479549 2021-10-13 354.6 2 14:27:00 2021-10-13 14:27:00 38723.15 0.92% Wednesday Here is the data that I am getting in the database enter image description here Columns which are coming empty are - SNO, PREMIUM, PREMIUM_PERCENTAGE. -
How to avoid "a lot of {%include%} gives a lot of <footer>"?
When I need to use a lot of {%include%} (content) in html templates - do unnecessary extensions appear for each content inclusion? Effects are also applied to each subsequent inclusion of content... When I can add content inclusion to the first html template expander, everything is fine. But when I use "pagination" I need to send "page=posts" to paginator.html. I can't find a way to send this variable to blog.html from layout.html... And I think that in the future I will have the same problems, and therefore it should be solved. layout.html <div class="container body-content"> <div id="content"> {% block content %} {% endblock %} </div> </div> <div class="container body-content"> <footer> <hr/> <p>&copy; {{ year }}. Сайт</p> </footer> </div> blog.html {% extends "app/layout.html" %} <!--♕--> {% block content %} <h2>{{ title }}</h2><br> {% for post in posts %} <hr> <div class=""> <h2> {{post.title}} </h2> <p> {{post.posted}} </p> </div> <p> <a href="{% url 'blogpost' parametr=post.id %}">{{ post.description }}</a> </p> {% endfor %} {% include "app/pagination.html" with page=posts %} {% endblock %} pagination.html {% extends "app/blog.html" %} <!--♕--> {% block content %} <div class="pagination"> <span class="step-links"> {% if page.has_previous %} <a href="?page={{ page.previous_page_number }}">Предыдущая</a> {% endif %} <span class="current"> Страница {{ page.number }} … -
How to open db.sqlite3 in Visual studio for django project
I want to use the db.sql 3 but when I open it is not reading the file. Moreover, I also downloaded SQLite extension but when I again click on db.SQLite 3 is nothing showing there. So please help me regarding this. -
Filter query on first many-to-many item
I would like the first! artist for the song to come from NL or BE. At the moment I'm querying all artists for a song. This is my query. Song.objects.filter(artists__country__code__in=['NL', 'BE']) and these are my models: class Song(Timestamps): uuid = models.UUIDField('UUID', unique=True) name = models.CharField('Name', max_length=255, blank=True) artists = models.ManyToManyField(Artist) ... class Artist(Timestamps): uuid = models.UUIDField('UUID', unique=True) name = models.CharField('Name', max_length=255, blank=True) country = CountryField(blank=True, null=True) ... I know that I can access the first item of the many-to-many field like this: song.artists.first() But I don't know how to do this in the query filter. Any ideas? Thanks in advance. -
Problem with a select that filters the other
I did all the filtering correctly from the frontend point of view, but in the backend I cannot save the data. This is the error: select a valid choise. That choice is not one of the available choices. I can't understand where the error is, I think in the fact that 'group_single' is passed in post from my view and therefore is not seen by the form. if 'gruppo_single' in self.data: try: gruppo_id = int(self.data.get('gruppo_single')) print("<----------ciao sono qui ------>", gruppo_id) self.fields['dati_esercizio'].queryset = models.Esercizi.objects.filter(gruppo_id = gruppo_id) except (ValueError, TypeError): pass else: print("<----------errore ------>") models.py class Gruppi(models.Model): nome_gruppo = models.CharField(max_length=100) class Esercizi(models.Model): nome_esercizio = models.CharField(max_length=100) gruppo = models.ForeignKey( Gruppi, on_delete = models.CASCADE, related_name = 'gruppo' ) class Schede(models.Model): nome_scheda = models.CharField(max_length=100) data_inizio = models.DateField() data_fine = models.DateField() utente = models.ForeignKey( User, on_delete = models.CASCADE, related_name = 'utente' ) class DatiGruppi(models.Model): giorni_settimana_scelta = [ ("LUNEDI","Lunedì"), ("MARTEDI","Martedì"), ("MERCOLEDI","Mercoledì"), ("GIOVEDI","Giovedì"), ("VENERDI","Venerdì"), ("SABATO","Sabato"), ("DOMENICA","Domenica") ] giorni_settimana = MultiSelectField( choices = giorni_settimana_scelta, default = '-' ) dati_gruppo = models.ForeignKey( Gruppi, on_delete = models.CASCADE, related_name = 'dati_gruppo' ) gruppi_scheda = models.ForeignKey( Schede, on_delete = models.CASCADE, related_name = 'gruppi_scheda' ) class DatiEsercizi(models.Model): serie = models.IntegerField() ripetizione = models.IntegerField() peso = models.DecimalField( max_digits = 4, decimal_places = 1, blank = … -
Not able to install tensorflow in Mac M1
I am trying to install tensorflow on my Mac M1 and I am getting the following error: ERROR: Could not find a version that satisfies the requirement tensorflow (from versions: none) ERROR: No matching distribution found for tensorflow I have python3- 3.9.7, pip- 21.3.1 -
how to migrate just specific table in django?
I tried multiple databases in django. So, I set databases like that # settings.py DATABASE_ROUTERS = [ 'stage1.routers.MultiDBRouter', ] DATABASE_APPS_MAPPING = { 'stage1': 'stage1', } DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', }, 'stage1': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'stage1', 'HOST': 'localhost', 'USER': 'root', 'PASSWORD': '######', 'PORT': 3306, 'CHARSET': 'utf8mb4', }, } # stage1.routers.py class MultiDBRouter(object): def __init__(self): self.model_list = ['stage1'] def db_for_read(self, model, **hints): if model._meta.app_label in self.model_list: return model._meta.app_label return None def db_for_write(self, model, **hints): if model._meta.app_label == 'stage1': return 'stage1' return None def allow_relation(self, obj1, obj2, **hints): if (obj1._meta.app_label in self.model_list or obj2._meta.app_label in self.model_list): return True return None def allow_migrate(self, db, app_label, model_name=None, **hints): if app_label == 'stage1': return db == 'stage1' return None # stage1.models.py from django.db import models class Room(models.Model): name = models.CharField(max_length=100) sort = models.CharField(max_length=100) class Meta: app_label = "stage1" I did manage.py migrate --database=stage1 and it worked. But there are something wrong I didn't intend. I just wanted stage1 database has only one table room. But it has all tables that are basically set like auth_group, django_session ... How can I do to make only one table room in stage1 database? Please help me. -
Swedish BankID QR code Server/Client Interaction in Django
This post is related to my last post BankID has the ability to offer animated QR code generation for authorization. It generates a new QR every second and you scan with a mobile app and then their server returns a success once the user enters their code or scans their fingerprint. You can just skip the QR code and have bankID ping the user to enter their code to auth, but I want to have the QR code functionality for my app. Now my question is this. When the POST request is sent Views gets a qr_start_token, and qr_start_secret returned from the bankID server. Views is waiting for a status change from the BankID server to do something, but that leaves me at a lost on how I can render the changing QR code on the client. How can I do this without rendering a new page, passing the secret through context and using javascript to replicate this process? Here is the relevant code: if request.META['HTTP_USER_AGENT']: ua_string = request.META['HTTP_USER_AGENT'] user_agent = parse(ua_string) if user_agent.is_pc: status=client.collect(order_ref=auth["orderRef"])["status"] order_time = time.time() while status == "pending": qr_start_token = auth["qrStartToken"] qr_start_secret = auth["qrStartSecret"] print(qr_start_secret) qr_time = str(int(time.time() - order_time)) qr_auth_code = hmac.new(qr_start_secret.encode(), qr_time.encode(), hashlib.sha256).hexdigest() qr_data … -
Django admin on many-to-many relation: Variant-category relationship with this Variant and Category already exists
In Django admin if i select new field in inline of category which is many to many relation with variant, if i select the same category it raise error Variant-category relationship with this Variant and Category already exists. How would i select new inline field with same category for many to many field. Here's my code Admin.py class VariantInline(admin.TabularInline): model = Variant.category_id.through extra = 0 @admin.register(Category) class CategoryAdmin(ImportExportModelAdmin): ... inlines = [VariantInline] Models.py class Category(models.Model): category_id = models.AutoField(primary_key=True) category_name = models.CharField(max_length=50) ... class Variant(models.Model): ... variant_id = models.AutoField(primary_key=True) category_id = models.ManyToManyField(Category) -
"'Request' object has no attribute 'learner'": Django Restframework
There is an error in my code "'Request' object has no attribute 'learner'". Here, My requirement is "request.learner" is empty then call "CDetailsSerializer" otherwise call "CourseDetailsSerializer". def list(self, request, **kwargs): try: queryset = self.get_queryset() queryset = self.filter_queryset(queryset) if not request.learner: serializer = CDetailsSerializer(queryset, many=True) else: serializer = CourseDetailsSerializer(queryset, many=True) print('s', serializer.data) response_data = {'course': serializer.data} return self.jp_response(s_code='HTTP_200_OK', data=response_data) except Exception as e: print(e) return self.jp_error_response('HTTP_500_INTERNAL_SERVER_ERROR', 'EXCEPTION', [str(e), ]) Here always calling (else part) CourseDetailsSerializer, but in some situations, I also want to call (if part) CDetailsSerializer.Give me a solution to fix this. -
django factory using a factory gives "Database access not allowed"
I want to create a user_profile from a factory called UserProfileFactory which uses a User object from UserFactory. the error is: RuntimeError: Database access not allowed, use the "django_db" mark, or the "db" or "transactional_db" fixtures to enable it. here are the relivant classes. from django.contrib.auth import get_user_model from factory import Faker, post_generation from factory.django import DjangoModelFactory class UserFactory(DjangoModelFactory): username = Faker("user_name") email = Faker("email") name = Faker("name") @post_generation def password(self, create: bool, extracted: Sequence[Any], **kwargs): password = ( extracted if extracted else Faker( "password", length=42, special_chars=True, digits=True, upper_case=True, lower_case=True, ).evaluate(None, None, extra={"locale": None}) ) self.set_password(password) class Meta: model = get_user_model() django_get_or_create = ["username"] class UserProfileFactory(DjangoModelFactory): user = UserFactory.create() #### the problem line ### country = Faker("country") # which laws apply birth_date = Faker("date_of_birth") # in the US you can't collect data from <13yo's class Meta: model = UserProfile and in the tests/test.py class TestUserProfileDetailView(): def test_create_userprofile(self): """creates an APIRequest and uses an instance of UserProfile to test a view user_detail_view""" factory = APIRequestFactory() request = factory.get('/api/userprofile/') request.user = UserProfileFactory.create() # problem starts here # response = user_detail_view(request) self.assertEqual(response.status_code, 200) -
Empty lines in form-select django template
i have a choice form, the user has to select a country from a dropdownlist. my html code: <div class="mb-3"> <label for="{{ profile_form.country.id_for_label }}" id="country_label" class="form-label">Country</label> <select class="form-select" name="{{ profile_form.country.html_name }}" id="{{ profile_form.country.id_for_label }}"> {% for country in profile_form.counry %}<option>{{ country }}</option>{% endfor %} </select> </div> But in html i get a dropdown with a empty line between every country: -Usa -emptyline -Germany -emptyline How can i get rid of those empty lines ? -
Can the APIRequestFactory create a request with data and user attributes
I'm trying to make a unit test for a function that takes a django Request object as a parameter; the Request object being one of the params from a Django class based view method. From the request object param, it's assumed there is a data and user attribute. My problem is that I can't replicate the request object using DRF's APIRequestFactory. When I'm using the python requests package and I do something like headers = { 'Authorization': "Token {}".format(settings.AUTH_TOKEN), 'Accept': 'application/json', 'Content-Type': 'application/json', } data['foo'] = foo_id response = requests.post( '{}/api/foo/{}/action/'.format(settings.ROOT_URL, foo_id), headers=headers, json=data) Then the user and data attribute exist in the request object of the class based views. If, however, I use DRF's APIRequestFactory and do data = {"foo_id": 1234} factory = APIRequestFactory() request = factory.post('/api/foo/1/action/', data, format="json") ...then I have to explicitly add request.user = user request.data = data Only the body attribute as data, and thats as a bytestream e.g. body: b'{"foo_id":"1234"}' Is what I'm trying to do possible? As an aside, it could also be that I'm violating the law of demeter and that my function being tested should be taking a dict and a user object as params instead of an entire request object, …