Log out when sending a form - django

I've created an app where you can make comment (which sends a form to a database and saves it) if you're login on only, but when I press the button "Create" instead of redirecting me to the page where it show all the comments, it logs me out and bring me back to the "log out" view (which is / )
the create Template:
{% extends 'base.html' %}
{% block content %}
<div class="create_comment">
<h2>Write a comment</h2>
<form class="site-form" action="{% url 'create' %}" method="post">
{% csrf_token %}
{{form}}
<input type="submit" value="Create">
</form>
</div>
{% endblock %}
The Views of Create:
#login_required(login_url='/userprofile/login/')
def comments_create(request):
if request.method == 'POST':
form = forms.CreateComment(request.POST)
if form.is_valid():
form.save()
return redirect('/usercomments')
else:
form = forms.CreateComment()
return render(request,'usercomments/comments_create.html', {'form':form})
Log out view:
def logout_view(request):
if request.method == 'POST':
logout(request)
return redirect('/')
else:
pass
usercomments Urls.py:
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$',views.comments_list, name="list"),
url(r'^create/$', views.comments_create, name="create"),
url(r'^(?P<slug>[\w-]+)/$',views.comments_detail, name="detail"),
]
userprofile urls.py:
from django.conf.urls import url
from . import views
app_name = 'userprofile'
urlpatterns = [
url(r'^signup/$', views.signup_view, name="signup"),
url(r'^login/$', views.login_view, name="login"),
url(r'^logout/$',views.logout_view, name="logout"),
]

Related

My view does not redirect after processing a form. Used HttpResponseRedirect

I am new to Django and I am trying to use custom forms. My problem is that my form does not do anything after I submit it.
I am following the documentation here:https://docs.djangoproject.com/en/4.1/topics/forms/
I have the following files:
forms.py:
from django import forms
class TestForm(forms.Form):
text = forms.CharField(label='Text', max_length=50)
urls.py:
from django.urls import path
from . import views
app_name = 'home'
urlpatterns = [
path('', views.index, name='index'),
path('test', views.test_view, name='test')
]
views.py:
def index(request):
return render(request, 'index.html', context)
def test_view(request):
if request.method == 'POST':
form = TestForm(request.POST)
if form.is_valid():
return HttpResponseRedirect('home:index')
else:
form = TestForm()
return render(request, 'test.html', context={'form':form, 'text':'No text yet.',})
template: test.html
<div>
<form action="home:club-invite" method="POST">
{% csrf_token %}
{{ form }}
<input type="submit" value="Submit">
</form>
<hr>
<p>Your text: {{ text }}</p>
</div>
The problem is that the Submit button does nothing. I was expecting a redirect to the index page. But here is no error, no subsequent http request or redirect, nothing...
Am I missing something here?
PS:I also tried return redirect('home:index'). Still no success.

comment added by the logging in user didn't properly save

I have been currently working on an easy Django website.
An error came up when I tried to implement a function that users can add comments to blogs. I succeeded to show the form where users can write their comments, but even if I pressed the add button, didn't save properly.
I don't even know where I made a mistake coz I knew how to post and save information to the database.
so, I ask you to help!!
# add_comment.html
{% extends 'base.html' %}
{% block title %}|コメント追加{% endblock %}
{% block content %}
<div class="header-bar">
← 戻る
</div>
<div class="body-container blog">
<div class="body-header">
<h1>コメント追加</h1>
</div>
<form method="post">
{% csrf_token %}
{{ form.as_p }}
<button class='button' type="submit">追加</button>
</form>
</div>
</div>
{% endblock %}
# views.py
#login_required
def add_comment(request, pk):
blog = get_object_or_404(Blog, pk=pk)
if request.method == 'post':
form = CommentForm(request.POST)
if form.is_valid():
comment = form.save(commit=False)
comment.blog = blog
comment.save()
return redirect('blog', pk=blog.pk)
else:
form = CommentForm()
context = {
'form': form,
}
return render(request, 'blog/add_comment.html', context)
# urls.py
from django.urls import path
from . import views
from .views import BlogCreate, BlogUpdate, BlogDelete, BlogList
# blogs
urlpatterns = [
path('', views.index, name='latest_blogs'),
path('my_blogs/', views.my_blogs, name='my_blogs'),
path('my_blogs/my_blog_search', views.my_blogs_search, name='my_blogs_search'),
path('drafts/', views.drafts, name='drafts'),
path('blog/<int:pk>/', views.blog, name='blog'),
path('blog/<int:pk>/comment/', views.add_comment, name='add_comment'),
path('create/', BlogCreate.as_view(), name='blog-create'),
path('update/<int:pk>/', BlogUpdate.as_view(), name='blog-update'),
path('delete/<int:pk>/', BlogDelete.as_view(), name='blog-delete'),
path('all_blogs/', BlogList.as_view(), name='all_blogs'),
path('all_blogs/all_blogs_search/', views.all_blogs_search, name='all_blogs_search'),
]
Any comments help me and thanks for your time in advance!!

