'Save html form data in database' django - django

I'm trying to save name and email from HTML from using django in postgres database, in action tag, function name is mentiond but insted of using that function, django is passing that data to a new page of same function name
HTML
<form class="newsletter_form d-flex flex-md-row flex-column align-items-start justify-content-between" action="subscribe" method="post">
{%csrf_token%}
<div class="d-flex flex-md-row flex-column align-items-start justify-content-between">
<div>
<input name="subname" type="text" class="newsletter_input newsletter_input_name" id="newsletter_input_name" placeholder="Name" required="required">
<div class="input_border"></div>
</div>
<div>
<input name="subemail" type="email" class="newsletter_input newsletter_input_email" id="newsletter_input_email" placeholder="Your e-mail" required="required">
<div class="input_border"></div>
</div>
</div>
<div><button type="submit" class="newsletter_button">subscribe</button></div>
</form>
views.py
def subscribe(request):
if request.method == 'POST':
subname = request.POST['subname']
subemail = request.POST['subemail']
sub = User.objects.create_user(subname=subname, subemail=subemail)
sub.save();
return redirect('/')
else:
return redirect('/')
url.py
from django.urls import path
from . import views
urlpatterns = [
path("register", views.register, name='register'),
path("login", views.login, name='login'),
path("logout", views.logout, name='logout'),
path("subscribe", views.subscribe, name='subscribe')
]
this is error

first of all you are not redirecting using redirect('/') because when you redirect you you should use the name you assigned in urls.py i.e path("register", views.register, name='register'), the name here is register
then in views.py:
def subscribe(request):
if request.method == 'POST':
subname = request.POST['subname']
subemail = request.POST['subemail']
sub = User.objects.create_user(subname=subname, subemail=subemail)
return redirect('subscribe')
else:
return redirect('home')
what i edited is :
deleted sub.save() because thats only used in django forms.
and about the subscribe url which causes 404 is you are not rendering a single template, how should the subscribe function work ?
call the render() function in the end of the subscribe function
and simple advice, add an ending slash in the end of every url pattern i.e path("register/", views.register, name='register'), :) this is advisable

Related

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.

How to add a search bar functionality to all the templates of django?

I am trying to add a search bar in my django site. I added a form in my base template. I have added the functionality to my home view. It is working in the home view. But not in other views. I tried creating a new view but i.e. Is not working too. Please tell me what should I do?
views.py:
def search(request):
if request.method == "GET":
query = request.GET.get('q').split()
if query:
queryset = reduce(
operator.__or__,
[
Q(title__icontains=queries) | Q(content__icontains=queries)
for queries in query
]
)
posts = Post.objects.filter(queryset).distinct()
return render(request, "blog/home.html", {'posts': posts})
template:-
<form class="form-inline my-2 my-lg-0">
<input class="form-control mr-sm-2" action="{% url 'blog-home' %}" method="GET" type="search" placeholder="Search Posts" aria-label="Search" name="q">
<button class="btn btn-outline-success my-2 my-sm-0" type="submit">Search</button>
</form>
urls.py
urlpatterns = [
path('', PostListView.as_view(), name='blog-home'),
path('user/<str:username>', UserPostListView.as_view(), name='user-posts'),
path('post/<int:pk>/', PostDetailView.as_view(), name='post-detail'),
path('post/new/', PostCreateView.as_view(), name='post-create'),
path('post/<int:pk>/update/', PostUpdateView.as_view(), name='post-update'),
path('post/<int:pk>/delete/', PostDeleteView.as_view(), name='post-delete'),
path('about/', views.about, name='blog-about'),
path('comment/<int:pk>/approve/', views.comment_approve, name='comment_approve'),
path('comment/<int:pk>/remove/', views.comment_remove, name='comment_remove'),
path('comment/<int:pk>/delete/', views.comment_delete, name='comment_delete'),
path('summernote/', include('django_summernote.urls')),
path('feedback/', views.contact_us, name='contact_us'),
path('search/', views.search),
]
This is how I performed my search function. First we get the object of the model we want and then we get the q which is the name of the input in my template and than filter as per the field that we want. The form action that I mention before is the solution for your problem.
view.py
def course_view(request):
latest_course = Course.objects.all()
query = request.GET.get('q')
print(query)
if query:
latest_course = Course.objects.filter(
Q(title__icontains=query)|
Q(user__full_name=query)|
Q(price__icontains=query)
)
context = {
'latest_course': latest_course,
}
return render(request, 'apps/course.html', context)
template.html( Its in my base template like yours)
<div class="sidebar-search">
<form method="GET" action="{% url 'courses' %}">
<div class="input-group">
<input type="text" class="form-control search-menu" placeholder="Search..." name='q'>
<div class="input-group-append">
<span class="input-group-text">
<i class="fa fa-search" aria-hidden="true"></i>
</span>
</div>
</div>
</form>
</div>
In your template form tag add the URL name where you want to load the search function. This way you can search from any page and will redirect you that page. If you don't get it I can provide you with a reference code so that you can grasp some idea.
<form method="GET" action="{% url 'courses' %}">

