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)
Related
I am trying to set up a user password change from built on this tutorial. Unfortunately, on success, this tutorial just returns the user to the change password form, which doesn't seem very satisfactory. So, I am attempting to redirect the user user to a success template.
My code is in an app called your_harmony
base.py
INSTALLED_APPS = [
...
'your_harmony',
...
]
urls.py
urlpatterns = [
...
url(r'^your-harmony/', include('your_harmony.urls')),
...
]
your_harmony/urls.py
urlpatterns = [
url(r'password/$', change_password, name='change_password'),
url(r'password_changed/$', password_changed, name='password_changed'),
]
views.py
def change_password(request):
if request.method == 'POST':
form = PasswordChangeForm(request.user, request.POST)
if form.is_valid():
user = form.save()
update_session_auth_hash(request, user) # Important!
messages.success(request, 'Your password was successfully updated!')
return redirect('password_changed')
else:
messages.error(request, 'Please correct the error below.')
else:
form = PasswordChangeForm(request.user)
url = 'registration/change_password.html'
return render(request, url, {'form': form})
def password_changed(request):
url = 'password_changed.html'
return render(request, url, {})
When I use the form to change the password and submit, the password is changed correctly, but I get the error
NoReverseMatch at /your-harmony/password_changed/
However, when I hover over the link to call the change password form, the url displayed in the browser is
127.0.0.1:8000/your-harmony/password
Can someone please point what I am doing wrong?
You can use this
from django.urls import reverse
return redirect(reverse('password_changed'))
after your success
and in your urls.py
from . import views
urlpatterns = [
url(r'password/$', views.change_password, name='change_password'),
url(r'password_changed/$', views.password_changed, name='password_changed'),
]
You should use namespaces
include('your_harmony.urls', namespace='whatever')
...
def f():
return redirect(reverse('whatever:password_changed'))
I'm trying to build a app in which every user has his own database content, but on one page/url some (chosen) database content is listed and publicly visible.
I did a lot of research, but cannot come up with the logic how this works. I have a username in the URL, but when I change it to other users names, the content is not changing... What step do I miss here?
views.py
def public_view(request, username):
if request.user.is_authenticated():
info = Profile.objects.filter(user=request.user)
instance = Parent.objects.filter(user=request.user)
childs = Child.objects.filter(user=request.user)
u = MyUser.objects.get(username=username)
context = {
'info': info,
'instance': instance,
'childs': childs,
'u': u,
}
return render(request, 'public/public_home.html', context)
else:
raise Http404
urls.py
from django.conf.urls import url
from django.contrib import admin
from . import views
urlpatterns = [
url(r'^user/(?P<username>\w+)/$', views.public_view, name='public_view'),
]
In your view you get data for current user using request.user in querysets.You should change your queryset's argument t u object:
def public_view(request, username):
if request.user.is_authenticated():
u = MyUser.objects.get(username=username)
info = Profile.objects.filter(user=u)
instance = Parent.objects.filter(user=u)
childs = Child.objects.filter(user=u)
context = {
'info': info,
'instance': instance,
'childs': childs,
'u': u,
}
return render(request, 'public/public_home.html', context)
else:
raise Http404
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})
I have a page which shows the user and their about. And in that, there's a link to update their about. But when I open that link it shows me with this error:
DoesNotExist at /profile/user/update_about/
User matching query does not exist.
And the traceback hightlights this line, which from the profile method in the views:
13. user = User.objects.get(username=unquote(user_name))
However this error does not occur when I load the profile method. It occurs only on the update_profile method in the views.
views.py
from django.shortcuts import render
from django.http import HttpResponseRedirect
from urllib import unquote
from django.contrib.auth.models import User
from models import About
from forms import AboutForm
# Create your views here.
def profile(request, user_name):
user = User.objects.get(username=unquote(user_name))
about = About.objects.get_or_create(user=user)
about = about[0]
return render(request, 'user_profile.html', {
'user':user,
'about_user':about
})
def update_about(request, user_name):
user = User.objects.get(username=unquote(user_name))
if request.method == 'POST':
form = AboutForm(request.POST)
if form.is_valid():
form.save()
return HttpResponseRedirect('/')
else:
about = About.objects.get(user=user)
form = AboutForm(initial={'dob':about.dob})
return render(request, 'update_about.html',{
'form':form
})
urls.py
urlpatterns = patterns('',
# Examples:
url(r'(?P<user_name>[\w#%.]+)/$', 'user_related.views.profile', name='profile'),
url(r'(?P<user_name>[\w#%.]+)/update_about/$', 'user_related.views.update_about', name='update_about'),
What is causing this? Your help will be very much appreciated. Thank you.
You forgot to add the caret sign (^) at the first position of regex. So the first regex matched "update_about/" part of the url.
Fixed code:
url(r'^(?P<user_name>[\w#%.]+)/$', 'user_related.views.profile', name='profile'),
url(r'^(?P<user_name>[\w#%.]+)/update_about/$', 'user_related.views.update_about', name='update_about'),
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.