How do i logout the user in the following django code? - python

What I am trying to do:
I am trying to log out the user whenever he/she clicks on the logout button.
What problem I am getting:
I get the following problem when I click on logout button:
My Code:-
article.html:
<div class="container">
<nav class="nav blog-nav">
<a class="nav-link" href="#">Library</a>
{% if user.is_authenticated %}
<a style="float: right;" class="nav-link" href="{% url 'librarysystem:Logout' %}">Logout</a>
<a style="float: right;" class="nav-link" href="#">{{ request.user.username }}</a>
{% if user.UserProfile.avatar == None %}
<a style="float: right;" class="nav-link" href="#"><img class="img-thumbnail" src="/static/defaultPic/defaultPic.png" class="img-responsive" alt = "Generic placeholder thumbnail"/></a>
{% else %}
<a style="float: right;" class="nav-link" href="#" class="thumbnail"><img class="thumbnail" src="{{ request.user.UserProfile.avatar }}" class="img-responsive"/></a>
{% endif %}
{% endif %}
</nav>
</div>
login View:
def loginUser(request):
data = {}
if request.method == "POST":
username = request.POST.get('username')
password = request.POST.get('password')
data['responseMessage'] = ''
user = authenticate(username=username,password=password);
if user is None:
data['response'] = False
else:
if user.is_active:
data['responseMessage'] = 'Already logged in.'
else:
login(request,user)
data['redirectTo'] = "/librarysystem/article/"
data['response'] = True
return JsonResponse(data)
logout View:
def logoutUser(request):
logout(request)
template = 'librarysystem/Elib.html'
return render(request, template)
urls.py:
from django.conf.urls import url
from .import views
urlpatterns = [
url(r'^register/$',views.registerUser),
url(r'^$', views.index, name="Index"),
url(r'^validateRegisterForm/$',views.validateRegisterForm),
url(r'^validateLoginForm/$',views.validateLoginForm),
url(r'^article/$', views.article, name="Article"),
url(r'^Login/$',views.loginUser, name="Login"),
url(r'^Logout/$',views.logoutUser, name="Logout"),
]

As the error log suggested:
global name 'logout' is not defined
You need to first import logout from django.contrib.auth.
Use this:
from django.contrib.auth import logout
Like this:
from django.contrib.auth import logout
def logoutUser(request):
logout(request)
template = 'librarysystem/Elib.html'
return render(request, template)
# Redirect to a success page.

Related

Django authentication problem in HTML not working

