i am trying to use django reverse to route back to a page which take an argument vendor_id.
I am trying to do it this way using this post as reference: POST
return HttpResponseRedirect(reverse('vendor_data', kwargs={'vendor_id':vendor_id}))
My view method which should be called:
def vendorData(request):
vendors = Vendors()
if request.method == 'GET':
vendor_id = request.GET.get('vendor_id')
if vendors.checkValidVendorId(vendor_id) == False:
return HttpResponse('<h2>404<br>Invalid Vendor Id.</h2>')
else:
vendor_details = vendors.getVendorData(vendor_id)
.....
return render(request, 'vendor_data.html', context_dict)
my urls.py:
url(r'^vendor_data/', views.vendorData, name='vendor_data'),
If i dont pass any argument then it shows the HttpResponse from my views method.
If i pass argument vendor_id like this:
return HttpResponseRedirect(reverse('vendor_data', kwargs={'vendor_id':vendor_id}))
It throws an error. The traceback is:
Traceback:
File "C:\Python27\lib\site-packages\django\core\handlers\base.py" in get_response
132. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\Manish\Desktop\ScratcherAdmin\ScratcherAdmin\vendors\views.py" in editVendorData
162. return HttpResponseRedirect(reverse('vendor_data', kwargs={'vendor_id':vendor_id}))
File "C:\Python27\lib\site-packages\django\core\urlresolvers.py" in reverse
579. return force_text(iri_to_uri(resolver._reverse_with_prefix(view, prefix, *args, **kwargs)))
File "C:\Python27\lib\site-packages\django\core\urlresolvers.py" in _reverse_with_prefix
496. (lookup_view_s, args, kwargs, len(patterns), patterns))
Exception Type: NoReverseMatch at /update_vendor_data/
Exception Value: Reverse for 'vendor_data' with arguments '()' and keyword arguments '{'vendor_id': u'20150001'}' not found. 1 pattern(s) tried: ['vendor_data/']
How to solve this?
What you are expecting inside your view is a GET parameter from query string. Something your expected URL should be something like,
www.example.com/vendor/?vendor_id=12345
And below,
return HttpResponseRedirect(reverse('vendor_data', kwargs={'vendor_id':vendor_id}))
will redirect you to something like,
www.example.com/vendor/12345
For which your view should expect an additional parameter vendor_id,
def vendorData(request, vendor_id):
and accordingly your rest of the code might change.
Solution to your problem:
return HttpResponseRedirect("{}?vendor_id={}".format(reverse('vendor_data'), vendor_id))
Related
I am trying to create a form(boqform) to post data into a model(boqmodel)
but I am getting this
typeerror is_valid() missing 1 required positional argument: 'self'
I need to display a form called boqform on html template and post the data user entered into boqmodel
my view:
def boqmodel1(request):
if boqform.is_valid():
form = boqform(request.POST)
obj=form.save(commit=False)
obj.save()
context = {'form': form}
return render(request, 'create.html', context)
else:
context = {'error': 'The post has been successfully created. Please enter boq'}
return render(request, 'create.html', context)
Traceback:
File "C:\Users\TRICON\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\handlers\exception.py" in inner
34. response = get_response(request)
File "C:\Users\TRICON\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\handlers\base.py" in _get_response
115. response = self.process_exception_by_middleware(e, request)
File "C:\Users\TRICON\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\handlers\base.py" in _get_response
113. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\TRICON\Desktop\ind\ind\boq\views.py" in boqmodel1
23. if boqform.is_valid():
Exception Type: TypeError at /boq/create/
Exception Value: is_valid() missing 1 required positional argument: 'self'
You're trying to call the instance function is_valid() on the class boqform. You need to get an instance of boqform first. Switching lines 1 and 2 of the function should fix the issue:
def boqmodel1(request):
form = boqform(request.POST)
if form.is_valid():
obj=form.save(commit=False)
obj.save()
context = {'form': form}
return render(request, 'create.html', context)
else:
context = {'error': 'The post has been successfully created. Please enter boq'}
return render(request, 'create.html', context)
In the webapp, to retrieve all the objects from a specific user I am using user pk. But to make url more readable I want to use username. The problem is in the django view, user pk in kwargs giving the correct values, but when I use username it shows error.
Here are my codes using 'username' as kwargs, that is returning keyerror,
views.py
class UserAllQuestionView(generic.ListView):
model = Question
template_name = 'mechinpy/user_profile_question.html'
context_object_name = 'user_all_questions'
def get_queryset(self):
return Question.objects.filter(user=self.kwargs['username'])
urls.py
path('m/user/<str:slug>/questions/', views.UserAllQuestionView.as_view(), name='user_profile_question_all'),
html
All User Questions
Traceback:
File "C:\Users\Bidhan\AppData\Local\Programs\Python\Python35\lib\site-packages\django\core\handlers\exception.py" in inner
34. response = get_response(request)
File "C:\Users\Bidhan\AppData\Local\Programs\Python\Python35\lib\site-packages\django\core\handlers\base.py" in _get_response
126. response = self.process_exception_by_middleware(e, request)
File "C:\Users\Bidhan\AppData\Local\Programs\Python\Python35\lib\site-packages\django\core\handlers\base.py" in _get_response
124. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\Bidhan\AppData\Local\Programs\Python\Python35\lib\site-packages\django\views\generic\base.py" in view
68. return self.dispatch(request, *args, **kwargs)
File "C:\Users\Bidhan\AppData\Local\Programs\Python\Python35\lib\site-packages\django\views\generic\base.py" in dispatch
88. return handler(request, *args, **kwargs)
File "C:\Users\Bidhan\AppData\Local\Programs\Python\Python35\lib\site-packages\django\views\generic\list.py" in get
142. self.object_list = self.get_queryset()
File "C:\Users\Bidhan\Desktop\Startup\mysite\mechinpy\views.py" in get_queryset
454. return Question.objects.filter(user=self.kwargs['username'])
Exception Type: KeyError at /m/user/bidhan/questions/
Exception Value: 'username'
Mismatch in URL parameter names
Given I understand your question correctly, you pass the username as a slug to the view, like:
path(
'm/user/<str:slug>/questions/',
views.UserAllQuestionView.as_view(),
name='user_profile_question_all'
),
You name this parameter slug however, but in your view, you call self.kwargs['username']. You thus need to change one of the two. For example:
path(
'm/user/<str:username>/questions/',
views.UserAllQuestionView.as_view(),
name='user_profile_question_all'
),
Furthermore it will probably still not work. If I understand it correctly, your Question class has a ForeignKey to the User model. A User is not the same as its textual representation (for example by means of a username), so the filter will look like:
class UserAllQuestionView(generic.ListView):
model = Question
template_name = 'mechinpy/user_profile_question.html'
context_object_name = 'user_all_questions'
def get_queryset(self):
return Question.objects.filter(user__username=self.kwargs['username'])
Using the user_id instead
That being said, it might be better to user the id of the User instead, which will likely introduce less confusion (for example what if a user manages to use a username with a slash in it, then the URL will no longer work). So a more safe approach might be:
path(
'm/user/<int:userid>/questions/',
views.UserAllQuestionView.as_view(),
name='user_profile_question_all'
),
class UserAllQuestionView(generic.ListView):
model = Question
template_name = 'mechinpy/user_profile_question.html'
context_object_name = 'user_all_questions'
def get_queryset(self):
return Question.objects.filter(user_id=self.kwargs['userid'])
and in the template write it like:
All User Questions
I am trying to make a view that i can use in multiple apps with different redirect urls:
Parent function:
def create_order(request, redirect_url):
data = dict()
if request.method == 'POST':
form = OrderForm(request.POST)
if form.is_valid():
form.save()
return redirect(redirect_url)
else:
form = OrderForm()
data['form'] = form
return render(request, 'core/order_document.html', data)
Child function:
#login_required()
def admin_order_document(request):
redirect_url = 'administrator:order_waiting_list'
return create_order(request, redirect_url)
When i'm trying to call admin_order_document function i'm getting:
Traceback (most recent call last):
File "/home/project/venv/lib/python3.5/site-packages/django/core/handlers/exception.py", line 41, in inner
response = get_response(request)
File "/home/project/venv/lib/python3.5/site-packages/django/core/handlers/base.py", line 187, in _get_response
response = self.process_exception_by_middleware(e, request)
File "/home/project/venv/lib/python3.5/site-packages/django/core/handlers/base.py", line 185, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
TypeError: create_order() missing 1 required positional argument: 'redirect_url'
If i remove redirect_url from both functions and manually add 'administrator:order_waiting_list' to redirect() it works, but i need to redirect to multiple urls. So, why am i getting this error?
url(r'^orders/create/', views.create_order, name='create_order')
This clearly is not going to work, since create_order requires redirect_url but there is no redirect_url kwarg in the regex r'^orders/create/'.
Perhaps you want to use the admin_order_document view here instead:
url(r'^orders/create/', views.admin_order_document, name='create_order')
Note you should add a trailing dollar, i.e. r'^orders/create/$' unless you want to match orders/create/something-else as well as orders/create/.
If you didn't changed the regular url
urlpatterns = [
url(r'^admin/', admin_site.urls),
...
]
of your admin site you need to call your function like that:
#login_required()
def admin_order_document(request):
redirect_url = 'admin:order_waiting_list'
return create_order(request, redirect_url)
That should fix your problem.
I'm using django-rest-auth for user signup and verify email.
I'm able to successfully send the email when a user signs up. Howvever, on email verification, I'm getting this error with the following traceback:
File "/Library/Python/2.7/site-packages/django/core/handlers/base.py" in get_response
111. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/Library/Python/2.7/site-packages/django/views/generic/base.py" in view
69. return self.dispatch(request, *args, **kwargs)
File "/Library/Python/2.7/site-packages/django/views/generic/base.py" in dispatch
87. return handler(request, *args, **kwargs)
File "/Library/Python/2.7/site-packages/django/views/generic/base.py" in get
155. return self.render_to_response(context)
File "/Library/Python/2.7/site-packages/django/views/generic/base.py" in render_to_response
130. template=self.get_template_names(),
File "/Library/Python/2.7/site-packages/django/views/generic/base.py" in get_template_names
142. "TemplateResponseMixin requires either a definition of "
Exception Type: ImproperlyConfigured at /rest-auth/registration/account-confirm-email/vjohhnrf6xpkmn1jxbzaopdn0g79tdyofumeeuyuehcuja8slyz7nzq1idyifcqk/
Exception Value: TemplateResponseMixin requires either a definition of 'template_name' or an implementation of 'get_template_names()'
Any idea on how to fix this ?
While Ricardo's answer is correct, it didn't do much to help me solve my problem. This is what I needed to do for my master urls.py:
from allauth.account.views import confirm_email
.....
url(r'^accounts-rest/registration/account-confirm-email/(?P<key>.+)/$', confirm_email, name='account_confirm_email'),
Make sure that the beginning of the url spec starts with whatever path you are using for allauth REST calls.
Of course, the above is for using the built-in view handling the confirmation.
When you use confirmation email you have two ways to do it.
Using the specified by the API or creating yours. By default it uses django-allauth and a TemplateView on reverse can be used.
If you create yours, you may have to override account_confirm_email and then post to verification_mail.
In urls.py it is defined just reverse so, depending on what you are trying to do you will have first to create your own account_confirm_email, get the required key and post it to verify-email. Here there is more information about this bug.
For the new Django versions re_path url resolver method works properly with this (?P.+) url regex.
from django.urls import re_path
re_path('rest-auth/registration/account-confirm-email/(?P<key>.+)/', CustomConfirmEmailView.as_view(), name='account_confirm_email')
Also I have customized allauth ConfirmEmailView get() method in order to redirect properly
from allauth.account.views import ConfirmEmailView
from django.contrib.auth import get_user_model
class CustomConfirmEmailView(ConfirmEmailView):
def get(self, *args, **kwargs):
try:
self.object = self.get_object()
except Http404:
self.object = None
user = get_user_model().objects.get(email=self.object.email_address.email)
redirect_url = reverse('user', args=(user.id,))
return redirect(redirect_url)
I also have the problem as I read the tutorialHere is the link ,it shows the problem as TemplateResponseMixin requires either a definition of 'template_name' or an implementation of 'get_template_names()'
solution:
I change the location of templates filer and change the templates in the setting.py
1. In the App_Name file,I add the New folder Named:templates
2. In the settings.py: TEMPLATES = [{'DIRS': [BASE_DIR+"/templates",],}]
I am using Django-registration-email in my Django project. In there documentation (Django-Registration-Email), I am instructed to add REGISTRATION_EMAIL_REGISTER_SUCCESS_URL in the settings.py. However, this is causing the type error:
'str' object is not callable
In the settings.py, I set the redirect url as such:
REGISTRATION_EMAIL_REGISTER_SUCCESS_URL = '/accounts/register/complete/'
And the the url is copied as such:
url(
r'^accounts/register/$',
RegistrationView.as_view(
template_name='registration/registration_form.html',
form_class=CustomEmailRegistrationForm,
get_success_url=getattr(
settings,'REGISTRATION_EMAIL_REGISTER_SUCCESS_URL',
lambda request, user:'/'),
),
name='registration_register',
),
And the debug information told me that the first error comes from /local/lib/python2.7/site-packages/registration/views.py in form_valid
The indicated error line is
success_url = self.get_success_url(request, new_user)
The whole block is
def form_valid(self, request, form):
new_user = self.register(request, **form.cleaned_data)
success_url = self.get_success_url(request, new_user)
# success_url may be a simple string, or a tuple providing the
# full argument set for redirect(). Attempting to unpack it
# tells us which one it is.
try:
to, args, kwargs = success_url
return redirect(to, *args, **kwargs)
except ValueError:
return redirect(success_url)
The traceback is:
Traceback:
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response
114. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/views/generic/base.py" in view
69. return self.dispatch(request, *args, **kwargs)
File "/Library/Python/2.7/site-packages/registration/views.py" in dispatch
79. return super(RegistrationView, self).dispatch(request, *args, **kwargs)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/views/generic/base.py" in dispatch
87. return handler(request, *args, **kwargs)
File "/Library/Python/2.7/site-packages/registration/views.py" in post
35. return self.form_valid(request, form)
File "/Library/Python/2.7/site-packages/registration/views.py" in form_valid
83. success_url = self.get_success_url(request, new_user)
Exception Type: TypeError at /accounts/register/
Exception Value: 'str' object is not callable
Can anyone help me to solve this issue? Thanks a lot! I am stuck by this problem for one whole day!
OK, when you use
get_success_url=getattr(
settings,'REGISTRATION_EMAIL_REGISTER_SUCCESS_URL',
lambda request, user:'/'),
)
in your url handler, you are setting get_success_url as a string. You are then calling it in form_valid, as a function, trying to pass it variables.
Finally, I find where is the problem: REGISTRATION_EMAIL_REGISTER_SUCCESS_URL is expecting a function rather than a string
So, I should add an one-line function in the settings.py
REGISTRATION_EMAIL_REGISTER_SUCCESS_URL = lambda request, user: '/activate/complete/'
Anyway, I still would like to move to allauth since django-registration-email is no longer maintained.