Django redirect not working in authentication

I am trying to authenticate a registered user . redirect is not working in my case. after clicking the login button it keep on showing the login page again. i want the user to go to home page upon the successful login. Here are my files.
views.py
from django.shortcuts import render, redirect
from django.http import HttpResponseRedirect
from django.contrib import messages
from django.contrib.auth import authenticate, login, logout
def register_new_a(request):
saved = False
if request.method == "POST":
# take whatever is posted to the Details Form
form = DetailsForm(request.POST)
if form.is_valid():
form.save()
messages.success(request, 'Your account details have been saved!')
return HttpResponseRedirect('/register_new_a?saved=True')
else:
form = DetailsForm()
if 'saved' in request.GET: # sends saved var in GET request
saved = True
return render(request, 'register1.html', {'form': form, 'saved': saved})
def loginUser(request):
if request.method == "POST":
username = request.POST.get('username')
password = request.POST.get('password')
user = authenticate(request, username=username, password=password)
if user is not None:
# at backend authenticated the credentials
login(request, user)
return redirect('home') # not working
return render(request, 'login_a.html')
urls.py
from django.contrib import admin
from django.urls import path
from home import views
urlpatterns = [
path("", views.index, name='home'),
path("login", views.loginUser, name='login'),
path("logout", views.logoutUser, name='logout'),
#path("register", views.register, name='register'),
path("register_new_a", views.register_new_a, name='register_new_a'),
path("register_new_b", views.register_new_b, name='register_new_b'),
path("about", views.about, name='about'),
]
login_a.html
{% extends 'base.html'%}
{% block title %}Login{% endblock title %}
{% block body %}
<div class="container my-3" >
<h1 class="display-3" align="center">Login Here</h1>
<br>
<h1 class="display-6" >STEP 1: </h1>
<form method="post" action="">
{% csrf_token %}
<div class="mb-3">
<label for="Username1" class="form-label" >Username </label>
<input type="username"class="form-control" name="username"></input>
</div>
<div class="mb-3">
<label for="Password1" class="form-label">Password</label>
<input type="password" class="form-control" id="Password1" name="password">
</div>
New user? Register Here
<button type="submit" class="btn btn-primary float-end" style="background: #0a9396" > Next</button>
</form>
</div>
{% endblock body %}
Any help would be appreciated.

Input redirect me on the wrong view