I wrote a small application for a social media site and I have a problem. I'm using {% if user.is_authenticated %} after I log in I'm getting the options in the navbar which should not be displayed for an authenticated user. The page keeps bouncing between two pages. I have made a video of the problem. Please have a look at it.
Video.
Files tree image:
File tree
base.html
<!DOCTYPE html>
{% load static %}
<html >
<head>
<title>Colab</title>
<link rel="stylesheet" type="text/css" href="{% static 'reg_sign_in_out/style.css' %}">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
</head>
<body>
<nav class="navbar navbar-expand-lg navbar-dark bg-dark">
<a class="navbar-brand" href="#">Colab</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNavAltMarkup" aria-controls="navbarNavAltMarkup" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarNavAltMarkup">
<div class="navbar-nav">
{% if user.is_authenticated %}
<a class="nav-item nav-link" href="{% url 'posts:home' %}">Home</a>
<a class="nav-item nav-link" href="{% url 'logout' %}">Logout</a>
{%else%}
<a class="nav-item nav-link active" href="{% url 'index' %}">Home <span class="sr-only">(current)</span></a>
<a class="nav-item nav-link" href="{% url 'reg_sign_in_out:user_login' %}">Login</a>
<a class="nav-item nav-link" href="{% url 'reg_sign_in_out:registration' %}">Register</a>
{% endif %}
<!-- <a class="nav-item nav-link disabled" href="#">Disabled</a> -->
</div>
</div>
</nav>
<div class="container">
{% block body_block %}
{% endblock body_block %}
</div>
</body>
</html>
posts/urls.py
app_name = "posts"
urlpatterns = [
path('home/',views.home,name='home'),
]+static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
urlpatterns += staticfiles_urlpatterns()
reg_sign_in_out/urls.py
app_name = "reg_sign_in_out"
urlpatterns = [
path('user_login/',views.user_login,name='user_login'),
path('registration/',views.registration,name="registration"),
]
project_colab/urls.py (main)
urlpatterns = [
path('',views.index,name="index"),
path('',include('reg_sign_in_out.urls'),name="reg_sign_in_out"),
path('',include('posts.urls'),name="posts"),
path('admin/', admin.site.urls),
path('logout/',views.user_logout,name='logout'),
path('special/',views.special,name='special'),
]
posts/views.py
def home(request):
post_creation = forms.PostsForm()
if request.method == "POST":
# name = request.POST.get('name')
# time = timezone.now()
# post_text = request.POST.get('post_text')
# temp = Posts(name=name,time=time,post_text=post_text)
# temp.save()
post_creation = forms.PostsForm(request.POST,request.FILES)
if post_creation.is_valid():
post_creation.save()
postx = Posts.objects.all()
return render(request,"posts/index.html",context={"post_info":postx,
"user":post_creation})
reg_sign_in_out/views.py
def index(request):
return render(request,"index.html")
#login_required
def special(request):
return HttpResponse("In!")
#login_required
def user_logout(request):
logout(request)
return HttpResponseRedirect(reverse('index'))
#csrf_protect
def registration(request):
registered = False
if request.method == "POST":
form = forms.UserForm(request.POST)
profileform = forms.RegistrationForm(request.POST,request.FILES)
if form.is_valid() and profileform.is_valid():
user = form.save()
print(user)
user.set_password(user.password)
user.save()
profile = profileform.save(commit=False)
profile.user = user
profile.save()
registered = True
else:
print(form.errors,profileform.errors)
return render(request,"reg_sign_in_out/registration.html",{"tried":"True",
"registered":registered,
"profile_form":profileform,
"user_form":form,
})
else:
user = forms.UserForm()
profileform = forms.RegistrationForm()
return render(request,"reg_sign_in_out/registration.html",{"registered":registered,
"profile_form":profileform,
"user_form":user,
})
#csrf_protect
def user_login(request):
if request.method == "POST":
username = request.POST.get('username')
password = request.POST.get('password')
user = authenticate(username=username,password=password)
if user:
if user.is_active:
login(request,user)
return HttpResponseRedirect(reverse('index'))
else:
return render(request,"reg_sign_in_out/login.html",{'tried':'True'})
else:
return render(request,"reg_sign_in_out/login.html")
I think the error in your file project_colab/urls.py (main) because you execute the function at the main of the project so, it affects whole the project so, I think you have to remove the function from urls.py in the main project and instead, try to put as following:
path('',include("index.urls")),
and in the posts/urls.py file you can put the function you has created and the path will be:
path('',views.index,name="index"),

NoReverseMatch at /login - error with LOGIN_URL or reverse function?

