I have some question about redirect. When i am using mapviews.index there are no errors but when i am using mpviews.index
Reverse for 'mythicPlus.views.index' not found. 'mythicPlus.views.index' is not a valid view function or pattern name
What should i do to fix this problem?
shopping_cart/views.py
from mythicPlus import views as mpviews
from mainPage import views as mapviews
return redirect(reverse(mpviews.index))
mythicPlus/urls.py
path('', views.index, name = 'mythicPlus_list'),
mythicPlus/views.py
def index(request):
boost_keys_list = mythicPlusOrders.objects.all()
context = {'object_list': boost_keys_list}
return render(request, "mythicPlus/posts.html", context)
mainPage/views.py
def index(request):
return render(request, 'mainPage/homePage.html')
reverse uses the viewname from the url so in path('my-url/', views.MyView.as_view(), name="my-view") the viewname is my-view
You need to provide that in your reverse. Or you could just do
redirect(mpviews.index)
Related
I need to send back response with product details, so I use HttpResponseRedirect and reverse. It requires the app_name:name, so I tried something like below, but I get error:
django.urls.exceptions.NoReverseMatch: Reverse for 'product' not found. 'ProductViewSet' is not a valid view function or pattern name.
This is my view:
#api_view(['POST'])
#permission_classes([IsAuthenticated])
def bump(request, pk):
product = get_object_or_404(Product, id=pk)
product.bumps.add(request.user)
return HttpResponseRedirect(reverse('products:product', args=[pk]))
This is my urls:
app_name = 'products'
router = DefaultRouter()
router.register(r'', ProductViewSet)
urlpatterns = [
path('', include(router.urls), name='product'),
]
What is wrong in this code? I use the correct app_name and name.
What is wrong in this code? I use the correct app_name and name.
The path you use does not link to a view: it is a path that contains a lot of subpaths, all generated by the DefaultRouter.
You are using a router, this means that it will create different paths that will each have a specific name. These are documented in the documentation for the DefaultRouter [drf-doc].
You thus can visit this with:
from django.shortcuts import redirect
#api_view(['POST'])
#permission_classes([IsAuthenticated])
def bump(request, pk):
product = get_object_or_404(Product, pk=pk)
product.bumps.add(request.user)
return redirect('products:product-detail', pk)
I implemented some tests to check the status code of some pages, but this one with the reverse function throws me the error: django.urls.exceptions.NoReverseMatch: Reverse for 'ads.views.AdListView' not found. 'ads.views.AdListView' is not a valid view function or pattern name.
Reading the documentation and some answers on Stack Overflow I'm supposed to use either the view function name or the pattern name inside the parenthesis of the reverse function, but none of them seems to work.
Here's my code:
ads/tests/test_urls.py
from django.test import TestCase
from django.urls import reverse
class SimpleTests(TestCase):
def test_detail_view_url_by_name(self):
resp = self.client.get(reverse('ad_detail'))
# I've also tried: resp = self.client.get(reverse('ads/ad_detail'))
self.assertEqual(resp.status_code, 200)
...
ads\urls.py
from django.urls import path, reverse_lazy
from . import views
app_name='ads'
urlpatterns = [
path('', views.AdListView.as_view(), name='all'),
path('ad/<int:pk>', views.AdDetailView.as_view(), name='ad_detail'),
...
]
mysite/urls.py
from django.urls import path, include
urlpatterns = [
path('', include('home.urls')), # Change to ads.urls
path('ads/', include('ads.urls')),
...
]
ads/views.py
class AdDetailView(OwnerDetailView):
model = Ad
template_name = 'ads/ad_detail.html'
def get(self, request, pk) :
retrieved_ad = Ad.objects.get(id=pk)
comments = Comment.objects.filter(ad=retrieved_ad).order_by('-updated_at')
comment_form = CommentForm()
context = { 'ad' : retrieved_ad, 'comments': comments, 'comment_form': comment_form }
return render(request, self.template_name, context)
Any idea of what is causing the problem?
Since you use an app_name=… in your urls.py, you need to specify this as a namespace in the name of the view, so ads:ad_detail, and specify a primary key:
resp = self.client.get(reverse('ads:ad_detail', kwargs={'pk': 42}))
So here we visit the URL where 42 is used as value for the pk URL parameter.
This is a view written for my posts app in Django. The problem is that after filling the update form and submitting it happens successfully. But it creates confusion for the user because the same HTML page is there and how can I redirect into the updated object?
def post_update(request,id=None):
instance=get_object_or_404(Post,id=id)
if instance.created_user != request.user.username :
messages.success(request, "Post owned by another user, You are having read permission only")
return render(request,"my_blog/denied.html",{})
else :
form=PostForm(request.POST or None,request.FILES or None,instance=instance)
if form.is_valid():
instance=form.save(commit=False)
instance.save()
context={ "form":form,
"instance":instance }
return render(request,"my_blog/post_create.html",context)
As already suggested by #mdegis you can use the Django redirect function to redirect to another view or url.
from django.shortcuts import redirect
def view_to_redirect_to(request):
#This could be the view that handles the display of created objects"
....
perform action here
return render(request, template, context)
def my_view(request):
....
perform form action here
return redirect(view_to_redirect_to)
Read more about redirect here and here
You can pass positional or keyword argument(s) to the redirect shortcut using the reverse() method and the named url of the view you're redirecting to.
In urls.py
from news import views
url(r'^archive/$', views.archive, name='url_to_redirect_to')
In views.py
from django.urls import reverse
def my_view(request):
....
return redirect(reverse('url_to_redirect_to', kwargs={'args_1':value}))
More about reverse Here
You can use redirect from http shortcuts.
from django.shortcuts import redirect
def my_view(request):
...
object = MyModel.objects.get(...)
return redirect(object) #or return redirect('/some/url/')
Here is the link to official docs.
To redirect from a view to another view, you need to give the conbination of the app name "myapp", colon ":" and the view name "dest_view" which is set in the path in "myapp/urls.py" as shown below. And, you don't need to modify the path in "myapp/urls.py" if you pass data with session with request.session['key'] as shown below:
# "myapp/views.py"
from django.shortcuts import render, redirect
def redirect_view(request):
# Here
request.session['person'] = {'name': 'John', 'age': 27}
# Here
return redirect("myapp:dest_view")
def destination_view(request):
return render(request, 'myapp/index.html', {})
You need to give the view name "dest_view" to path() in "myapp/urls.py" as shown below:
# "myapp/urls.py"
from django.urls import path
from . import views
app_name = "myapp"
urlpatterns = [ # This is view name
path('dest/', views.destination_view, name="dest_view")
]
Then, this is Django Template:
# "myapp/index.html"
{{ request.session.person.name }} {# John #}
{{ request.session.person.age }} {# 27 #}
from django.urls import reverse
def my_view(request):
....
return redirect(reverse('url_to_redirect_to', kwargs={'args_1':value(object.id for specific id)}))
I am using Django authentication. Whenever a user logs in, I want to redirect him to /profile/user_id, being user_id a number. I can get the value of user_id by request.user.profile.id. In settings.py I have LOGIN_REDIRECT_URL = 'app_1:index'
app_1/urls.py:
url(r'^profile/$', views.index, name='index'),
# ex: /profile/5/
url(r'^profile/(?P<user_id>[0-9]+)/$', views.profile, name='profile'),
app_1/views.py (things I've also tried are commented):
def index(request):
userid = request.user.profile.id
#return render(request, 'app_1/index.html', context)
#return profile(request, request.user.profile.id)
#return render(request, 'app_1/user_prof.html', {'user': request.user.profile.id})
#return redirect(profile, user_id= request.user.profile.id)
return redirect('profile', user_id=userid)
def profile(request, user_id):
user = get_object_or_404(Profile, pk=user_id)
return render(request, 'app_1/user_prof.html', {'user': user})
I must be missing something because this should be easy but I'm stuck on it. Thanks in advance.
EDIT: The error I'm getting is Reverse for 'profile' not found. 'profile' is not a valid view function or pattern name.: http://dpaste.com/270YRJ9
Try using this instead
from django.urls import reverse
return redirect(reverse('profile', kwargs={"user_id": userid}))
Or this:
return redirect('app_1:profile', user_id=userid)
AoA,
I am trying to redirect to some view, but failed to do so.
here is the code
views.py
def logout(request):
c = {'username': 'Create Account', 'status': ''}
c.update(csrf(request))
response = render_to_response("home.html",c)
response.delete_cookie('id')
request.session['id'] = 'None'
return redirect('/home/')
def home(request):
#some code here
return render_to_response('blah blah')
urls.py
url(r'^home/$', 'contacts.views.home_Page'),
url(r'^logout/$', 'contacts.views.logout'),
the above code redirect me to -- let's suppose current URL(127.0.0.1/account)
it redirects me to (127.0.0.1/account/home) but i want to redirect to 127.0.0.1/home
how can I redirect to specific view ?
redirect(to[, permanent=False], *args, **kwargs) returns an HttpResponseRedirect to the appropriate URL for the arguments passed. You need to return the HttpResponseRedirect object in the view function.
BTW, you should try to avoid hardcoding urls in you code, instead you should use view names.
e.g:
urls.py:
url(r'^home/$', home, name='home_view')
...
view.py:
def logout(request):
...
redirect('home_view')
django provides a built-in logout that you should use:
from django.shortcuts import redirect
from django.contrib.auth import logout
def log_out(request):
logout(request)
return redirect('home')
Now 'home' can be many things; but the easiest way to make sure its pointing to the right place is to name your urls. So in your urls.py:
url(r'home/$', home, name='home')