Hello i'm a beginner at django and i got this problem. (i don't know if the code i put is enough)
When i decide to create a new comment, if i click on "create" instead of redirect me to "usercomments" and send the data to the database, it log me out and send me where log out is supposed to send me. i can't find a similar problem, i don't even know what kind of error it is, help
Thanks :)
Templates of "create comment" :
<div class="create-comment">
<h2>Write a comment</h2>
<form class="site-form" action="{% url 'usercomments:create' %}" method="post">
{% csrf_token %}
{{form}}
<input type="submit" value="Create">
</form>
</div>
Urls.py :
from django.conf.urls import url
from . import views
app_name = 'usercomments'
urlpatterns = [
url(r'^$',views.comments_list, name="list"),
url(r'^create/$', views.comments_create, name="create"),
url(r'^(?P<slug>[\w-]+)/$',views.comments_detail, name="detail"),
]
Views of create comment :
#login_required(login_url="/userprofile/login/")
def comments_create(request):
if request.method == 'POST':
form = forms.CreateComment(request.POST)
if form.is_valid():
# save article to db
instance = form.save(commit=False)
instance.author = request.user
instance.save()
return redirect('usercomments:list')
else:
form = forms.CreateComment()
return render(request, 'usercomments/comments_create.html', { 'form': form })
Views of log out :
def logout_view(request):
if request.method == 'POST':
logout(request)
return redirect('/') <--- Where i get redirected when i press "create"
else:
pass
Urls of logout :
from django.conf.urls import url
from . import views
app_name = 'userprofile'
urlpatterns = [
url(r'^signup/$', views.signup_view, name="signup"),
url(r'^login/$', views.login_view, name="login"),
url(r'^logout/$',views.logout_view, name="logout"),
]

Django not passing data to the post method

I have been going over a Django tutorial and I have come across an issue where whenever I am trying to post a form to pass data from the webpage to the database it will not go to the method that it is supposed to go to in order for the action to be performed. Here is the code
urls.py
from django.urls import path, re_path
from . import views
app_name = 'music'
urlpatterns = [
path('', views.index, name='index'),
# /music/<album_id>/
re_path('(?P<album_id>[0-9]+)/', views.detail, name='detail'),
# /music/<album_id>/favorite/
re_path('(?P<album_id>[0-9]+)/favorite/', views.favorite, name='favorite'),
]
details.html
<img src="{{ album.album_logo }}"/>
<h1>{{ album.album_title }}</h1>
<h3>{{ album.artist }}</h3>
{% if error_message %}
<p><strong>{{ error_message }}</strong></p>
{% endif %}
<form action="{% url 'music:favorite' album.id %}" method="post">
{% csrf_token %}
{% for song in album.song_set.all %}
<input type="radio" id="song{{ forloop.counter }}" name="song" value="song.id"/>
<label for="song{{ forloop.counter }}">
{{ song.song_title }}
{% if song.is_favorite %}
<img src="https://i.imgur.com/b9b13Rd.png"/>
{% endif %}
</label><br>
{% endfor %}
<input type="submit" value="Favorite">
</form>
views.py
from django.shortcuts import render, get_object_or_404
from django.http import Http404
from .models import Album, Song
import pdb;
def index(request):
all_albums = Album.objects.all()
return render(request, 'music/index.html', { 'all_albums': all_albums })
def detail(request, album_id):
album = get_object_or_404(Album, pk=album_id)
return render(request, 'music/detail.html', {'album': album})
def favorite(request, album_id):
album = get_object_or_404(Album, pk=album_id)
try:
selected_song = album.song_set.get(pk=request.POST['song'])
except (KeyError, Song.DoesNotExist):
return render(request, 'music/detail.html', {
'album': album,
'error_message': "You did not select a valid song",
})
selected_song.is_favorite = True
selected_song.save()
return redirect('music:detail', album_id=album_id)
Any pointers would be helpful as to why this is occurring. I went back to the tutorial and I typed whatever was in it again to make sure I did it correctly. It could be because it was a slightly older version I am not sure though. I am running Django version 2.0 while the tutorial was running 1.9.1
The problem is in your favorite view. You have to use an if statement to capture the POST request data. Something like this.
def favorite(request):
if request.method == "POST":
# do whatever you want with your POST data
else:
# do something else
context = {
data: any data that you want to pass to your template
}
return render(request, "your_template.html", context)
See if you can implement a structure like this in your view. If you have any questions or need more details, ask below in comment.
Hope it helps
def favorite(request, album_id):
if request.method == "POST":
album = get_object_or_404(Album, pk=album_id)
try:
selected_song = album.song_set.get(pk=request.POST['song'])
selected_song.is_favorite = True
selected_song.save()
return redirect('music:detail', album_id=album_id)
except (KeyError, Song.DoesNotExist):
return render(request, 'music/detail.html', {
'album': album,
'error_message': "You did not select a valid song",
})