I am developing an app in Django.
I am developing users authentication.
I have a registration.html and a login.html templates inside path:
templates > authentication
Everything, including the registering function, works fine, but as I try to access to login template, the browser returns:
NoReverseMatch at /login
'app' is not a registered namespace
I bet the problem lies in the LOGIN_URL that I added in settings.py to enable authentication system (I am following a tutorial).
In fact, all the others view work fine, just the one pointing to login.html is not.
Here below are all my lines relating to the authentication system:
In my settings.py:
LOGIN_URL = '/login'
In my base.html:
{% if user.is_authenticated %}
<li class="nav-item dropdown">
<a class="nav-link dropdown-toggle" data-toggle="dropdown" href="#" role="button" aria-haspopup="true" aria-expanded="false">{{ user_form.username }}</a>
<div class="dropdown-menu">
<a class="dropdown-item" href="">profilo</a>
<a class="dropdown-item" href="{% url 'logout' %}">Log out</a>
</div>
</li>
{% elif not user.is_authenticated %}
<li class="nav-item dropdown">
<a class="nav-link dropdown-toggle" data-toggle="dropdown" href="#" role="button" aria-haspopup="true" aria-expanded="false">Login</a>
<div class="dropdown-menu">
<a class="dropdown-item" href="{% url 'registration' %}">Registrati</a>
<a class="dropdown-item" href="{% url 'login' %}">Accedi</a>
</div>
</li>
{% endif %}
In my authentication > login.html:
{% extends 'base.html'%} <!-- vuol dire inserisci qui la navigation toolbar contenuta in base -->
{% block content %}
<h1>Login</h1>
<br>
<div class="jumbotron">
<form action="{% url 'app:login' %}" method="post">
{% csrf_token %}
<label for="username">Username:</label>
<input type="text" name="username" value="" placeholder="nome utente">
<label for="password">Password:</label>
<input type="password" name="password" value="" placeholder="password">
<input type="submit" name="" value="Login">
</form>
</div>
{% load static %} <!-- Qui il tag è obbligatorio nonostante sia stato inserito dentro base.html -->
<!-- CSS -->
{% comment %} <link rel="stylesheet" type="text/css" href={% static "css/file.css" %}> {% endcomment %}
<!-- Javascript -->
{% comment %} <script type="text/javascript" src={% static "js/file.js" %}></script> {% endcomment %}
{% endblock %}
In my app > urls.py, Inside urlpatterns list:
path('authentication/registration', views_users_authentication.registration, name="registration"),
path('login', views_users_authentication.user_login, name="login"),
in my project > urls.py, Inside urlpatterns list:
path('admin/', admin.site.urls),
path('', include('app.urls')),
Then I have a separate sheet to contain views functions related to the authentication system, that is views_users_authentication.py , which contains:
def registration(request):
registered = False
# se l'utente ha lanciato il post
if request.method=="POST":
print("post eseguito!")
user_form = UserForm(data=request.POST)
profile_form = UserProfileInfoForm(data=request.POST)
# condizione di validità del form
if user_form.is_valid() and profile_form.is_valid():
print("form validi!")
user = user_form.save()
user.set_password(user.password) # questa linea hasha la pasword
user.save()
# registra l'utente
profile = profile_form.save(commit=False)
profile.user = user
registered=True
print("Utente registrato con successo!")
# condizione per registrare l'utente
if 'profile_pic' in request.FILES:
profile.profile_pic = request.FILES['profile_pic']
print("Acquisita la fotografia dell'utente!")
profile.save()
# attenzione al salvataggio dei form e dei modelli che sono due cose diverse
# registra le info aggiuntive
else:
print("Registrazione fallita:")
print(user_form.errors, profile_form.errors)
else:
user_form = UserForm()
profile_form = UserProfileInfoForm()
context_dict = {'user_form':user_form, 'profile_form':profile_form, 'registered':registered}
return render(request, 'authentication/registration.html', context_dict)
def user_login(request):
if request.method == "POST":
username = request.POST.get("username")
password = request.POST.get("password")
user = authenticate(username=username, password=password)
if user:
if user.is_active:
login(request, user)
return HttpResponseRedirect(reverse('home'))
else:
HttpResponse("Account non attivo")
else:
print("qualcuno ha cercato di loggarsi e ha fallito")
print("Username: {} and password {}".format(username,password))
return HttpResponse("Inseriti parametri non validi per il login!")
else:
return render(request, "authentication/login.html", {})
In your login.html you should use just login as url name instead app:login:
<form action="{% url 'login' %}" method="post">
Since you didn't specify namespace in urlpatterns.py file. If you want to use app namespace you can change urlpatern like this:
path('', include('app.urls', namespace='app')),

NoReverseMatch at /post/new/ Reverse for 'post_publish' with keyword arguments '{'pk': ''}' not found

