I want to access ElasticSearch securely via a Django URL. From this request, I will lookup the user's token to get their primary key. Then I will only show ES results that match.
For now, I just want to connect to my ElasticSearch URL. It would kind of work like a "proxy".
Anyway, the following returns the bottom traceback. How do I set it up correctly? Do I need a serialiser
views.py
from django.http import HttpResponseRedirect
class ElasticViewSet(viewsets.ModelViewSet):
def my_view(request):
if True:
return HttpResponseRedirect('http://localhost:9200/_seach')
urls.py
router.register(r'elastic', ElasticViewSet, base_name='Elastic')
Traceback
Traceback:
File "/Users/mac1/Dev/A51/Backend/NewDJ/venv/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response
149. response = self.process_exception_by_middleware(e, request)
File "/Users/mac1/Dev/A51/Backend/NewDJ/venv/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response
147. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/Users/mac1/Dev/A51/Backend/NewDJ/venv/lib/python2.7/site-packages/django/views/decorators/csrf.py" in wrapped_view
58. return view_func(*args, **kwargs)
File "/Users/mac1/Dev/A51/Backend/NewDJ/venv/lib/python2.7/site-packages/rest_framework/viewsets.py" in view
83. return self.dispatch(request, *args, **kwargs)
File "/Users/mac1/Dev/A51/Backend/NewDJ/venv/lib/python2.7/site-packages/rest_framework/views.py" in dispatch
477. response = self.handle_exception(exc)
File "/Users/mac1/Dev/A51/Backend/NewDJ/venv/lib/python2.7/site-packages/rest_framework/views.py" in handle_exception
437. self.raise_uncaught_exception(exc)
File "/Users/mac1/Dev/A51/Backend/NewDJ/venv/lib/python2.7/site-packages/rest_framework/views.py" in dispatch
474. response = handler(request, *args, **kwargs)
File "/Users/mac1/Dev/A51/Backend/NewDJ/venv/lib/python2.7/site-packages/rest_framework/mixins.py" in list
40. queryset = self.filter_queryset(self.get_queryset())
File "/Users/mac1/Dev/A51/Backend/NewDJ/venv/lib/python2.7/site-packages/rest_framework/generics.py" in get_queryset
67. % self.__class__.__name__
Exception Type: AssertionError at /****/elastic/
Exception Value: 'ElasticViewSet' should either include a `queryset` attribute, or override the `get_queryset()` method.
First thing first, you don't want a ModelViewSet as there's no Model. Just go for the regular ViewSet.
Second, please take some time to think about what you want to do and how you want it done. my_view is not a ViewSet regular action. Returning HttpResponseRedirect is not acting as a proxy.
Related
I'm using the django-rest-passwordreset package to implement password reset endpoints.
When a given email doesn't exist, it throws a ValidationError exception, causing a 500 error. How can I catch this error, and return a 400 instead? I simply added the urls as shown below, so I don't think I can surround it with an try: except or something similar.
urlpatterns=[
...
url(r'^password/recover/', include('django_rest_passwordreset.urls')),
...
]
Exception:
ValidationError at /password/recover/
{'email': ['There is no active user associated with this e-mail address or the password can not be changed']}
Request Method: POST
Request URL: http://192.168.99.100:8000/password/recover/
Django Version: 2.0.6
Traceback:
File "/usr/local/lib/python3.6/site-packages/django/core/handlers/exception.py" in inner
35. response = get_response(request)
File "/usr/local/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response
128. response = self.process_exception_by_middleware(e, request)
File "/usr/local/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response
126. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/usr/local/lib/python3.6/site-packages/django/views/decorators/csrf.py" in wrapped_view
54. return view_func(*args, **kwargs)
File "/usr/local/lib/python3.6/site-packages/django/views/generic/base.py" in view
69. return self.dispatch(request, *args, **kwargs)
File "/usr/local/lib/python3.6/site-packages/rest_framework/views.py" in dispatch
483. response = self.handle_exception(exc)
File "/usr/local/lib/python3.6/site-packages/rest_framework/views.py" in handle_exception
443. self.raise_uncaught_exception(exc)
File "/usr/local/lib/python3.6/site-packages/rest_framework/views.py" in dispatch
480. response = handler(request, *args, **kwargs)
File "/usr/local/lib/python3.6/site-packages/django_rest_passwordreset/views.py" in post
116. code='invalid')}
Exception Type: ValidationError at /password/recover/
Exception Value: {'email': ['There is no active user associated with this e-mail address or the password can not be changed']}
Request information:
USER: AnonymousUser
GET: No GET data
POST: No POST data
FILES: No FILES data
COOKIES: No cookie data
HEADERS: "email" : "bob#thebuilder.com"
I managed to solve it by creating a custom Exception handler as described here.
Additional information:
- Filter on the specific error message to avoid catching ALL ValidationErrors,
- Otherwise return the standard Django exception response.
I'm trying to retrieve a model instance in Django Rest Framework 3.6.3 at /path/to/API/widget/1/, 1 being the primary key of the widget. It's giving me:
retrieve() got an unexpected keyword argument 'pk'
From the trace I think I'm doing something to cause dispatch to throw an exception when instantiating the handler (from views.py, source here). I don't understand what I'm doing wrong through when I examine the source. Here's the trace:
Traceback:
File "/lib/python3.5/site-packages/django/core/handlers/exception.py" in inner
41. response = get_response(request)
File "/lib/python3.5/site-packages/django/core/handlers/base.py" in _legacy_get_response
249. response = self._get_response(request)
File "/lib/python3.5/site-packages/django/core/handlers/base.py" in _get_response
187. response = self.process_exception_by_middleware(e, request)
File "/lib/python3.5/site-packages/django/core/handlers/base.py" in _get_response
185. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/lib/python3.5/site-packages/django/views/decorators/csrf.py" in wrapped_view
58. return view_func(*args, **kwargs)
File "/lib/python3.5/site-packages/rest_framework/viewsets.py" in view
86. return self.dispatch(request, *args, **kwargs)
File "/lib/python3.5/site-packages/rest_framework/views.py" in dispatch
489. response = self.handle_exception(exc)
File "/lib/python3.5/site-packages/rest_framework/views.py" in handle_exception
449. self.raise_uncaught_exception(exc)
File "/lib/python3.5/site-packages/rest_framework/views.py" in dispatch
486. response = handler(request, *args, **kwargs)
Exception Type: TypeError at /path/to/API/widget/1/
Exception Value: retrieve() got an unexpected keyword argument 'pk'
Here's the view from the ViewSet:
def retrieve(self, request, some_lookup_field=None):
instance = self.get_object(pk) # handle multi-tenant access control
if not instance:
return Response(status=status.HTTP_404_NOT_FOUND)
serializer = self.get_serializer(instance) # from the class's `serializer_cass` attribute
return Response(serializer.data)
As you see in your stacktrace, the error is:
retrieve() got an unexpected keyword argument 'pk'.
Look closely in your retrieve() function:
def retrieve(self, request, some_lookup_field=None):
# ____________________________^
instance = self.get_object(pk) # handle multi-tenant access control
# _________________________^
...
You are taking some_lookup_field as a parameter and not pk, that you use below in self.get_object(pk). Try to rename some_lookup_field to pk.
This error might because you put wrong urls in your url.py. I've had the same problem in my project
class CircularDetail(DeleteView):
model = Circular
template_name = 'genre/circular_detail.html'
def get_context_data(self, **kwargs):
ctx = super(CircularDetail, self).get_context_data(**kwargs)
ctx['c'] = Circular.objects.get(pk=self.pk)
ctx['sittings'] = Sitting.objects.all()
ctx['ballot'] = Sitting.objects.all()
return ctx
Above view give me following errors:
Traceback:
File "/home/ohid/test_venv/lib/python3.5/site-packages/django/core/handlers/base.py" in get_response
149. response = self.process_exception_by_middleware(e, request)
File "/home/ohid/test_venv/lib/python3.5/site-packages/django/core/handlers/base.py" in get_response
147. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/ohid/test_venv/lib/python3.5/site-packages/django/views/generic/base.py" in view
68. return self.dispatch(request, *args, **kwargs)
File "/home/ohid/test_venv/lib/python3.5/site-packages/django/views/generic/base.py" in dispatch
88. return handler(request, *args, **kwargs)
File "/home/ohid/test_venv/lib/python3.5/site-packages/django/views/generic/detail.py" in get
118. context = self.get_context_data(object=self.object)
File "/home/ohid/test_venv/myapp/genre/views.py" in get_context_data
126. ctx['c'] = Circular.objects.get(pk=self.pk)
Exception Type: AttributeError at /circular/1/detail/
Exception Value: 'CircularDetail' object has no attribute 'pk'
I need your assistance to fix this issues.
URL parameters are passed via kwargs, so you can access it this way
self.kwargs.get("pk")
so change
ctx['c'] = Circular.objects.get(pk=self.pk)
to
ctx['c'] = Circular.objects.get(pk=self.kwargs.get("pk"))
First of all, fix your base class to DetailView (instead of DeleteView)
DetailView inherited from django.views.generic.detail.SingleObjectMixin (https://docs.djangoproject.com/en/1.10/ref/class-based-views/mixins-single-object/#django.views.generic.detail.SingleObjectMixin) which expects primary key to be in slug parameter, so fix your URL regexp to
r'^circular/(?P<slug>[-\w]+)/detail$'
and access your object using self.object in view or just {{ object }} in template.
I'm currently working on the following issue: The user can access the page test.com/BlogPostTitle. Where BlogPostTitle is a slug. If a Blog post with the fitting title exists, Django should render the DetailView of said blog post. If it doesn't exist, Django should render a form to create a blog post.
This works so far:
class EntryDetail(DetailView): # Displays blog entry, if it exists
model = Blog
slug_field = 'title'
template_name = 'app/entry.html'
class EntryForm(FormView): # Displays form, if entry 404s
template_name = 'app/create.html'
form_class = EntryForm
success_url = '/'
def form_valid(self, form):
form.save()
return super(EntryForm, self).form_valid(form)
class EntryDisplay(View):
def get(self, request, *args, **kwargs):
try:
view = EntryDetail.as_view()
return view(request, *args, **kwargs)
except Http404:
if check_user_editor(self.request.user) == True: # Fails here
view = EntryForm.as_view()
return view(request, *args, **kwargs)
else:
pass
Now, only users who are in the group "editor" should be able to see the form/create a post:
def check_user_editor(user):
if user:
return user.groups.filter(name="editor").exists() # Returns true, if user in editor group
else:
return Falseâ‹…
As you can see, I've implemented the function in the EntryDisplay, however, Django errors 'User' object is not iterable.
I'm guessing I've to work with SingleObjectMixin, but I haven't quite understood the docs on that.
Any help would be much appreciated.
Full traceback:
Traceback:
File "/home/django/local/lib/python3.4/site-packages/django/views/generic/detail.py" in get_object
53. obj = queryset.get()
File "/home/django/local/lib/python3.4/site-packages/django/db/models/query.py" in get
385. self.model._meta.object_name
During handling of the above exception (Blog matching query does not exist.), another exception occurred:
File "/home/django/mediwiki/mediwiki/views.py" in get
68. return view(request, *args, **kwargs)
File "/home/django/local/lib/python3.4/site-packages/django/views/generic/base.py" in view
68. return self.dispatch(request, *args, **kwargs)
File "/home/django/local/lib/python3.4/site-packages/django/views/generic/base.py" in dispatch
88. return handler(request, *args, **kwargs)
File "/home/django/local/lib/python3.4/site-packages/django/views/generic/detail.py" in get
115. self.object = self.get_object()
File "/home/django/local/lib/python3.4/site-packages/django/views/generic/detail.py" in get_object
56. {'verbose_name': queryset.model._meta.verbose_name})
During handling of the above exception (No blog found matching the query), another exception occurred:
File "/home/django/local/lib/python3.4/site-packages/django/core/handlers/exception.py" in inner
39. response = get_response(request)
File "/home/django/local/lib/python3.4/site-packages/django/core/handlers/base.py" in _legacy_get_response
249. response = self._get_response(request)
File "/home/django/local/lib/python3.4/site-packages/django/core/handlers/base.py" in _get_response
187. response = self.process_exception_by_middleware(e, request)
File "/home/django/local/lib/python3.4/site-packages/django/core/handlers/base.py" in _get_response
185. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/django/local/lib/python3.4/site-packages/django/views/generic/base.py" in view
68. return self.dispatch(request, *args, **kwargs)
File "/home/django/local/lib/python3.4/site-packages/django/views/generic/base.py" in dispatch
88. return handler(request, *args, **kwargs)
File "/home/django/mediwiki/mediwiki/views.py" in get
74. view = HttpResponse(request.user)
File "/home/django/local/lib/python3.4/site-packages/django/http/response.py" in __init__
293. self.content = content
File "/home/django/local/lib/python3.4/site-packages/django/http/response.py" in content
319. content = b''.join(self.make_bytes(chunk) for chunk in value)
File "/home/django/local/lib/python3.4/site-packages/django/utils/functional.py" in inner
235. return func(self._wrapped, *args)
Exception Type: TypeError at /test
Exception Value: 'User' object is not iterable
Your error is in line 74 in mediwiki.views:
view = HttpResponse(request.user)
HttpResponse expects a string or an iterable. Since request.user is not a string, it tries to use it as an iterable, which fails.
I can't say much without the actual code. If in fact you want to send just a string representation of the user as the response, you need to cast is to a string:
view = HttpResponse(str(request.user))
Is the error occurred at template rendering? If so I wonder you've make iter over attributes on single User object. I think you may need user.values().
BTW, check_user_editor should be simpler:
def check_user_editor(user):
return user.groups.filter(name="editor").exists()
I have a user authentication form in django. Once I login into the form with the super-user credentials, I am having this error : 'DeleteQuery' object has no attribute 'add'
I am using login, REDIRECT_FIELD_NAME, logout methods from the django.contrib.auth module.
This is my Traceback :
File "/home/ramana/enorgo/local/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response
112. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/ramana/enorgo/local/lib/python2.7/site-packages/django/views/decorators/cache.py" in _wrapped_view_func
52. response = view_func(request, *args, **kwargs)
File "/home/ramana/enorgo/enorgo/utils/view_functions.py" in wrapper
23. output = func(request, *args, **kw)
File "/home/ramana/enorgo/enorgo/apps/base/views.py" in login
55. login_user(request, form.get_user())
File "/home/ramana/enorgo/local/lib/python2.7/site-packages/django/contrib/auth/__init__.py" in login
83. request.session.cycle_key()
File "/home/ramana/enorgo/local/lib/python2.7/site-packages/django/contrib/sessions/backends/base.py" in cycle_key
279. self.delete(key)
File "/home/ramana/enorgo/local/lib/python2.7/site-packages/django/contrib/sessions/backends/db.py" in delete
75. Session.objects.get(session_key=session_key).delete()
File "/home/ramana/enorgo/local/lib/python2.7/site-packages/django/db/models/base.py" in delete
695. collector.delete()
File "/home/ramana/enorgo/local/lib/python2.7/site-packages/django/db/models/deletion.py" in delete
277. query.delete_batch(pk_list, self.using)
File "/home/ramana/enorgo/local/lib/python2.7/site-packages/django/db/models/sql/subqueries.py" in delete_batch
47. where.add((Constraint(None, field.column, field), 'in',
Exception Type: AttributeError at /login/
Exception Value: 'DeleteQuery' object has no attribute 'add'
Actually this problem was solved when I shifted to a different database. If someone could explain why this happened, that would be great.