Linking of homePage view to other views

I am trying to link my home page view to other views but it's not working
I also tried to take only a single view but it still not working
I also don't know how to connect multiple views into a single URL
app/views.py
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import redirect
from django.shortcuts import render
from homePage.forms import SignInForm,DropUsaMessage
# Create your views here.
def homePage(request):
sign_in_detail=SignIn
message_detail=DropUsaMessage
return render(request, "index.html",{"form":sign_in_detail,"forms":message_detail})
def SignIn(request):
sign_in_detail=SignInForm()
if request.method == 'POST':
sign_in_detail = SignInForm(request.POST)
if sign_in_detail.is_valid():
return render(request, "index2.html",{"form":sign_in_detail})
else:
sign_in_detail = SignInForm()
# "form":sign_in_detail
return render(request, "index.html",{})
def Contact(request):
message_detail=DropUsaMessage()
if request.method == 'POST':
message_detail = DropUsaMessage(request.POST)
if message_detail.is_valid():
return homePage(request)
else:
message_detail = DropUsaMessage()
# "forms":message_detail
return render(request, "index.html",{"forms":message_detail})
app/urls.py
from django.urls import path
from . import views
urlpatterns=[
path('', views.homePage),
]
app/forms.py
from django import forms
from django.core import validators
class SignInForm(forms.Form):
email=forms.EmailField(widget=forms.EmailInput(attrs={"class": 'form-control',"placeholder":'Enter E-mail',"id": 'exampleInputEmail1'}))
password=forms.CharField(widget=forms.PasswordInput(attrs={"class":'form-control',"placeholder":'Enter Password',"id":'exampleInputPassword1'}))
class DropUsaMessage(forms.Form):
name = forms.CharField(widget=forms.TextInput(attrs={"class":'form-control',"placeholder":'Your Name'}))
email = forms.EmailField(widget=forms.EmailInput(attrs={"class": 'form-control',"placeholder":'Your E-mail',"id": 'exampleInputEmail1'}))
phone = forms.IntegerField(widget=forms.NumberInput(attrs={"class":'form-control',"placeholder":'Your Phone Number'}))
message = forms.CharField(widget=forms.Textarea(attrs={"class":'form-control',"placeholder":'Type Your Message',"style":'width:100%; height: 150px'}))
index.html
<div class="container-fluid">
<div class="row">
<div class="col-md-8">
<img src="{% static 'img/sampleImage.jpg' %}" width="100%" height="100%" class="d-inline-block align-top" alt="">
</div>
<div class="col-md-4">
<form method="POST">
{% csrf_token %}
{{ form }}
<div class="form-check">
<span class="fpswd">Forgot password?</span>
</div>
<button type="submit" class="btn btn-primary" name="SignIn">Submit</button>
</form>
</div>
</div>
</div>
<div class="container contact-form">
<form method="post">
<h3>Drop Us a Message</h3>
{% csrf_token %}
{{ forms }}<br><br>
<div class="form-group">
<input type="submit" name="SendMessage" class="btnContact" value="Send Message" />
</div>
</form>
</div>
the signin field is not showing up. there is a long address is showing in django-debug-toolbar
Give names to your URL patterns like below:
urlpatterns=[
path('', views.homePage, name='home'),
]
Then in your templates you can use Jinja to reference these names like.
Home
You can get a little help from DjangoProject site tutorial with the link.
UPDATE:
You need to create a Navbar (Navigation bar). You can then call all your pages with URLS in your home page. Like
Home | Services | Portfolio
You need to create urlpatterns with name for each page and you can then use it like.
<ul><li>Home</li>
<ul><li>Services</li>
<ul><li>Portfolio</li>.
So then all the pages will link up to your home page and you can navigate.
For that you need to create 3 respective views like below in your urls.py:
urlpatterns=[
path('', views.homePage, name='home'),
path('services/', views.servicePage, name='services'),
path('portfolio/', views.portfolioPage, name='portfolio'),
]
You can not have multiple views on a single URL. One URL maps to a single view.

