how to reverse page after deleting any data in django? - django

i wanted to redirect my page to index after deleting row so i use `
return HttpResponseRedirect(reverse('index'))
to reverse . i wanted thishttp://127.0.0.1:8000/indexbut it is showinghttp://127.0.0.1:8000/index/index`
what is the proble please help me.
this is my view.py
`
def index(request):
return render(request, "card/index.html")
def delete(request, id):
dishes = dish.objects.get(id=id)
dishes.delete()
return HttpResponseRedirect(reverse('index'))
this is urls.py
path('index', views.index, name="index"),
path('check', views.check, name="check"),
path('delete/<int:id>', views.delete, name='delete'),
`

from django.shortcuts import render, redirect
def index(request):
return render(request, "card/index.html")
def delete(request, id):
dishes = dish.objects.get(id=id)
dishes.delete()
return redirect("/index/")

Try using the conventional method of reverse('app_name:url_name').
2nd method: Try passing the path directly in reverse like reverse('/index')

Related

Django CreateView redirect to UpdateView if already have an object created

I have tried how to check(using get() function) inside CreateView. so when we try to access CreateView URL, this view will check is there an object has been created. if yes, it will redirect to that object UpdateView URL. but the problem is I don't know how to reverse it.
urls.py
app_name = 'product'
urlpatterns = [
url(r'^$', pglist, name='list'),
url(r'^create/$', pcreate, name='create'),
url(r'^(?P<slug>[\w-]+)/$', pdetail, name='detail'),
url(r'^(?P<slug>[\w-]+)/update/$', pupdate, name='update'),
url(r'^redire/$', ered, name='redire'),
views.py
CreateView class
def get(self, *args, **kwargs):
if self.model.objects.get(user=self.request.user):
return redirect("product:update", kwargs={'slug': ??? I HAVE NO IDEA HOW TO DOING THIS PART ???slug})
else:
return redirect("product:create")
if I change the line into ==> return redirect("pages:update"), CreateView URL show
NoReverseMatch at /create/
Reverse for 'update' with no arguments not found. 1 pattern(s) tried: ['(?P<slug>[\\w-]+)/update/$']
so, what it should be?
return redirect("product:update", kwargs={'slug': ??? I HAVE NO IDEA HOW TO DOING THIS PART ???slug})
Well I would hazard a guess you have a slug field on your model, and you could provide the slug to the reverse method's kwargs like so:
return redirect(
"product:update",
kwargs={'slug': self.model.objects.get(user=self.request.user).slug}
)

django redirect after form submission not working

new to django
so this one probably has a very simple answer but i cannot for the life of me find the specific solution to this. I am simply trying to redirect to a new URL after a form submission with a FileField.
I can navigate to the URL separately and it works fine.
The file uploads correctly so I know it is validated correctly.
But the redirect returns the following error:
Reverse for 'success' not found. 'success' is not a valid view function or pattern name.
I have tried a bunch of different naming conventions, but none has worked. It looks to me like I have setup the URL and passed it correctly.
Would really appreciate some help with this. The simplest problems are the most frustrating!
Here are the views.
from django.shortcuts import render, redirect
from django.http import HttpResponse, HttpResponseRedirect
from django.urls import reverse
from .forms import InvestmentReportForm
def upload(request):
if request.method == 'POST':
form = InvestmentReportForm(request.POST, request.FILES)
if form.is_valid():
form.save()
return redirect('success')
else:
form = InvestmentReportForm()
return render(request, 'app/upload.html', {'form': form})
def success(request):
return HttpResponse("File successfully uploaded")
And my urls.py:
app_name = 'app'
urlpatterns = [
path('', views.index, name='index'),
path('upload/', views.upload, name='upload'),
path('success/', views.success, name='success'),
path('performance/', views.performance, name='performance'),
]
The answer was simple as I suspected. For others, if you use a namespace for a set of url patterns, you have to refer to that namespace when calling those urls. For this example:
return redirect('app:success')
def upload(request):
if request.method == 'POST':
form = InvestmentReportForm(request.POST, request.FILES)
if form.is_valid():
form.save()
return HttpResponseRedirect('success/')
else:
form = InvestmentReportForm()
return render(request, 'app/upload.html', {'form': form})

Use Django sessions in URL

I currently am using Django to have users enter information via a form, and the data is then saved as a session. I then use this session to call the entered data in other views. I was wondering if it is possible to use this entered data stored in these sessions in my urls?
def search(request):
result = {}
context = RequestContext(request)
t = request.session.get("tick")
if request.method == 'POST':
search = Search(data=request.POST)
if search.is_valid():
ticker = search.cleaned_data['search']
request.session["tick"] = ticker
else:
print search.errors
else:
search = Search()
return render_to_response('ui/search.html', {"result":result}, context)
and here is my corresponding urls.py:
url(r'^search/$', views.search, name='search'),
Is there any way I can use the session that is saved as 't = request.session.get("tick")' in my urls so I could get the urls to correspond with the data the user entered? For example if the user entered, 'hello' then my urls would show /search/hello.
Thanks.
Yes, you can do it like this:
urls.py
url(r'^search/$', views.search, name='search'),
url(r'^search/(?P<query>.+)/$', views.search, name='search'),
views.py
from django.http import HttpResponseRedirect
from django.core.urlresolvers import reverse
def search(request, query=None):
result = {}
context = RequestContext(request)
if request.method == 'POST':
search = Search(data=request.POST)
if search.is_valid():
ticker = search.cleaned_data['search']
return HttpResponseRedirect(reverse('search', kwargs={'query': ticker}))
else:
print search.errors
else:
search = Search()
return render_to_response('ui/search.html', {"result":result}, context)

Creating Django sessions

I am facing a problem while building a Django web app.
I want that if a user logs into his account, his session should be stored and when he agains visits the login page ,he should be redirected to his home page. I have tried using
Here is my code.
Views.py
from django.http import HttpResponse
from django.shortcuts import render_to_response
from django.contrib.auth.decorators import login_required
from django.template import RequestContext
def index(request):
return HttpResponse("Index Page")
#login_required
def home(request):
ctx = {}
return render_to_response('auth/home.html',ctx, context_instance = RequestContext(request))
Urls.py
from django.conf.urls.defaults import *
from django.contrib.auth.views import login, logout
urlpatterns = patterns('',
url(r'^$','apps.auth.views.index'),
)
urlpatterns = patterns('',
url(r'cc/', login, kwargs = {'template_name' : 'auth/cc.html'} , name = 'cc_login'),
url(r'logout/', logout, name = 'cc_logout'),
url(r'home/','apps.auth.views.home', name = 'cc_home'),
)
I ran into the same situation with my django project.
I solved it by making a view that was similar too:
def login_page(request):
if request.user.is_authenticated():
return redirect(<insert your desired page here>)
else:
return render(<whatever the login page is>)
This way, if the user is logged in, they will be redirected to whatever page you want them to be.
EDIT:
In response to the comments below, I am modifying my answer (original is still above).
Here is what I have done to solve your problem.
from django.contrib.auth.views import login
def custom_login(request, **kwargs):
"""
Redirects the user to the desired page if they are authenticated
"""
if request.user.is_authenticated():
return redirect(<whatever page or view you want them to go to>)
else:
return login(request, **kwargs)
For example, your kwargs could be {'template_name': 'your_login_template.html', 'authentication_form': YourCustomRegistrationFormClass}
If you're using the standard login and registration procedures, just leave the kwargs part blank.
I'm fairly new to Django, but have you tried overriding the default login view?
views.py
from django.contrib.auth import views as auth_views
from django.shortcuts import redirect
def login(request, *args, **kwargs):
if request.method == 'POST':
request.session.set_expiry(0) # Remember user session
if request.user.is_authenticated():
return redirect(USER_PAGE_ADDRESS)
return auth_views.login(request, *args, **kwargs)
urls.py
urlpatterns = patterns('',
url(r'cc/', APP_NAME.views.login, kwargs = {'template_name' : 'auth/cc.html'} , name = 'cc_login'),
...
)

Django retrieve data from db to complete a url pattern

I know this is an easy question, I am just not getting something...so thank you for your patience and advice.
I have a view that asks a user to register to use our app. The data he/she submits is stored in a database and he is sent off to another page to set up the application:
#views.py
def regPage(request, id=None):
form = RegForm(request.POST or None,
instance=id and UserRegistration.objects.get(id=id))
# Save new/edited pick
if request.method == 'POST' and form.is_valid():
form.save()
return HttpResponseRedirect('/dev/leaguepage/')
user_info = UserRegistration.objects.all()
context = {
'form':form,
'user_info' :user_info,
}
return render(request, 'regpage.html', context)
Rather than sending ALL users to the same page '/dev/leaguepage/', I need to send each user to his own page based on the PK in the database like: '/dev/PrimaryKey/' I am not sure how to make this happen either on the views file or in the URLs.py file:
#urls.py
from django.conf.urls.defaults import patterns, include, url
from acme.dc_django import views
urlpatterns = patterns('',
url(r'^leaguepage/$','acme.dc_django.views.leaguePage'),
url(r'^$', 'acme.dc_django.views.regPage'),
)
Thank you for your help!
dp
Updated code:
#url
url(r'^user/(?P<id>\d+)/$','acme.dc_django.views.leaguePage', name="league_page"),
#view
def regPage(request, id):
form = RegForm(request.POST)
# Save new/edited pick
if request.method == 'POST' and form.is_valid():
form.save()
return HttpResponseRedirect(reverse('league_page', kwargs={'id' :id}))
#return HttpResponseRedirect('/dev/leaguepage/')
user_info = UserRegistration.objects.all()
context = {
'form':form,
'user_info' :user_info,
}
return render(request, 'regpage.html', context)
You can do a reverse lookup on your leaguePage to do your redirect, passing in the values you need to resolve the pattern. You'll need to add a name to the URL pattern you want to reverse, but basically the syntax is:
return HttpResponseRedirect(reverse('my_detail', args=(), kwargs={'id' : id}))
Example URL pattern and view:
urlpatterns = patterns('my_app.views',
url(r'^my-pattern/(?P<id>\d+)/$', 'my_action', name='my_detail'),
)
def my_action(request, id):
#do something
Hope that helps you out.