Please, click the link to see the picture to see the error.
base.html
<ul class= 'nav navbar-nav navbar-right'>
{% if user.is_authenticated %}
<li>
New post
</li>
<li>
Drafts
</li>
<li>
Log out
</li>
<li>
<a >Welcome: {{ user.username }}</a>
</li>
{% else %}
<li>
<a class = 'nav navbar-right' href="{% url 'login' %}">
<span class = 'glyphicon glyphicon-user'></span>
</a>
<a class = 'nav navbar-right' href= "{% url 'signup' %}">
Sign up</a>
post_detail.html
{% extends 'blog/base.html'%}
{% block content %}
<h1 class= 'posttitle loader'>{{ post.title }}</h1>
{% if post.published_date %}
<div class="date postdate">
{{ post.published_date }}
</div>
{% else %}
<a class = 'btn btn-primary' href=" {% url 'post_publish' pk=post.pk
%}">Publish</a>
{% endif %}
<p class = 'postcontent'> {{ post.text|safe|linebreaksbr}}</p>
{% if user.is_authenticated %}
<a class= 'btn btn-primary' href="{% url 'post_edit' pk=post.pk %}">
<span class = 'glyphicon glyphicon-pencil'></span>
</a>
<a class= 'btn btn-primary' href="{% url 'post_remove' pk=post.pk %}">
<span class = 'glyphicon glyphicon-remove'></span>
</a>
{% endif %}
<hr>
{% if user.is_authenticated %}
<a class = 'btn btn-primary btn-comment' href="{% url 'add_comment_to_post'
pk=post.pk %}">Comment</a>
{% else %}
<a class = 'btn btn-primary btn-comment' href="{% url 'comment_redirect'
pk=post.pk %}">Comment</a>
{% endif %}
<div class="container">
{% for comment in post.comments.all %}
<br>
{% if user.is_authenticated or comments.approved_comments %}
{{ comment.created_date }}
{% if not comment.approved_comments %}
<a class= 'btn btn-default' href="{% url 'comment_remove' pk=comment.pk
%}">
<span class = 'glyphicon glyphicon-remove'></span></a>
<a class= 'btn btn-primary' href="{% url 'comment_approve' pk=comment.pk
%}">
<span class = 'glyphicon glyphicon-ok'></span></a>
{% else %}
{% endif %}
<p>{{ comment.text|safe|linebreaks }}</p>
<p>Posted by: {{ comment.author }}</p>
{% endif %}
{% empty %}
<p>No comments</p>
{% endfor %}
</div>
{% endblock %}
post_form.html
% extends 'blog/base.html'%}
{% load bootstrap3 %}
{% block content %}
<h1>New post</h1>
<form class="post-form" method="POST">
{% csrf_token %}
{{ form.as_p }}
<button type="submit" class="save btn btn-default">Save</button>
</form>
<script>
var editor = new MediumEditor('.editable');
</script>
{% endblock %}
urls.py
from django.conf.urls import url
from blog import views
urlpatterns = [
url(r'^about/$', views.AboutView.as_view(), name = 'about'),
url(r'^$', views.PostListView.as_view(),name = 'post_list' ),
url(r'^post/(?P<pk>\d+)$', views.PostDetailView.as_view(), name = 'post_detail'),
url(r'^post/new/$', views.CreatePostView.as_view(), name = 'post_new'),
url(r'^post/(?P<pk>\d+)/edit/$', views.PostUpdateView.as_view(), name = 'post_edit'),
url(r'^post/(?P<pk>\d+)/remove/$', views.PostDeleteView.as_view(), name = 'post_remove'),
url(r'^drafts/$', views.DraftListView.as_view(),name = 'post_draft_list' ),
url(r'^post/(?P<pk>\d+)/Comment/$', views.add_comment_to_post, name = 'add_comment_to_post'),
url(r'^comment/(?P<pk>\d+)/approve/$',views.comment_approve, name = 'comment_approve'),
url(r'^comment/(?P<pk>\d+)/remove/$',views.comment_remove, name = 'comment_remove'),
url(r'^signup/$', views.SignUp.as_view(), name ='signup'),
url(r'^comment/(?P<pk>\d+)/Comment/$', views.comment_red, name = 'comment_redirect'),
url(r'^post/(?P<pk>\d+)/publish/$', views.post_publish,
name='post_publish'),
]
views.py
from django.shortcuts import render, get_object_or_404, redirect
from django.utils import timezone
from django.views.generic import (TemplateView, ListView, DetailView,
CreateView,UpdateView,DeleteView)
from blog.models import Post,comments, User
from django.contrib.auth.mixins import LoginRequiredMixin
from django.contrib.auth.decorators import login_required
from django.contrib.auth.forms import UserCreationForm
from blog.forms import PostForm, CommentsForm
from django.urls import reverse_lazy
from django.contrib.auth import login, logout
from . import forms
Created views here.
class AboutView(TemplateView):
template_name = 'about.html'
class PostListView(ListView):
model = Post
def get_query(self):
return post.object.filter(published_date__lte=timezone.now()).orderby('-
published_date')
class PostDetailView(DetailView):
model = Post
class CreatePostView(LoginRequiredMixin,CreateView):
login_url = '/login/'
redirect_field_name = 'blog/post_detail.html'
form_class = PostForm
model = Post
class PostUpdateView(LoginRequiredMixin, UpdateView):
login_url = '/login/'
redirect_field_name = 'blog/post_detail.html'
form_class = PostForm
model = Post
class PostDeleteView(LoginRequiredMixin, DeleteView):
model = Post
success_url = reverse_lazy('post_list')
class DraftListView(LoginRequiredMixin, ListView):
login_url = '/login/'
redirect_field_name = 'blog/post_draft_list.html'
model = Post
def get_query(self):
return post.object.filter(published_date__isnull =
True).order_by('created_date')
class SignUp(CreateView):
form_class = forms.UserCreateForm
success_url = reverse_lazy('login')
template_name = 'sign_up.html'
model = User
############COMMENT###################
#login_required
def post_publish(request, pk):
post = get_object_or_404(Post, pk=pk)
post.publish()
redirect('post_detail', pk=pk)
def comment_red(request,pk):
post = get_object_or_404(Post, pk=pk)
return render(request,'blog/comment_redirect.html')
#login_required
def add_comment_to_post(request,pk):
post = get_object_or_404(Post, pk=pk)
if request.method == "POST":
form = CommentsForm(request.POST)
if form.is_valid():
comment = form.save(commit = False)
comment.post = post
comment.save()
return redirect('post_detail', pk=post.pk)
else:
form = CommentsForm()
return render(request, 'blog/comment_form.html',{'form':form})
#login_required
def comment_approve(request, pk):
comment = get_object_or_404(comments, pk=pk)
comment.approve()
return redirect('post_detail', pk=comment.post.pk)
#login_required
def comment_remove(request, pk):
comment = get_object_or_404(comments, pk=pk)
comment.delete()
return redirect('post_detail', pk=comment.post.pk)
Can I anyone please help me where I got wrong or what I need to, I just got stuck on this. Initially, it was working fine when I click New post on nav bar, it would lead me to the form when I can input text and author but now when I click there, I get this NoReverseMatch at /post/new/ Reverse for 'post_publish' with keyword arguments '{'pk': ''}' not found.
Thank you.
My first guess is that post object is null here:
<a class = 'btn btn-primary' href=" {% url 'post_publish' pk=post.pk
%}">Publish</a>
But to be sure we need a full stack strace.
EDIT #1
We are still missing the traceback, i cannot see it in your picture, but my answer is still valid. post.pk is None, you should replace it with object.pk since you're using a Detailview.
https://docs.djangoproject.com/en/2.0/ref/class-based-views/generic-display/#detailview

