Following this tutorial:
http://django-rest-framework.org/tutorial/1-serialization.html
through http://django-rest-framework.org/tutorial/4-authentication-and-permissions.html
I have this code:
# models.py
class Message(BaseDate):
"""
Private Message Model
Handles private messages between users
"""
status = models.SmallIntegerField(_('status'), choices=choicify(MESSAGE_STATUS))
from_user = models.ForeignKey(User, verbose_name=_('from'), related_name='messages_sent')
to_user = models.ForeignKey(User, verbose_name=_('to'), related_name='messages_received')
text = models.TextField(_('text'))
viewed_on = models.DateTimeField(_('viewed on'), blank=True, null=True)
# serialisers.py
class MessageSerializer(serializers.ModelSerializer):
from_user = serializers.Field(source='from_user.username')
to_user = serializers.Field(source='to_user.username')
class Meta:
model = Message
fields = ('id', 'status', 'from_user', 'to_user', 'text', 'viewed_on')
# views.py
from permissions import IsOwner
class MessageDetail(generics.RetrieveUpdateDestroyAPIView):
model = Message
serializer_class = MessageSerializer
authentication_classes = (TokenAuthentication, SessionAuthentication)
permission_classes = (permissions.IsAuthenticated, IsOwner)
# permissions.py
class IsOwner(permissions.BasePermission):
"""
Custom permission to only allow owners of an object to edit or delete it.
"""
def has_permission(self, request, view, obj=None):
# Write permissions are only allowed to the owner of the snippet
return obj.from_user == request.user
# urls.py
urlpatterns = patterns('',
url(r'^messages/(?P<pk>[0-9]+)/$', MessageDetail.as_view(), name='api_message_detail'),
)
Then opening the URL of the API i get this error:
**AttributeError at /api/v1/messages/1/
'NoneType' object has no attribute 'from_user'**
Traceback:
File "/var/www/sharigo/python/lib/python2.6/site-packages/django/core/handlers/base.py" in get_response
111. response = callback(request, *callback_args, **callback_kwargs)
File "/var/www/sharigo/python/lib/python2.6/site-packages/django/views/generic/base.py" in view
48. return self.dispatch(request, *args, **kwargs)
File "/var/www/sharigo/python/lib/python2.6/site-packages/django/views/decorators/csrf.py" in wrapped_view
77. return view_func(*args, **kwargs)
File "/var/www/sharigo/python/lib/python2.6/site-packages/rest_framework/views.py" in dispatch
363. response = self.handle_exception(exc)
File "/var/www/sharigo/python/lib/python2.6/site-packages/rest_framework/views.py" in dispatch
351. self.initial(request, *args, **kwargs)
File "/var/www/sharigo/python/lib/python2.6/site-packages/rest_framework/views.py" in initial
287. if not self.has_permission(request):
File "/var/www/sharigo/python/lib/python2.6/site-packages/rest_framework/views.py" in has_permission
254. if not permission.has_permission(request, self, obj):
File "/var/www/sharigo/sharigo/apps/sociable/permissions.py" in has_permission
17. return obj.from_user == request.user
Exception Type: AttributeError at /api/v1/messages/1/
Exception Value: 'NoneType' object has no attribute 'from_user'
It seems like None is being passed as the value for the parameter "obj" to isOwner.has_permission().
What am I doing wrong? I think i followed strictly the tutorial.
When has_permission() is called with obj=None it's supposed to return whether the user has permission to any object of this type. So you should handle the case when None is passed.
Your code should be something like:
def has_permission(self, request, view, obj=None):
# Write permissions are only allowed to the owner of the snippet
return obj is None or obj.from_user == request.user
Use function has_object_permission instead of has_permission.
ex:
def has_object_permission(self, request, view, obj=None):
return obj.from_user == request.user
and call function check_object_permissions inside get_object in views
def get_object(self):
obj = get_object_or_404(self.get_queryset())
self.check_object_permissions(self.request, obj)
return obj
Related
I am using Django Rest Framework. I have an existing database (cannot make any changes to it). I have defined a serializer - ReceiptLog with no model, which should create entries in TestCaseCommandRun and TestCaseCommandRunResults when a post() request is made to ReceiptLog api endpoint. Receipt log doesn't exist in the database, I am using it just as an endpoint to accept a combined payload and create entries in underlying tables. Post() to TestCaseCommandRunResults and TestCaseCommandRun works independently, however, when I try to post through ReceiptLog it throws below error
Error Traceback:
File "/usr/local/lib/python3.6/dist-packages/django/core/handlers/exception.py" in inner
35. response = get_response(request)
File "/usr/local/lib/python3.6/dist-packages/django/core/handlers/base.py" in _get_response
128. response = self.process_exception_by_middleware(e, request)
File "/usr/local/lib/python3.6/dist-packages/django/core/handlers/base.py" in _get_response
126. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/usr/lib/python3.6/contextlib.py" in inner
52. return func(*args, **kwds)
File "/usr/local/lib/python3.6/dist-packages/django/views/decorators/csrf.py" in wrapped_view
54. return view_func(*args, **kwargs)
File "/usr/local/lib/python3.6/dist-packages/django/views/generic/base.py" in view
69. return self.dispatch(request, *args, **kwargs)
File "/usr/local/lib/python3.6/dist-packages/rest_framework/views.py" in dispatch
495. response = self.handle_exception(exc)
File "/usr/local/lib/python3.6/dist-packages/rest_framework/views.py" in handle_exception
455. self.raise_uncaught_exception(exc)
File "/usr/local/lib/python3.6/dist-packages/rest_framework/views.py" in dispatch
492. response = handler(request, *args, **kwargs)
File "/usr/local/lib/python3.6/dist-packages/rest_framework/generics.py" in post
192. return self.create(request, *args, **kwargs)
File "/usr/local/lib/python3.6/dist-packages/rest_framework/mixins.py" in create
21. self.perform_create(serializer)
File "/usr/local/lib/python3.6/dist-packages/rest_framework/mixins.py" in perform_create
26. serializer.save()
File "/usr/local/lib/python3.6/dist-packages/rest_framework/serializers.py" in save
216. '`create()` did not return an object instance.'
Exception Type: AssertionError at /dqf_api/ReceiptLog/
Exception Value: `create()` did not return an object instance.
models.py
class TestCaseCommandRun(models.Model):
# fields ..Doesn't have id field as the database doesn't have it
class Meta:
managed = False
db_table = 'test_case_command_run'
unique_together = (('team_name', 'suite_name', 'suite_run_id', 'case_name', 'command_name'),)
class TestCaseCommandRunResults(models.Model):
# fields ..Doesn't have id field as the database doesn't have it
class Meta:
managed = False
db_table = 'test_case_command_run_results'
unique_together = (('suite_run_id', 'command_run_id', 'rule_name', 'result_id'),)
views.py
class TestCaseCommandRunViewSet(viewsets.ModelViewSet):
queryset = models.TestCaseCommandRunViewSet.objects.values('team_name','suite_name','suite_run_id', 'case_name','command_name','command_run_id','run_start','run_end','result','run_status')
serializer_class = serializers.TestCaseCommandRunViewSet
class TestCaseCommandRunResultsViewSet(viewsets.ModelViewSet):
queryset = models.TestCaseCommandRunResultsViewSet.objects.values('suite_run_id','command_run_id','rule_name', 'result_id',
'result','expected_values','actual_values','report_values','extended_values')
serializer_class = serializers.TestCaseCommandRunResultsViewSet
class ReceiptLogViewSet(CreateAPIView):
serializer_class = serializers.ReceiptLogSerializer.ReceiptLogSerializerClass
serializers.py
class TestCaseCommandRunResultsViewSet(serializers.ModelSerializer):
class Meta:
model = models.TestCaseCommandRunResultsViewSet
fields = ['suite_run_id','command_run_id','rule_name', 'result_id','result','expected_values','actual_values','report_values','extended_values']
class TestCaseCommandRunSerializer(serializers.ModelSerializer):
class Meta:
model = models.TestCaseCommandRunSerializer
fields = ['team_name','suite_name','suite_run_id', 'case_name','command_name','command_run_id','run_start','run_end','result','run_status']
class ReceiptLogSerializerClass(serializers.Serializer):
team_name = serializers.CharField(max_length=30)
suite_name = serializers.CharField(max_length=100)
suite_run_id = serializers.CharField(max_length=50,required=False, allow_blank=True, default=datetime.now().strftime('%Y%m%d%H%M%S'))
case_name = serializers.CharField(max_length=50)
command_name = serializers.CharField(max_length=50)
command_run_id = serializers.CharField(max_length=50,required=False, allow_blank=True, default='Not Applicable')
run_start = serializers.DateTimeField(default=datetime.now, required=False)
run_end = serializers.DateTimeField(default=datetime.now, required=False)
result = serializers.CharField(max_length=10, default='Not Applicable')
run_status = serializers.CharField(max_length=10)
rule_name = serializers.CharField( max_length=50, required=False, allow_blank=True, default='Not Applicable')
expected_values = serializers.CharField(max_length=200, allow_blank=True)
actual_values = serializers.CharField(max_length=200, allow_blank=True)
report_values = serializers.CharField(max_length=200, allow_blank=True)
extended_values = serializers.CharField(max_length=200, allow_blank=True)
def create(self, validated_data):
# command_run_data_list = []
command_run_results_data_list = []
raw_data_list = []
many = isinstance(validated_data, list)
if many:
raw_data_list = validated_data
else:
raw_data_list.append(validated_data)
result_id = 1
for data_row in raw_data_list:
new_command_run_entry = {
'team_name': data_row.get('team_name'),
'suite_name': data_row.get('suite_name'),
'suite_run_id': data_row.get('suite_run_id'),
'case_name': data_row.get('case_name'),
'command_name': data_row.get('command_name'),
'command_run_id': data_row.get('command_run_id'),
'run_start': data_row.get('run_start'),
'run_end': data_row.get('run_end'),
'result': data_row.get('result'),
'run_status': data_row.get('run_status')
}
command_run_data_list.append(new_command_run_entry)
new_command_run_result_entry = {
'suite_run_id': data_row.get('suite_run_id'),
'command_run_id': data_row.get('command_run_id'),
'rule_name': data_row.get('rule_name'),
'result_id': result_id,
'result': data_row.get('result'), # PASS or FAIL
'expected_values': data_row.get('expected_values'),
'actual_values': data_row.get('actual_values'),
'report_values': data_row.get('report_values'),
'extended_values': data_row.get('extended_values'),
}
command_run_results_data_list.append(new_command_run_result_entry)
result_id += 1
for item in command_run_results_data_list:
response_run_results = models.TestCaseCommandRunResults.objects.create(**item)
for item in command_run_data_list:
response_run = models.TestCaseCommandRun.objects.create(**item)
urls.py
router = routers.DefaultRouter()
router.register(r'test_case_command_runs', views.TestCaseCommandRunViewSet)
router.register(r'test_case_command_run_results', views.TestCaseCommandRunResultsViewSet)
urlpatterns = [
url(r'^buildInfo', views.build_info),
url(r'^isActive', views.is_active),
url(r'^dqf_api/', include(router.urls)),
url(r'^dqf_api/ReceiptLog/', views.ReceiptLogView.ReceiptLogViewSet.as_view(), name='ReceiptLog')]
Any help is really appreciated.I am new to Django and DRF
Your serializer's create method MUST return an instance of the object it represents. Also, you should not iterate inside the serializer to create instances, that should be done on the view: you iterate through the data, calling the serializer each iteration.
Updated the serializers.py file to include the below code
class ReceiptLogSerializerClass(serializers.Serializer):
#Fields
def create(self, validated_data):
raw_data_list = []
many = isinstance(validated_data, list)
if many:
raw_data_list = validated_data
else:
raw_data_list.append(validated_data)
result_id = 1
for data_row in raw_data_list:
new_command_run_entry = {
'team_name': data_row.get('team_name'),
'suite_name': data_row.get('suite_name'),
'suite_run_id': data_row.get('suite_run_id'),
'case_name': data_row.get('case_name'),
'command_name': data_row.get('command_name'),
'command_run_id': data_row.get('command_run_id'),
'run_start': data_row.get('run_start'),
'run_end': data_row.get('run_end'),
'result': data_row.get('result'),
'run_status': data_row.get('run_status')
}
response = TestCaseCommandRunSerializer.create(TestCaseCommandRunSerializer(),validated_data= new_command_run_entry)
new_command_run_result_entry = {
'suite_run_id': data_row.get('suite_run_id'),
'command_run_id': data_row.get('command_run_id'),
'rule_name': data_row.get('rule_name'),
'result_id': result_id,
'result': data_row.get('result'), # PASS or FAIL
'expected_values': data_row.get('expected_values'),
'actual_values': data_row.get('actual_values'),
'report_values': data_row.get('report_values'),
'extended_values': data_row.get('extended_values'),
}
response = TestCaseCommandRunResultsSerializer.create(TestCaseCommandRunResultsSerializer(),validated_data= new_command_run_result_entry)
logger.info(" new_command_run_result_entry response %s" % response)
result_id += 1
return validated_data
I was not de-serializing the data correctly and hence ran into multiple issues.
return validated_data
rectified all the errors and now I am able to post() data to multiple models through single API.
For posting a multiple payloads in a single API Call added below lines in ReceiptLogViewSet
def get_serializer(self, *args, **kwargs):
if "data" in kwargs:
data = kwargs["data"]
if isinstance(data, list):
kwargs["many"] = True
return super(ReceiptLogViewSet, self).get_serializer(*args, **kwargs)
Ref: Django rest framework cannot deal with multple objects in model viewset
The serializer ReceiptLogSerializerClass MUST be a ModelSerializer, not a Serializer
if you written your own model manager for default user model then there are chances of your method not returning the user instance which should be return.
for example:
class CustomUserManager(BaseUserManager):
def _create_user(self, email, password=None, **extra_kwargs):
if not email:
raise ValueError("email should be present")
user = self.model(email=email, **extra_kwargs)
user.set_password(password)
user.save(using=self._db)
return user
def create_user(self, email, password=None, **extra_kwargs):
extra_kwargs.setdefault('is_staff', False)
extra_kwargs.setdefault('is_superuser', False)
#self._create_user(email, password, **extra_kwargs) if this method not returning user instance upon creation this will cause problem `create()` did not return an object instance
return self._create_user(email, password, **extra_kwargs)
def create_superuser(self, email, password=None, **extra_kwargs):
extra_kwargs.setdefault('is_staff', True)
extra_kwargs.setdefault('is_superuser', True)
#self._create_user(email, password, **extra_kwargs) if this method not returning user instance upon creation this will cause problem `create()` did not return an object instance
return self._create_user(email, password, **extra_kwargs)
I am trying to implement filter api in django rest. Something like -
localhost:8000/api/v1/users/?email=abc.xzy#gmail.com/
So it should search for user with the passed filter and return the result.But currently it is returning all user.
URLS.py
url(r'^api/v1/users/$', UserViews.UserList.as_view(), name='userlist_view'),
url(r'^api/v1/users/(?P<email>.+)/$', UserViews.UserList.as_view(), name='userList_view'),
url(r'^api/v1/users/(?P<pk>[0-9]+)/$', UserViews.UserDetail.as_view(), name='userdetail_view'),
UserViews.py
class UserList(generics.ListAPIView):
"""
List all users, or create a new user.
"""
lookup_url_kwarg = "email"
def get(self, request, format=None):
if request.user.is_authenticated():
users = User.objects.all()
serializer = UserSerializer(users, many=True)
return Response(serializer.data)
return Response("User is not authenticated.", status=status.HTTP_400_BAD_REQUEST)
def post(self, request, format=None):
valid_paylaod, msg = UserListRepository.validations_create_user(request.data)
if not valid_paylaod:
return Response(msg, status=status.HTTP_400_BAD_REQUEST)
result = UserListRepository.create_user_repo(request)
if not result.success:
return Response(str(result.msg), status=result.status )
return Response(UserSerializer(result.data).data, status=result.status)
def get_queryset(self):
# It restricts the userlist by retunning users having emails passed in uery param
user = self.request.user
if user.is_authenticated():
if 'email' in self.request.query_params:
email = self.request.query_params.get('email', None)
users = User.objects.get(email= email)
if not users:
return Response( "User Not found", status=status.HTTP_404_NOT_FOUND)
else:
return Response(UserSerializer(User.objects.all()).data, status.HTTP_200_OK, users)
else:
return Response(UserSerializer().data, status=result.status)
else:
return Response("User is not authenticated.", status=status.HTTP_400_BAD_REQUEST)
Can some one tell why the request is not going to get_queryset() method and going to get() of UserList method. On removing get method, the request goes to get_queryset(self) method. On debugging, I found that I get valid Response before return statement -
(Pdb) UserSerializer(result.data).data
{'parent_id': 2, 'id': 31, 'group_id': '4', 'last_name': 'user', 'email': 'agency22_user#agency22.com', 'organization_id': 0, 'first_name': 'agency22'}
But Still in APi response, I get following error :
Internal Server Error: /api/v1/users/
Traceback (most recent call last):
File "/Users/richagupta/VirtualEnvs/py35/lib/python3.5/site-packages/django/core/handlers/base.py", line 149, in get_response
response = self.process_exception_by_middleware(e, request)
File "/Users/richagupta/VirtualEnvs/py35/lib/python3.5/site-packages/django/core/handlers/base.py", line 147, in get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
Fi e "/Users/richagupta/VirtualEnvs/py35/lib/python3.5/site-packages/django/views/decorators/csrf.py", line 58, in wrapped_view
return view_func(*args, **kwargs)
File "/Users/richagupta/VirtualEnvs/py35/lib/python3.5/site-packages/django/views/generic/base.py", line 68, in view
return self.dispatch(request, *args, **kwargs)
File "/Users/richagupta/VirtualEnvs/py35/lib/python3.5/site-packages/rest_framework/views.py", line 466, in dispatch
response = self.handle_exception(exc)
File "/Users/richagupta/VirtualEnvs/py35/lib/python3.5/site-packages/rest_framework/views.py", line 463, in dispatch
response = handler(request, *args, **kwargs)
File "/Users/richagupta/VirtualEnvs/py35/lib/python3.5/site-packages/rest_framework/generics.py", line 201, in get
return self.list(request, *args, **kwargs)
File "/Users/richagupta/VirtualEnvs/py35/lib/python3.5/site-packages/rest_framework/mixins.py", line 43, in list
if page is not None:
File "/Users/richagupta/VirtualEnvs/py35/lib/python3.5/site-packages/rest_framework/serializers.py", line 674, in data
ret = super(ListSerializer, self).data
File "/Users/richagupta/VirtualEnvs/py35/lib/python3.5/site-packages/rest_framework/serializers.py", line 239, in data
self._data = self.to_representation(self.instance)
File "/Users/richagupta/VirtualEnvs/py35/lib/python3.5/site- packages/rest_framework/serializers.py", line 614, in to_representation
self.child.to_representation(item) for item in iterable
File "/Users/richagupta/VirtualEnvs/py35/lib/python3.5/site- packages/django/template/response.py", line 173, in __iter__
raise ContentNotRenderedError('The response content must be '
django.template.response.ContentNotRenderedError: The response content must be rendered before it can be iterated over.
I am not clear why . API URL I am hitting is : localhost:8000/api/v1/users?email=agency22_user#agency22.com
The problem is that you are overriding the get method of ListAPIView. This method is called by a GET request. The default implementation of get calls the list method of ListModelMixin and there get_queryset gets called:
def list(self, request, *args, **kwargs):
queryset = self.filter_queryset(self.get_queryset())
page = self.paginate_queryset(queryset)
if page is not None:
serializer = self.get_serializer(page, many=True)
return self.get_paginated_response(serializer.data)
serializer = self.get_serializer(queryset, many=True)
return Response(serializer.data)
If you override this method you have to call get_queryset yourself.
If you just want to check if the user is authenticated and then call the default list method you can do it like this:
def get(self, request, format=None):
if request.user.is_authenticated():
return super(UserList, self).get(request, format)
return Response("User is not authenticated.", status=status.HTTP_400_BAD_REQUEST)
I'm confused by the UrlConf:
url(r'^api/v1/users/$', UserViews.UserList.as_view(), name='userlist_view'),
url(r'^api/v1/users/(?P<email>.+)/$', UserViews.UserList.as_view(), name='userList_view'),
First one is for localhost:8000/api/v1/users/
Second one is for localhost:8000/api/v1/users/abc.xzy#gmail.com/ not localhost:8000/api/v1/users/?email=abc.xzy#gmail.com/, this is a query parameter not kwargs, check this if you want to use query parameter
class UserList(generics.ListAPIView):
"""
List all users, or create a new user.
"""
lookup_url_kwarg = "email"
serializer_class = UserSerializer
def post(self, request, format=None):
valid_paylaod, msg = UserListRepository.validations_create_user(request.data)
if not valid_paylaod:
return Response(msg, status=status.HTTP_400_BAD_REQUEST)
result = UserListRepository.create_user_repo(request)
if not result.success:
return Response(str(result.msg), status=result.status )
return Response(UserSerializer(result.data).data, status=result.status)
def get_queryset(self):
"""
It restricts the userlist by return users having emails passed in query param
"""
queryset = Users.objects.all()
email = self.request.query_params.get('email', None)
if email is not None:
queryset = queryset.filter(email=email)
return queryset
It looks like you are using Response from django instead of django-rest-framework.
You have to import Response from rest_framework.response
from rest_framework.response import Response
In Django rest framework there is a proper specification of how to use filters. So your user class would look like.
class UserList(generics.ListAPIView):
"""
List all users, or create a new user.
"""
lookup_url_kwarg = "email"
serializer_class = UserSerializer
def get(self, request, format=None):
if request.user.is_authenticated():
users = User.objects.all()
serializer = UserSerializer(users, many=True)
return Response(serializer.data)
return Response("User is not authenticated.", status=status.HTTP_400_BAD_REQUEST)
def post(self, request, format=None):
valid_paylaod, msg = UserListRepository.validations_create_user(request.data)
if not valid_paylaod:
return Response(msg, status=status.HTTP_400_BAD_REQUEST)
result = UserListRepository.create_user_repo(request)
if not result.success:
return Response(str(result.msg), status=result.status )
return Response(UserSerializer(result.data).data, status=result.status)
def get_queryset(self):
email = self.request.query_params.get('email', None)
return User.objects.filter(email=email)
or you can try without get_queryset . The link would change , updated link is :
localhost:8000/api/v1/users/abc.xzy#gmail.com/
and the updated code is
class UserList(generics.ListCreateAPIView):
"""
List all users, or create a new user.
"""
lookup_url_kwarg = "email"
serializer_class = UserSerializer
def get(self, request, email,format=None):
if request.user.is_authenticated():
user_details = User.objects.filter(email=email)
serializer = UserSerializer(user_details, many=True)
return Response(serializer.data, status=status.status.HTTP_200_OK)
return Response("User is not authenticated.", status=status.HTTP_400_BAD_REQUEST)
def post(self, request, format=None):
valid_paylaod, msg = UserListRepository.validations_create_user(request.data)
if not valid_paylaod:
return Response(msg, status=status.HTTP_400_BAD_REQUEST)
result = UserListRepository.create_user_repo(request)
if not result.success:
return Response(str(result.msg), status=result.status )
return Response(UserSerializer(result.data).data, status=result.status)
I got this error shown as title. According to document, I added "slug_url_kwarg = 'result'", (result is the app name). It doesn't work, then I added "def get_object(self):", it returns the error as "id is a KeyError"
The database it has created by itself a primary ket:"id", so I used this "id" as slug_field. Is this correct?
Do you think if it is necessary for me to use UpdateView? I want the html to display a result after submiting the form(using ajax)?
Thans in advance for your reply.
url
url(r'^result_list/$',ResultView.as_view(),name='result'),
views.py
class ResultView(UpdateView):
context_object_name = 'result_list'
template_name = 'result_list.html'
form_class = InputForm
slug_field = 'result.id' ---here means the pk,right?
slug_url_kwarg = 'result'
def get_queryset(self):
return Result.objects.all()
def post(self, request, *args, **kwargs):
form = InputForm(request.POST)
if form.is_valid():
if self.request.is_ajax():
company = form.cleaned_data['company']
region = form.cleaned_data['region']
queryset=Result.objects.filter(region=region)
return HttpResponse(simplejson.dumps(to_json),mimetype='application/json')
else:
return HttpResponse(form.errors)
def get_context_data(self, **kwargs):
context = super(ResultView, self).get_context_data(**kwargs)
context["sales"] = self.get_queryset().aggregate(Sum('sales'))
def get_object(self):
object = get_object_or_404(Result,id=self.kwargs['id']) <!here is not correct--->
return object
traceback
File "C:\Python27\lib\site-packages\django-1.8.3-py2.7.egg\django\core\handlers\base.py" in get_response
132. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Python27\lib\site-packages\django-1.8.3-py2.7.egg\django\views\generic\base.py" in view
71. return self.dispatch(request, *args, **kwargs)
File "C:\Python27\lib\site-packages\django-1.8.3-py2.7.egg\django\views\generic\base.py" in dispatch
89. return handler(request, *args, **kwargs)
File "C:\Python27\lib\site-packages\django-1.8.3-py2.7.egg\django\views\generic\edit.py" in get
267. self.object = self.get_object()
File "C:\Users\user\Desktop\project\result\views.py" in get_object
54. object = get_object_or_404(Result,id=self.kwargs['id'])
Exception Type: KeyError at /result_list/
Exception Value: 'id'
You forgot to map the url pattern, you don't need to specify slug_field and slug_url_kwarg in your case:
url(r'^dupont_list/(?P<pk>[0-9]+)/$', DupontView.as_view(), name='dupont'),
Trying to inherit ModelForm to create a BaseForm to update created_by, modified_by fields in model.
My BaseForm is as
class BaseForm(ModelForm):
def __init__(self, *args, **kwargs):
self.user = kwargs.pop('request', None).user
super(BaseForm, self).__init__(*args, **kwargs)
def save(self, *args, **kwargs):
kwargs['commit']=False
obj = super(BaseForm, self).save(*args, **kwargs)
if self.user:
obj.modified_by = self.user.username
obj.save()
return obj
Child Form is as
class InviteForm(BaseForm):
class Meta:
model = UserInvitation
and I am passing the request in child form through view
form = InviteForm(instance=instance,request=request)
however it gives error
TypeError at /accounts/invitation/
__init__() got an unexpected keyword argument 'request'
The error is not there if I do not inherit the BaseForm and write the code in child form i.e. InviteForm.
Please advise what I am doing wrong, I do not want to repeat the code in each form.
Traceback:
File "c:\Python27\lib\site-packages\django\core\handlers\base.py" in get_response
115. response = callback(request, *callback_args, **callback_kwargs)
File "c:\Python27\lib\site-packages\django\contrib\auth\decorators.py" in _wrapped_view
25. return view_func(request, *args, **kwargs)
File "C:\Python27\Lib\site-packages\django\bin\mysite\userplus\views.py" in invitation
87. form = InviteForm(instance=instance,request=request)
Exception Type: TypeError at /accounts/invitation/
Exception Value: __init__() got an unexpected keyword argument 'request'
To update the modified_by field that you have in your UserInvitation model, you should exclude it from being shown in the form:
class BaseForm(ModelForm):
...
class InviteForm(BaseForm):
class Meta:
model = UserInvitation
exclude = ('modified_by',)
Then in your view
form = InviteForm(request.POST, instance=instance)
if form.is_valid():
invite = form.save(commit=false)
invite.modified_by = request.user
invite.save()
That way the user making the request is used.
Alternatively, you can set the user beforehand:
# views.py
instance = Invite(modified_by=request.user)
form = InviteForm(request.POST, instance=instance)
...
I'm trying to create a function that list all the people who are following a particular user but I keep encountering this error which I can't seem to solve . Can someone give me a hand please :)
error
AttributeError at /Follow/
'function' object has no attribute 'objects'
Request Method: GET
Request URL: http://127.0.0.1:8000/Follow/
Django Version: 1.5.1
Exception Type: AttributeError
Exception Value:
'function' object has no attribute 'objects'
Traceback:
File "C:\Python27\lib\site-packages\django\core\handlers\base.py" in get_response
115. response = callback(request, *callback_args, **callback_kwargs)
File "C:\Python27\lib\site-packages\endless_pagination\decorators.py" in decorated
35. return view(request, *args, **kwargs)
File "C:\Python27\lib\site-packages\django\contrib\auth\decorators.py" in _wrapped_view
25. return view_func(request, *args, **kwargs)
"C:\mysite\pet\views.py" in Followings
97. followers = Follow.objects.followers(user)
Exception Type: AttributeError at /Follow/
Exception Value: 'function' object has no attribute 'objects'
models
class Follow(models.Model):
""" Model to represent Following relationships """
follower = models.ForeignKey(AUTH_USER_MODEL, related_name='following')
followee = models.ForeignKey(AUTH_USER_MODEL, related_name='followers')
created = models.DateTimeField(default=timezone.now)
objects = FollowingManager()
class Meta:
verbose_name = _('Following Relationship')
verbose_name_plural = _('Following Relationships')
unique_together = ('follower', 'followee')
def __unicode__(self):
return "User #%d follows #%d" % (self.follower_id, self.followee_id)
def save(self, *args, **kwargs):
# Ensure users can't be friends with themselves
if self.follower == self.followee:
raise ValidationError("Users cannot follow themselves.")
super(Follow, self).save(*args, **kwargs)
class Person(models.Model):
user = models.ForeignKey(User)
name = models.CharField(max_length=30, blank=True)
def __unicode__(self):
return self.user.username
views
#page_template('pagination.html')
#login_required
def Followings(request,template='following.html', extra_context=None):
followers = Follow.objects.followers(user)
person = Person.objects.filter(user__in=followers)
context = {
'page_template': 'pagination.html',
'person' :Person.objects.filter(user__in=followers),
}
extra_context = {'person':person,}
if extra_context is not None:
context.update(extra_context)
return render_to_response(
template, context, context_instance=RequestContext(request))
url
url(
r'^Follow/$',
'pet.views.Followings',
name= 'Followings',
),
change
followers = Follow.objects.followers(user)
to
followers = request.user.followers.all()