16๐
I was trying to do the same myself but found out that Django Test Client does not set the user in the request and it is not possible to set request.user
while using Client
any other way. I used RequestFactory
to that.
def setUp(self):
self.request_factory = RequestFactory()
self.user = User.objects.create_user(
username='javed', email='javed@javed.com', password='my_secret')
def test_my_test_method(self):
payload = {
'question_title_name': 'my first question title',
'question_name': 'my first question',
'question_tag_name': 'first, question'
}
request = self.request_factory.post(reverse('home'), payload)
request.user = self.user
response = home_page(request)
More about request factory here
๐คJaved
12๐
Try this:
from django.test import TestCase, Client
from django.contrib.auth.models import User
class YourTestCase(TestCase):
def test_profile(self, user_id):
user = User.objects.create(username='testuser')
user.set_password('12345')
user.save()
client = Client()
client.login(username='testuser', password='12345')
response = client.get("/account/profile/{}/".format(user.id), follow=True)
self.assertEqual(response.status_code, 200)
Here, I first create the user and set the login credentials for the user. Then I create a client and login with that user. So in your views.py, when you do request.user
, you will get this user.
๐คSarin Madarasmi
- Git push heroku master: Heroku push rejected, no Cedar-supported app detected
- Django datetime field โ convert to timezone in view
- How do I hide the field label for a HiddenInput widget in Django Admin?
- Is there any way to use GUIDs in django?
- Combining multiple Django templates in a single request
- Django 1.7 removing Add button from inline form
- Field choices() as queryset?
- Disable caching for a view or url in django
2๐
If you use django.test
you can do something like that:
self.client.force_login(user)
๐คDainius
- Paypal monthly subscription plan settings for first day of the month and making monthly recurring payment โ django python
- What is the difference between south migrations and django migrations?
- How can I schedule a Task to execute at a specific time using celery?
0๐
If you have a response, you can access response.context['user']
.
If you need a response object, just call any view that will create a context, e.g. response = self.client.get('/')
.
๐คarcanemachine
- Display foreign key columns as link to detail object in Django admin
- Pycharm (Python IDE) doesn't auto complete Django modules
Source:stackexchange.com