Unable to redirect Django form

I am trying to build a simple blog with a basic post function through a very simple form. The function I am trying to accomplish is:
if the new post POSTs (no errors etc.) save to the database and redirect to the newly created post_details page. Otherwise I want it to re render the post form again. I keep getting the error NoReverseMatch at /post/pk and I cannot find my error. I am obviously not understanding something properly. The related code is below:
views.py
def post_new(request):
if request.method == "POST":
form = PostForm(request.POST)
if form.is_valid():
post = form.save(commit=False)
post.author = request.user
post.published_date = timezone.now()
post.save()
return redirect('post_detail', pk=post.pk)
else:
form = PostForm()
return render(request, 'blog/post_edit.html', {'form': form})
post_edit.html
{% extends 'blog/base.html' %}
{% block content %}
<h2>New post</h2>
<form method="POST" class="post-form">{% csrf_token %}
{{ form.as_p }}
<button type="submit" class="save btn btn-default">Save</button>
</form>
{% endblock %}
urls.py
from django.urls import path
from . import views
urlpatterns = [
path('', views.post_list, name='post_list'),
path('post/<int:pk>/', views.post_detail, name='post_detail'),
path('post/new/', views.post_new, name='post_new'),
]
I found my error inside my link for in my template view post_detail.html:
<a class="btn btn-default" href="{% url 'post_edit' pk=post.pk %}"><span class="glyphicon glyphicon-pencil"></span></a>
It was redirecting properly to post_detail.html but the link above was breaking my page.

How can i call views from Html Templates in Django?

As i'm trying to upload file and send with some functionality i'm getting error while calling view function from views.py to html templates i don't know what i did wrongly Can anyone help me..Thanks in Advance :)
here is my views.py:
my application name is secondone and my view function name is SavedProfile.
from django.shortcuts import render
from secondone.forms import ProfileForm
from secondone.models import Profile
def SaveProfile(request):
saved = False
if request.method == "POST":
#Get the posted form
MyProfileForm = ProfileForm(request.POST, request.FILES)
if MyProfileForm.is_valid():
profile = Profile()
profile.name = MyProfileForm.cleaned_data["name"]
profile.picture = MyProfileForm.cleaned_data["picture"]
profile.save()
saved = True
else:
MyProfileForm = ProfileForm()
return render(request, 'last.html', locals())
Here is my Template:
<html>
<body>
<form name="form" enctype="multipart/form-data"
action = "{% url 'views.SaveProfile' %}" method = "POST" >{% csrf_token %}
<div style="max-width: 470px">
<center>
<input type="text" style="margin-left:20%;"
placeholder="Name" name="name">
</center>
</div>
<br>
<div style = "max-width:470px;">
<center>
<button style = "border:0px;background-color:#4285F4; margin-top:8%;
height:35px; width:80%; margin-left:19%;" type = "submit" value = "Login" >
<strong>Login</strong>
</button>
</center>
</div>
</body>
</html>
Here is my url.py:
from django.contrib import admin
from myapp import views
from secondone import views
from django.views.generic import TemplateView
from django.conf.urls import url, include
from django.contrib import admin
from django.contrib.auth import views as auth_views
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
url(r'^login/$', auth_views.login, name='login'),
url(r'^logout/$', auth_views.logout, name='logout'),
url(r'^oauth/', include('social_django.urls', namespace='social')), # <--
url(r'^admin/', admin.site.urls),
url(r'^accounts/',include('allauth.urls')),
url(r'^profile/',TemplateView.as_view(template_name = 'registeration.html')),
url(r'^saved/', views.SaveProfile, name = 'saved')
]
i tried with some other techniques and i got my output..
<html>
<body>
<form name="form" enctype="multipart/form-data"
action = "/SaveProfile/" method = "POST" >{% csrf_token %}
<div style="max-width: 470px">
<center>
<input type="text" style="margin-left:20%;"
placeholder="Name" name="name">
</center>
</div>
<br>
<div style = "max-width:470px;">
<center>
<button style = "border:0px;background-color:#4285F4; margin-top:8%;
height:35px; width:80%; margin-left:19%;" type = "submit" value = "Login" >
<strong>Login</strong>
</button>
</center>
</div>
</body>
</html>