Django: NoReverse Match error and page not found

I've gotten the NoReverse Match error before and I got it to work with a blind guess. and page not found I've always been able to fix so I'm really not sure what is going on.
As far as I can tell everything should be working correctly, and I even compared this code to a previous project and it looks fine (I have been tinkering with it so it may not be exactly what I originally typed in).
base.html
<!DOCTYPE html>
{% load staticfiles %}
<html lang="en">
<head>
<title>Evverest</title>
<meta name"viewport" content="width=device-width, initial-scale=1">
<meta charset="uft-8">
<link rel="shortcut icon" href="/images/favicon.ico">
<link rel="stylesheet" href="{% static 'css/style.css' %}">
</head>
<body>
<nav>
<div class="container">
<a class="brand" href="{% url 'index' %}">Evverest</a>
<div class="navbar">
<a class="nav-link btn" href="{% url 'index' %}">Home</a>
{% if user.is_authenticated %}
<a class="nav-link" href="{% url 'users:user-profile' %}">New Color Set</a>
<a class="nav-link" href="{% url 'users:user_logout' %}">Logout</a>
{% else %}
<a class="nav-link" href="{% url 'users:user_login' %}">Login</a>
<a class="nav-link" href="{% url 'users:register' %}">Register</a>
{% endif %}
</div>
</div>
</nav>
<div class="container">
{% block content %}
{% endblock %}
</div>
</body>
</html>
app views.py
from django.shortcuts import render
from users.forms import UserForm,UserProfileForm
from users.models import UserProfileInfo
from django.contrib.auth import authenticate,login,logout
from django.http import HttpResponseRedirect, HttpResponse
from django.core.urlresolvers import reverse
from django.contrib.auth.decorators import login_required
from django.contrib.auth.mixins import LoginRequiredMixin
from django.views.generic import (TemplateView,ListView,
DetailView,CreateView,
UpdateView,DeleteView)
# Create your views here.
def user_login(request):
if request.method == 'POST':
username = request.POST.get('username')
password = request.POST.get('password')
user = authenticate(username=username,password=password)
if user:
if user.is_active:
login(request,user)
return HttpResponseRedirect(reverse('index'))
else:
return HttpResponse("Account now active")
else:
print("Login Unsuccessful")
return HttpResponse("Username and/or password are not correct")
else:
return render(request,'login.html',{})
def register(request):
registered = False
if request.method == 'POST':
user_form = UserForm(data=request.POST)
profile_form = UserProfileForm(data=request.POST)
if user_form.is_valid() and profile_form.is_valid():
user = user_form.save()
user.set_password(user.password)
user.save()
profile = profile_form.save(commit=False)
profile.user = user
if 'profile_pic' in request.FILES:
profile.profile_pic = request.FILES['profile_pic']
profile.save()
registered = True
else:
print(user_form.errors,profile_form.errors)
else:
user_form = UserForm()
profile_form = UserProfileForm()
return render(request,'register.html',{
'user_form':user_form,
'profile_form':profile_form,
'registered':registered
})
#login_required
def user_logout(request):
logout(request)
return HttpResponseRedirect(reverse('login'))
class HomeView(ListView):
model = UserProfileInfo
ordering = ['-join_date']
class UserProfileView(DetailView):
model = UserProfileInfo
class UserEditProfileView(LoginRequiredMixin,UpdateView):
login_url = '/login/'
redirect_field_name = '/users_detail.html'
form_class = UserProfileForm
model = UserProfileInfo
Project urls.py
from django.conf.urls import url
from django.contrib import admin
from django.conf.urls import include
from users import views
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^$',views.HomeView.as_view(),name='index'),
url(r'^users/',include('users.urls',namespace='users')),
]
app urls.py
from django.conf.urls import url
from users import views
app_name = 'users'
urlpatterns = [
url(r'^login/$',views.user_login,name='user_login'),
url(r'^logout/$',views.user_logout,name='user_logout',kwargs={'next_page':'/'}),
url(r'^register/$',views.register,name='register'),
url(r'(?P<username>\d+)/$',views.UserProfileView.as_view(),name='user-profile'),
url(r'(?P<username>\d+)/edit$',views.UserEditProfileView.as_view(),name='user-profile-edit'),
]
file structure:
EDIT
Here is the traceback:
As you see in your urls.py:
url(r'(?P<username>\d+)/$',views.UserProfileView.as_view(),name='user-profile')
Your user-profile url takes one parameter, which is username. But in your template you do not pass it:
<a class="nav-link" href="{% url 'users:user-profile' %}">New Color Set</a>
So Django does not know which username to pass and this causes NoReverseMatch.
You just need to to pass the username to the url:
<a class="nav-link" href="{% url 'users:user-profile' username=user.username %}">New Color Set</a>
Figured it out: The problem come up because in another template (which I didn't post because I didn't realize it had any effect on this) I didn't put in the namespace users
Here is that other template:
{% extends "base.html" %}
{% block content %}
<div class="form-base">
<h2>Login</h2>
<form action="{% url 'users:user_login' %}" method="POST">
{% csrf_token %}
<label for="username">Username: </label>
<input type="text" class="login-input" name="username" placeholder="Enter Username" />
<label for="password">Password: </label>
<input type="password" class="login-input" name="password" />
<input type="submit" name="" value="Login" />
</form>
</div>
{% endblock %}
Thank you for the help everyone.

