I have created a test which which would sent a post request to a url and the method called against that request makes few objects, my question is how do i get these created objects ?
def test_post(self):
response = self.c.post('/url/', {'name' : 'postname', 'content' : 'abc'})
while my view logic looks something like
Class MakePost():
def makePost(self, request, data):
object = Class()
object2 = AnotherClass()
return object
def get_success_url(self, request, user):
return '/post/'
You can check your created objects in you test like:
def test_post(self):
response = self.c.post('/url/', {'name' : 'postname', 'content' : 'abc'})
# assume the above call has created an Post and a Category objects. Let's check them out.
category = Category.objects.get(name='category')
post = Post.objects.get(name='postname')
self.assertEqual(post.content, 'abc')
self.assertEqual(post.category, category)
As your database is cleaned before every test_* method and contains no objects (except fixtures if you use any), there would be only one object with that name.
Related
class PreUpdateDeleteAPIView(APIView):
serializer_class = PreEditSerializer
queryset = Reserve.objects.all()
def post(self, request):
code = request.data()
"""''.join(code)"""
data = {
reverse('update-delete', args = [code] ,request=request)
}
return Response(data)
hello. i have an problem for converting querydict to string. what should i do now?
i have tried json.dump and several answers in SOF. but i didnt get my answer yet!
request.data is a property that returns a QueryDict, so you work with:
code = request.data
It however makes no sense to specify args=[code], since code is a dictionary-like structure.
Likely you need some value that corresponds to some key from the request.data, so something like:
code = request.data['code']
I have a Django rest framework API that gets a POST request and has a retrive method in the view.
I want that when the user presses the post button it will route the URL to the render created in the retrieve method of the view class.
code:
#views.py
class LocationInfoViewSet(ModelViewSet):
# Order all objects by id, reversed.
queryset = LocationInfo.objects.all().order_by('-id')
serializer_class = LocationInfoSerializer
def retrieve(self, request, *args, **kwargs):
"""
This method is used to get the last object created by the user and render a map associated with the
mission's name.
"""
data = self.queryset[0]
serialized_data = LocationInfoSerializer(data, many=False)
points = list(serialized_data.data.values())
assign_gdt1 = GeoPoint(lat=points[2], long=points[3])
assign_gdt2 = GeoPoint(lat=points[4], long=points[5])
assign_uav = GeoPoint(lat=points[6], long=points[7], elevation=points[-3])
# Geo locations from the POST request.
gdt1 = [assign_gdt1.get_lat(), assign_gdt1.get_long()]
gdt2 = [assign_gdt2.get_lat(), assign_gdt2.get_long()]
uav = [assign_uav.get_lat(), assign_uav.get_long(), assign_uav.get_elevation()]
mission_name = points[1]
try:
# Check if a file already exists in the DB.
HTMLFileInteractionWithDB.table = THREE_POINTS_TRINAGULATION
openfile = HTMLFileInteractionWithDB.return_file_from_db(mission_name=mission_name)
return render(request, openfile)
except:
# Create a new file if one does not exists.
# The main function Creates an HTML File to be rendered.
return render(request, main(gdt1, gdt2, uav,
gdt1_elev=assign_gdt1.get_elevation(),
gdt2_elev=assign_gdt2.get_elevation(),
mission_name=mission_name
)
)
mission name is a primary key, So to access to the retrieve method the user need to go to the URL line and write the mission name for the method to work.
So, how and where in my project (urls,view...) do I create this route.
Exmpale:
I'm a little confused as to the purpose of this view.
The retrieve method is correctly used when it is retrieving a specific object from the queryset list using the pk. IE, one of your LocationInfo objects. It's always a get request.
Your retrieve method is also missing the pk parameter, which is sometimes defaulted as None.
retrieve(self, request, pk=None)
If I were you, I'd create a completely separate view or viewset method/action for this.
Instead of using retrieve for this, we can create a completely new method:
from rest_framework.decorators import action
class LocationInfoViewSet(ModelViewSet):
# Order all objects by id, reversed.
queryset = LocationInfo.objects.all().order_by('-id')
serializer_class = LocationInfoSerializer
# {The rest of your methods, etc...}
#action(detail=False, methods=["post"])
def last_object_by_user(self, request, *args, **kwargs):
# your query to get the last object by your user
queryset = LocationInfo.objects.filter(created_by=request.user).latest()
# The rest of your code
This will create a new endpoint called /{name}/last_object_by_user/ that you can make post requests to.
You'd also notice that I've modified your queryset a bit. Your current queryset gives us the last LocationInfo created by any user. Did you create a field in LocationInfo that tracks who created that LocationInfo?
Here's the documentation for this: Marking extra actions for routing
Note: I did not test this code so if you copy-paste this, it might not work, but the idea is what's important.
What I want to do: is do my get_initial() to create a Author object with defaults, then extract data from Post.
Conceptually, code does it right, but in reality initial doesnt return and object doesnt creates
```
class StartGame(PermissionRequiredMixin, CreateView):
model = Author```
fields = {'date_of_death'}
permission_required = 'catalog.can_mark_returned'
def get_initial(self,req):
initial = super(StartGame, self).get_initial()
initial = initial.copy()
return initial
def post(self, request, **kwargs):
bb_object = BigBlind.objects.create(bb_sum=request.POST.get('bigblind'))
bb_object.save()
return HttpResponseRedirect(reverse('catalog:index'))
If I delete my post method, my object creates fine, but I need to create BigBlind object too, I just dont get how to do it.
Or what should I read exactly.
Thanks
Dealed: created model in Post method, delete get_initial_data
I have a django rest framework project. I am trying to override the create method so that if there are certain parameters or arguments passed into the url, it will ovverride some of the default informaiton passed in with the form.
I am doing that by creating the data object that will be used to create the new object. Right now, I am grabbing the user by using request.user but it is giving me the following error:
TypeError at /api/v2/preferences/namespace1/
'User' object is not subscriptable
and I am not sure how to fix it.
Here is my code for the mode view set create method override:
#permission_classes((IsAuthenticated))
def create(self, request, *args, **kwargs):
print(request)
namespace = self.kwargs.get('namespace', None)
path = self.kwargs.get('path', None)
if namespace is None and path is None:
return super().create(request)
if namespace and path is None:
data = {
"person":self.request.user,
'version':request.POST['version'],
'namespace':namespace,
'path':request.POST['path'],
'value':request.POST['value'],
'user_id':request.user['id'],
}
return super().create(data)
if namespace and path:
data = {
"person":self.request.user,
'version':request.POST['version'],
'namespace':namespace,
'path':path,
'value':request.POST['value'],
'user_id':request.user['id'],
}
return super().create(data)
request.user returns a User object from database, it is not a dict; hence your request.user['id'] subscription operation will fail expectedly.
You need to get the id attribute of the User object:
request.user.id
So, make the data dict like:
data = {
...
...
'user_id': request.user.id,
}
My question is exactly what it's subject says :
How to create Django Tastypie API which accepts the POST data, does some processing on it and returns some HTTP response, but does not creates any entry in database.
For Example for this sample API resource :
class NextNumberResource(ModelResource):
class Meta:
resource_name = 'next_number'
detail_allowed_methods = []
list_allowed_methods = ['post']
def obj_create(self, bundle, **kwargs):
#raise CustomBadRequest(code = "code ={c}".format(c=int(bundle.data["number"])*2))
next_number = int(bundle.data["number"]) * 2
data = json.dumps({"next_number":next_number})
return HttpResponse(data, content_type='application/json', status=200)
I am getting following error :
{"error_message": "'HttpResponse' object has no attribute 'pk'"}
I think it's better to handle this request in dispatch_* methods (e.g. dispatch_list).
For example here.
Explanation: If you handle a post request which doesn't create any instance, you have to process it before std workflow of the tastypie.