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.
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))
def login_page(request):
if request.user.is_authenticated():
return redirect('cc_home')
else:
return render_to_response(request,'auth/cc.html')
Urls.py
from django.conf.urls.defaults import *
from django.contrib.auth.views import login, logout
urlpatterns = patterns('',
url(r'cc/', 'apps.auth.views.login_page', name = 'cc_login'),
url(r'logout/', logout, name = 'cc_logout'),
url(r'home/','apps.auth.views.home', name = 'cc_home'),
)
And here is my template cc.html
<form action ="." method = POST>
{% csrf_token %}
{{ form.as_p }}
<input type = "submit" value = "login">
</form>
</body>
home.html
{{ user }} 's profile
Logout
When I browse to CC url it should first asks the user's credentials. After successful login, it should redirect to the user's home url, which is running fine. But, when the user again browse to CC url (), he should be redirected it to his home page.
While Debugging, I found that it is not able to render the form when the user is not authenticated. It does not shows the Django's inbuilt form provided in the CC.html, it just shows the Login button.
How do I render the form. Kindly suggest.
Thanks
But you haven't passed any form to the template to render! You need to instantiate the login form and pass it to the template context, otherwise {{ form }} doesn't refer to anything.
You should be able to use the default form if you replace;
url(r'cc/', 'apps.auth.views.login_page', name = 'cc_login'),
with;
url(r'cc/', login, {template_name: 'cc.html'}),
May be the error is in the login_page method. try to fix it like this
def login_page(request):
if request.user.is_authenticated():
return redirect('cc_home')
else:
return render_to_response('auth/cc.html',{} context_instance = RequestContext(request))
i believe that the request in your render_to_response cause the problem
Related
from django.contrib import admin
from django.urls import path
from . import views
urlpatterns = [
path('', views.Index, name='Index'),
path('register/', views.register, name='register'),
path('login/', views.login, name='login'),
path('register/reg_done/', views.reg_done,),
]
Above is my urls.py. What I am trying is to get my reg_done page come up as after a user click on the submit button to save the regestration info. But its showing that this page not found.
I tried to change the path in form action as register/reg_done/. But then it showed the same error with register/register/reg_done.
In HTML I am giving form action the value"/reg_done", that's it.
Below is my views.py
from django.shortcuts import render
from django.http import HttpResponse
import sqlite3
# Create your views here.
def Index(request):
return render(request, 'index.html')
def register(request):
return render(request, 'register.html')
def login(request):
return render(request, 'login.html')
def reg_done(request):
name = request.POST.get('name')
mail = request.POST.get('mail')
phone = request.POST.get('phone')
psw = request.POST.get('psw')
pswr = request.POST.get('pswr')
all = [name, mail, phone, psw, pswr]
return render(request, 'reg_done.html', {'all':all})
I assume the register view handles the registration. In the form for the register.html file,
Do:
<form action="/register/reg_done" method="post">
your form fields here
</form>
if you want to go with pure HTML solution. If you want something more Django-ly, use the url template tag:
<form action="{% url 'reg_done' %}" method="post">
your form fields here
</form>
I'll advice the later to ensure you avoid "premium developer tears".
In views.py, add this to the top of the file:
from django.views.decorators.http import require_POST
Then edit the reg_done view to:
#require_POST
def reg_done(request):
name = request.POST.get('name')
mail = request.POST.get('mail')
phone = request.POST.get('phone')
psw = request.POST.get('psw')
pswr = request.POST.get('pswr')
all = [name, mail, phone, psw, pswr]
return render(request, 'reg_done.html', {'all':all})
Next, change the path for reg_done in urls.py to:
path('register/reg_done/', views.reg_done, name='reg_done'),
The problem lies in your usage of urls. You should reference the reg_done view as /register/reg_done instead of register/reg_done. The former treats it as an url relative to the domain name while the latter treats it as relative to the current page. That's why coming from the register view and going to the latter yields register/register/reg_done rather than what you want: register/reg_done.
I have a basic login, sign up html page in my Django project: the login page redirects to the user_login function in views.py as follows:
<form action="{% url 'user_login' %}" method="POST">. //rest of the code
In urls.py the request is getting forwaded correctly:
.......#beginnning code
path('user_login', views.user_login, name='user_login'),
path('portfolio', views.portfolio, name='portfolio'),
......
In views.py this is my user_login code to authenticate the user and redirect the user to a 'portfolio.html' page if the user credentials are correct.
I have imported User, Login class as follows:
from django.http import HttpResponseRedirect
from django.shortcuts import render
from .models import Profile
from django.contrib.auth.models import User
from django.contrib.auth import authenticate, login
# Create your views here.
def index(request):
return render(request, 'mysite/index.html')
def user_login(request):
if request.method == 'POST':
name_r = request.POST.get('name')
password_r = request.POST.get('password')
user = authenticate(username=name_r, password=password_r)
if user:
login(request, user)
#below line might be incorrect
return HttpResponseRedirect('mysite/portfolio.html')
else:
return render(request, 'mysite/login.html')
#rest of the code for signup which is working perfectly.
Whenever i click on Login page, the login page never loads in the first place, let alone checking whether authentication is taking place or not.
The error occurring is as follows:
I am not sure exactly where the error is occurring and what solution must be applied to it.
Your view never returns anything if request.method is not POST.
I'm having multiple forms around my website.
However, a have a particular form that is working in the home page (index.html), but when coping this particular form in a section of my site it doesn't work anymore (on this section, if I return to home everything works as expected).
What am I missing?
Views.py:
from django.shortcuts import render, HttpResponse, HttpResponseRedirect
from .models import Treasure, TamaniosCantidades
from .forms import TreasureForm, TamaniosCantidadesForm, LoginForm
from django.contrib.auth import authenticate, login, logout
# Create your views here.
def index(request):
treasures = Treasure.objects.all()
form = TreasureForm()
tamanioscantidades_form = TamaniosCantidadesForm()
return render(request, 'main_app/index.html', {'treasures': treasures,
'form': form,
'tamanioscantidades_form': tamanioscantidades_form})
def productos(request):
treasures = Treasure.objects.all()
form = TreasureForm()
return render(request, 'main_app/productos.html', {'treasures': treasures,
'form': form})
def die_cut(request):
tamanioscantidades_form = TamaniosCantidadesForm()
return render(request, 'main_app/die-cut-stickers.html', {'tamanioscantidades_form': tamanioscantidades_form})
def post_tamanioscantidades(request):
form = TamaniosCantidadesForm(request.POST)
if form.is_valid():
tamanioscantidades = TamaniosCantidades(tamanios=form.cleaned_data['tamanios'],
cantidades=form.cleaned_data['cantidades'])
# tamanioscantidades = tamanioscantidades_form.save(commit = False)
# tamanioscantidades.usuario = request.user
tamanioscantidades.save()
return HttpResponseRedirect('/')
def post_treasure(request):
form = TreasureForm(request.POST)
if form.is_valid():
treasure = Treasure(name=form.cleaned_data['name'],
value=form.cleaned_data['value'])
treasure.save()
return HttpResponseRedirect('/')
urls.py:
app_name = 'main_app'
urlpatterns = [
path('', views.index),
path('productos/', views.productos),
path('productos/die-cut-stickers', views.die_cut, name='die-cut-stickers'),
path('post_url/', views.post_treasure, name='post_treasure'),
path('post_url_tamanioscantidades/', views.post_tamanioscantidades, name='post_tamanioscantidades'),
]
*html**:
<div class="col-md-6 border border-primary rounded border-3">
<div class="m-5">
<div class="row">
<form action="post_url_tamanioscantidades/" method="post">
{% csrf_token %}
{{ tamanioscantidades_form.as_p }}
<input type="submit" value="Submit"/>
</form>
</div>
</div>
As I said, this form works in home, but when coping the same code in a section of my site the submit button does not save the form in database.
It returns:
Page not found (404)
Request Method: POST
Request URL: http://127.0.0.1:8000/productos/post_url_tamanioscantidades/
Using the URLconf defined in gallito.urls, Django tried these URL patterns, in this order:
admin/
productos/
productos/die-cut-stickers [name='die-cut-stickers']
post_url/ [name='post_treasure']
post_url_tamanioscantidades/ [name='post_tamanioscantidades']
accounts/
The current path, productos/post_url_tamanioscantidades/, didn't match any of these.
The problem is the form is being submitted to http://127.0.0.1:8000/productos/post_url_tamanioscantidades/ which does not exist instead you want it to submit at http://127.0.0.1:8000/post_url_tamanioscantidades/
So in your form html start the form action with /
<form action="/post_url_tamanioscantidades/" method="post">
I'm new to Django and am having a bit of trouble with forms. I'm trying to display a single text input so that users can enter their phone number and it will be sent to my email. I'm actually going to have it stored in a postgre database but want to get the basics down first. The submit button is being displayed but the text input field isn't. I tried putting the forms.py inside of the views.py to see if the PhoneForm() function and file wasn't importing but that didn't do anything.
views.py
from django.shortcuts import render, redirect
from django.http import HttpResponse, HttpResponseRedirect
from django.core.mail import send_mail
from .forms import PhoneForm
# Create your views here.
def index(request):
# Render the index.html template with a context dictionary
return render(request, "index.html")
def get_number(request):
# if this is a POST request we need to process the form data
if request.method == 'POST':
#create a form instance
form = PhoneForm(request.POST)
if form.is_valid():
cd = form.cleaned_data
send_mail(
cd['phone_form'],
['siteadmin#example.com'],
)
return HttpResponseRedirect('/thanks/')
else:
form = PhoneForm()
return render(request, 'index.html', {'form': form})
index.html
<form action="" method="post">
{% csrf_token %}
{{ form }}
<input type="submit" value="Submit" />
</form>
forms.py
from django import forms
class PhoneForm(forms.Form):
phone_form = forms.CharField(widget=forms.TextInput())
EDIT: Adding urls.py (the one in the app)
from django.conf.urls import include, url
from django.contrib import admin
from . import views
urlpatterns = [
url(r'^$', views.index, name='index'),
url(r'^$', views.get_number, name='get_number'),
]
Both urls in urls.py have the same expression r'^$' and django looks for them in order, therefore the first one (index) will always be selected. This links to the index view not the get_number view. This means the form is not passed to the template and the form does not show up.
To solve this move url(r'^$', get_number), to the top of 'urlpatterns'.
Change from {{form}} to {{form.phone_form}} in index.html
I'm trying to create a marketplace website similar to craigslist.
I created a form according to the Django tutorial "Working with forms", but I don't know how to render information I got from the POST forms.
I want to make information(subject,price...etc) that I got from POST show up on another page like this. http://bakersfield.craigslist.org/atq/3375938126.html and, I want the "Subject"(please look at form.py) of this product(eg.1960 French Chair) to show up on another page like this. http://bakersfield.craigslist.org/ata/ }
Can I get some advice to handle submitted information?
Here's present codes. I'll appreciate all your answers and helps.
<-! Here's my codes -->
◆forms.py
from django import forms
class SellForm(forms.Form):
subject = forms.CharField(max_length=100)
price = forms.CharField(max_length=100)
condition = forms.CharField(max_length=100)
email = forms.EmailField()
body = forms.TextField()
◆views.py
from django.shortcuts import render, render_to_response
from django.http import HttpResponseRedirect
from site1.forms import SellForm
def sell(request):
if request.method =="POST":
form =SellForm(request.POST)
if form.is_valid():
subject = form.cleaned_data['subject']
price = form.cleaned_data['price']
condition = form.cleaned_data['condition']
email = form.cleaned_data['email']
body = form.cleaned_data['body']
return HttpResponseRedirect('/books/')
else:
form=SellForm()
render(request, 'sell.html',{'form':form,})
◆urls.py
from django.conf.urls import patterns, include, url
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
url(r'^sechand/$','site1.views.sell'),
url(r'^admin/', include(admin.site.urls)),
)
◆sell.html
<form action = "/sell/" method = "post">{% csrf_token%}
{{ form.as_p }}
<input type = "submit" value="Submit" />
</form>
I assume you have a Sell model/table in your db(where you store the users' "sells"), otherwise it wouldn't make any sense. This means you can save yourself some time and use a ModelForm,
instead of a simple Form. A model form takes a database table and produces an html form for it.
forms.py
from django.forms import ModelForm
from yourapp.models import Sell
class SellForm(ModelForm):
class Meta:
model = Sell
In your views.py you need one more view that displays the Sells that your users have
posted for others to see. You also need an html template that this view will render with context about each Sell.
sell_display.html
{% extends 'some_base_template_of_your_site.html' %}
{% block content %}
<div id="sell">
<h3> {{ sell.subject }}</h3>
<p> {{ sell.condition }}</p>
<p> {{ sell.body }}</p>
<!-- the rest of the fields.. -->
</div>
{% endblock %}
We also need a new url entry for the displaying of a specific Sell
urls.py
from django.conf.urls import patterns, include, url
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
# Changed `sell` view to `sell_create`
url(r'^sechand/$','site1.views.sell_create'),
# We also add the detail displaying view of a Sell here
url(r'^sechand/(\d+)/$','site1.views.sell_detail'),
url(r'^admin/', include(admin.site.urls)),
)
views.py
from django.http import HttpResponseRedirect
from django.shortcuts import render_to_response, get_object_or_404
from yourapp.models import Sell
from yourapp.forms import SellForm
def sell_detail(request, pk):
sell = get_object_or_404(Sell, pk=int(pk))
return render_to_response('sell_display.html', {'sell':sell})
def sell_create(request):
context = {}
if request.method == 'POST':
form = SellForm(request.POST)
if form.is_valid():
# The benefit of the ModelForm is that it knows how to create an instance of its underlying Model on your database.
new_sell = form.save() # ModelForm.save() return the newly created Sell.
# We immediately redirect the user to the new Sell's display page
return HttpResponseRedict('/sechand/%d/' % new_sell.pk)
else:
form = SellForm() # On GET request, instantiate an empty form to fill in.
context['form'] = form
return render_to_response('sell.html', context)
This is enough to get you going I think. There are patterns to make these things more modular and better, but I don't want to flood you with too much information, since you are a django beginner.