Cannot see the form input field at all

I would like to collect the content that user input, then change the database using POST method. But i just blank when i clicked post button on the website.
Here's the views.py
class PostTweet(View):
def post(self, request, username):
form = TweetForm(request.POST)
print form.is_valid()
print request.POST
print form.errors
if form.is_valid():
user = User.objects.get(username=username)
tweet = Tweet(text=form.cleaned_data['text'],
user=user,
country=form.cleaned_data['country'])
tweet.save()
return HttpResponseRedirect('/user/'+username)
else:
form = TweetForm()
return render(request, 'profile.html', {'form':form})
class Profile(View):
"""
User Profile page reachable from /user/<username> URL
"""
def get(self, request, username):
params = {}
user = User.objects.get(username = username)
tweets = Tweet.objects.filter(user=user)
params["tweets"] = tweets
params["user"] = user
return render(request, 'profile.html', params)
forms.py
from django import forms
class TweetForm(forms.Form):
text = forms.CharField(widget=forms.Textarea, max_length=160)
country = forms.CharField(widget=forms.HiddenInput(),required=False)
profile.html
{% extends "base.html" %}
{% block content %}
<div class="row clearfix">
<div class="col-md-6 col-md-offset-3 column">
<form id="form" method="POST" action="post/">{% csrf_token %}
<div class="col-md-8 fieldWrapper">
{{ form }}
<span class="input-group-btn">
<button class="btn btn-default" type="submit">Post</button>
</span>
</div>
</form>
</div>
<h3> </h3>
<div class="col-md-12 column">
{% for tweet in tweets %}
<div class="well">
<span>{{ tweet.text}}</span>
</div>
{% endfor %}
</div>
</div>
{% endblock %}
Here's the urls.py
from django.conf.urls import include, url, patterns
from django.contrib import admin
from tweets.views import Index, Profile, PostTweet, HashTagCloud
admin.autodiscover()
urlpatterns = patterns('',
url(r'^$', Index.as_view()),
url(r'^user/(\w+)/$', Profile.as_view()),
url(r'^admin/', include(admin.site.urls)),
url(r'^user/(\w+)/post/$', PostTweet.as_view()),
url(r'^hashTag/(\w+)/$', HashTagCloud.as_view()),
)
Anyone just give me a hint would be appreciated :-)
Adding {{form}} only should not render the field. form is an object with fields as properties. In your html try substituting {{form}} with {{form.text}}
Also you can try passing the object "form" as follows:
return render(request, 'profile.html', form = form)

Categories