I have been working on a Django REST API and one of the views is as follows :
#api_view(['POST'])
def create(request):
key = request.POST.get('key')
name = request.POST.get("name")
email = request.POST.get("email")
password = request.POST.get("password")
print(key)
if(key=='0'):
user = Users(name=name,email=email,password=password)
user.save()
return Response("User Created Successfully")
else:
return Response("Invalid Key")
When I send a POST request with all the proper parameters I get the key printed as NONE, but I tried replacing POST with GET every where as below and then sending a GET request actually works normally, but POST request isn't working :
#api_view(['GET'])
def create(request):
key = request.GET.get('key')
name = request.GET.get("name")
email = request.GET.get("email")
password = request.GET.get("password")
print(key)
if(key=='0'):
user = Users(name=name,email=email,password=password)
user.save()
return Response("User Created Successfully")
else:
return Response("Invalid Key")
Thanks in advance !!
Tried GET instead of POST and that works, but since this is a method to enter value in the DB so this should be POST request.
[Edit 1]
I have tried using request.data but that isn't working, it is returning empty request like this {} and the same is the case with request.POST.
I am sending the request from Postman.
The request I am sending is like this :
In your screenshot, you are passing query parameters in POST request. You should POST data though data tab in postman (formdata,json,etc). Based on your screenshot, you can get the data passed through request.query_params, but this is not recommended for POST requests.
In Django REST Framework, request.POST or data submitted through POST is restructured into request.data and data through GET requests is passed into request.query_params. Both of these are QueryDict, so normal dictionary methods are applicable.
Reference: https://www.django-rest-framework.org/api-guide/requests/#request-parsing
Related
After testing on postman i get the right response but when i pushed the code for the frontend guys, I get a report that it's always returning false...
views.py
# Check authentication status
def check(request):
data = {}
if request.user.is_authenticated:
data['response'] = 'user is authenticated'
data['name'] = request.user.name
data['email'] = request.user.email
data['phone_number'] = request.user.phone_number
data['id_user'] = request.user.id_user
data['passed_kyc'] = request.user.passed_kyc
else:
data['response'] = 'user is not authenticated'
return JsonResponse(data)
It probably depends on what value they expect from the response, so ask them to show you the code or to tell you what key/value pair they expect from the response, and what values they expect to mean "true" or "false"
For example, if they expect a key "isAuthenticated" and a value of either "true/false", then you should be adding:
data['isAuthenticated'] = True/False #depending on whether user is authenticated or not
I'm having my view
def my_wishlist(request):
user = request.user
user_products = WishlistProductPrices.objects.filter(user=user).all()
### Create filters ###
filter = get_user_filter_fields_wishlist(user_products)
filter = filter(request.GET,queryset = user_products)
if request.method == "POST":
post_form = MyForm(request.POST)
if post_form.is_valid():
#do stuff
form = MyForm()
context = {
"form":form,
"filter":filter
}
return render(request, "myapp/add_wishlist.html",context=context) #Returns POST, seems like
else:
#invalid post_form
context = {
"form":post_form,
"filter":filter
}
return render(request, "myapp/add_wishlist.html",context=context)
else: #Get request
form = MyForm()
context = {
"form":form,
"filter":filter
}
return render(request, "myapp/add_wishlist.html",context=context)
it works like a charm, but after the user has submitted something, and presses F5 the "do you want to resend the information again" pops-up.
I find it weird, since I assume the render(request,"mypp/add_wishlist.html) ad the bottom of the page would return a GET request?
render simply renders the template, and wraps this in a HttpResponse and returns that as response to the HTTP request, regardless what that request is.
This means that if the form is valid, and you render a response back, then refreshing will normally make the same HTTP request. This thus means that a person who makes an order can for example make a second order by just refreshing the webpage.
As a result in case of a successful request (so where the form is valid), one implements the Post/Redirect/Get architectural pattern [wiki]. In that case, it does not render a template, but it returns a redirect response (a response with status code 302), and thus asks the browser to make a GET request to the passed url.
You can make such redirect with the redirect(…) function [Django-doc].
I have a few questions regarding tokens and username/pass pairs.
I have a django rest API set up which uses tokens once a user has registered. However I do not know how to return the token to the user in a safe matter? Currently I use:
response_data = UserSerializer(instance=new_user).data
response_data['token'] = token.key
return Response(response_data, status=status.HTTP_201_CREATED)
But in this way i can clearly see all of the details in my Response body in the browser? Even my password. How should I return it to the client ?
When registering a User I do it this way:
serialized = UserSerializer(data=request.DATA)
if serialized.is_valid():
print(serialized.validated_data)
new_user = get_user_model().objects.create(**serialized.validated_data)
token = Token.objects.create(user=new_user)
Will this create my user properly ? Will the password be hashed?
Thank you
P.S. here is the whole method:
#api_view(['POST'])
def register_user(request):
print (request)
serialized = UserSerializer(data=request.DATA)
if serialized.is_valid():
print(serialized.validated_data)
new_user = get_user_model().objects.create(**serialized.validated_data)
token = Token.objects.create(user=new_user)
response_data = UserSerializer(instance=new_user).data
response_data['token'] = token.key
return Response(response_data, status=status.HTTP_201_CREATED)
else:
return Response(serialized._errors, status=status.HTTP_400_BAD_REQUEST)
I would handle #1 by setting a cookie, if that works for your use case. Relevant SO Post: How to set cookie in Django view and then render template.
For #2, I believe you should use create_user rather than create. Check the Django docs here. A quick way to check and see if your passwords are getting hashed properly is to pop open a shell, grab a user object, and see what the password looks like:
>>u = User.objects.get(id=1)
>>u.password
u'pbkdf2_sha256$12000$e30c2ea7a76f83b7c1a975ddc24286b675e714ebbbc72ccd5f0401730231ab57'
You will easily be able to tell whether or not the password has been hashed.
I have built a Django webpage with a text area and I would like a user of the site to be able to tweet the content of the text area.
I have been able to post on my own account (with developer credentials), however I'm having trouble extracting the user's secret token (gained after logging in with python social auth), and without this they cant make a post.
The problem seems to be that the secret token cannot be found in the dictionary that holds this information. Bearing in mind that login via OAuth works correctly; what is it past this point, that I am not doing, or doing incorrectly that means that 'oauth_secret_token' cannot be found/ does not exist?
views.py
def form_handle(request):
form = MyForm()
if request.method=='POST':
form = MyForm(request.POST)
if form.is_valid():
cd = form.cleaned_data
text = cd.get('text')
if 'tweet' in request.POST:
user = request.user
soc = user.social_auth.get(provider='twitter')
access_token = soc.extra_data['access_token']
access_secret = soc.extra_data['oauth_token_secret'] <-- error generated here.
post_tweets().post_my_tweet(text, access_token, access_secret)
form = MyForm()
return render(request, 'hello.html',{'form':form})
else:
form = MyForm()
return render(request, 'hello.html',{'form':form})
twitter_posting.py
from twitter import *
class post_tweets():
ckey= "XXXXXXXXXXXXX"
csecret= "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
def post_my_tweet(self, tweet, atoken, asecret):
t = Twitter(auth=OAuth(atoken, asecret, self.ckey, self.csecret))
t.statuses.update(status= str(tweet))
EDIT:
I have read the Tweepy documentation here: http://docs.tweepy.org/en/v3.2.0/auth_tutorial.html
And Twython documentation here: https://twython.readthedocs.org/en/latest/usage/basic_usage.html#updating-status
I am convinced that both of these libraries would be able to help me, however cant work out how to apply it to my code. Would someone from one of these comunities be able to give me an example of how I can modify this so it tweets from the users account?
The answer is that the oauth token and secret are inside the second dimension of a 2d dictionary. The key to the dictionary is called 'access_token' it holds five KV pairs with keys: 'oauth_token', 'oauth_token_secret', 'x_auth_expires', 'user_id', and 'screen_name'.
This therefore is how you post to twitter from a users account using django:
views.py
def form_handle(request):
form = MyForm()
if request.method=='POST':
form = MyForm(request.POST)
if form.is_valid():
cd = form.cleaned_data
text = cd.get('text')
if 'tweet' in request.POST:
user = request.user
soc = user.social_auth.get(provider='twitter')
access_token = soc.extra_data['access_token'] ['oauth_token'] <-- changed
access_secret = soc.extra_data['access_token']['oauth_token_secret'] <-- changed
post_tweets().post_my_tweet(text, access_token, access_secret)
form = MyForm()
return render(request, 'hello.html',{'form':form})
else:
form = MyForm()
return render(request, 'hello.html',{'form':form})
twitter_posting.py is unchanged from the question above. If you would like to view the twitter data returned upon login you can create a custom pipeline that prints out all the data (this is how I solved the problem). Without turning this into a pipeline tutorial I've added some helpful links below.
http://psa.matiasaguirre.net/docs/pipeline.html
https://github.com/omab/python-social-auth/tree/master/social/pipeline
This is my view that I want to be tested.
def logIn(request):
"""
This method will log in user using username or email
"""
if request.method == 'POST':
form = LogInForm(request.POST)
if form.is_valid():
user = authenticate(username=form.cleaned_data['name'],password=form.cleaned_data['password'])
if user:
login(request,user)
return redirect('uindex')
else:
error = "Nie prawidlowy login lub haslo.Upewnij sie ze wpisales prawidlowe dane"
else:
form = LogInForm(auto_id=False)
return render_to_response('login.html',locals(),context_instance=RequestContext(request))
And here's the test
class LoginTest(unittest.TestCase):
def setUp(self):
self.client = Client()
def test_response_for_get(self):
response = self.client.get(reverse('logIn'))
self.assertEqual(response.status_code, 200)
def test_login_with_username(self):
"""
Test if user can login wit username and password
"""
user_name = 'test'
user_email = 'test#test.com'
user_password = 'zaq12wsx'
u = User.objects.create_user(user_name,user_email,user_password)
response = self.client.post(reverse('logIn'),data={'name':user_name,'password':user_password},follow=True)
self.assertEquals(response.request.user.username,user_name)
u.delete()
And when i run this test i got failure on test_login_with_username:
AttributeError: 'dict' object has no attribute 'user'
When i use in views request.user.username in works fine no error this just fails in tests. Thanks in advance for any help
edit:Ok I replace the broken part with
self.assertEquals(302, response.status_code)
But now this test breaks and another one too.
AssertionError: 302 != 200
Here is my code for the view that now fail. I want email and username to be unique.
def register(request):
"""
Function to register new user.
This function will have to care for email uniqueness,and login
"""
if request.method == 'POST':
error=[]
form = RegisterForm(request.POST)
if form.is_valid():
username = form.cleaned_data['username']
email = form.cleaned_data['email']
if form.cleaned_data['password'] == form.cleaned_data['password_confirmation']:
password = form.cleaned_data['password']
if len(User.objects.filter(username=username)) == 0 and len(User.objects.filter(email=email)) == 0:
#email and username are bouth unique
u = User()
u.username = username
u.set_password(password)
u.email = email
u.is_active = False
u.is_superuser = False
u.is_active = True
u.save()
return render_to_response('success_register.html',locals(),context_instance=RequestContext(request))
else:
if len(User.objects.filter(username=username)) > 0:
error.append("Podany login jest juz zajety")
if len(User.objects.filter(email=email)) > 0:
error.append("Podany email jest juz zajety")
else:
error.append("Hasla nie pasuja do siebie")
#return render_to_response('register.html',locals(),context_instance=RequestContext(request))
else:
form = RegisterForm(auto_id=False)
return render_to_response('register.html',locals(),context_instance=RequestContext(request))
And here is the test that priviously work but now it is broken
def test_user_register_with_unique_data_and_permission(self):
"""
Will try to register user which provided for sure unique credentials
And also make sure that profile will be automatically created for him, and also that he he have valid privileges
"""
user_name = 'test'
user_email = 'test#test.com'
password = 'zaq12wsx'
response = self.client.post(reverse('register'),{'username': user_name,'email':user_email,
'password':password,'password_confirmation':password},follow=True)
#check if code is 200
self.assertEqual(response.status_code, 200)
u = User.objects.get(username=user_name,email = user_email)
self.assertTrue(u,"User after creation coudn't be fetched")
self.assertFalse(u.is_staff,msg="User after registration belong to staff")
self.assertFalse(u.is_superuser,msg="User after registration is superuser")
p = UserProfile.objects.get(user__username__iexact = user_name)
self.assertTrue(p,"After user creation coudn't fetch user profile")
self.assertEqual(len(response.context['error']),0,msg = 'We shoudnt get error during valid registration')
u.delete()
p.delete()
End here is the error:
AssertionError: We shoudnt get error during valid registration
If i disable login test everything is ok. How this test can break another one? And why login test is not passing. I try it on website and it works fine.
The documentation for the response object returned by the test client says this about the request attribute:
request
The request data that stimulated the response.
That suggests to me one of two things. Either it's just the data of the request, or it's request object as it was before you handled the request. In either case, you would not expect it to contain the logged in user.
Another way to write your test that the login completed successfully would be to add follow=False to the client.post call and check the response code:
self.assertEquals(302, response.status_code)
This checks that the redirect has occurred.
response.request is not the HttpRequest object in the view you are expecting. It's a dictionary of data that stimulated the post request. It doesn't have the user attribute, hence the AttributeError
You could rewrite your test to:
use the RequestFactory class introduced in Django 1.3 and call logIn in your test directly instead of using client.post.
inspect client.session after the post to check whether the user has been logged in.
Why one failing test can break another
When you edited the question, you asked
How this test can break another one?
The test_login_with_username was failing before it reached u.delete, so the user created in that test was not deleted. That caused test_user_register_with_unique_data_and_permission because the user test already existed.
If you use the django.test.TestCase class, the database will be reset in between each test, so this wouldn't be a problem.