Linking of homePage view to other views - django

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.

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.

trying to use username in urlpattern to give every user a unique link

this my approach if you know how to do it please help
my views.py
def profile(request, username):
return render(request, 'profile.html')
my urls.py
from django.conf.urls import url
from django.urls import path
from django.contrib.auth import views as auth_views
from . import views
# Template Urls!
app_name = 'accounts'
urlpatterns = [
path('Skolar/',views.base, name= 'base'),
path('Register/',views.register,name='register'),
path('login/', views.my_login_view, name='login'),
path('logout/',views.user_logout,name='logout'),
path('<slug:username>',views.profile, name='profile'),
path('EditProfile/',views.update_profile,name='editprofile'),
]
error showing
Reverse for 'profile' with no arguments not found. 1 pattern(s) tried: ['(?P<username>[-a-zA-Z0-9_]+)$']
in my html i use
<a class="dropdown-item" href="{% url 'accounts:profile' %}">My Account</a>
adding profile html which i want ot show user after clickin gon that link
{% extends 'masteraccount.html' %}
{% block content %}
{% load static %}
<link rel="stylesheet" href="{% static 'css/accountscss/profile.css'%}">
<div class="">
<div class="page-content">
<label class="name" for="NAME">NAME:</label>
<p>{{user.first_name}} {{user.last_name}}</p>
<label for="Email">Email:</label>
<p>{{user.email}}</p>
<label for="Twitter">Twitter:</label>
<p>{{user.profile.twitter}}</p>
<label for="Facebook">Facebook:</label>
<p>{{user.profile.Facebook}}</p>
<label for="Facebook">About:</label>
<p>{{user.profile.about}}</p>
<label for="Facebook">Date of Birth:</label>
<p>{{user.profile.dob}}</p>
</div>
<button type="button" class="btn btn-primary btn-lg">Edit Profile</button>
</div>
{% endblock %}
views.py let us assume your model is 'Profile' and your have 'user' related to one-to-one to User you should use something like:
from django.shortcuts import render,get_object_or_404
def profile(request, username):
profile = get_object_or_404(Profile,user = username)
return render(request, 'profile.html',{'profile':profile})
urls.py:
from django.conf.urls import url
from django.urls import path
from django.contrib.auth import views as auth_views
from . import views
# Template Urls!
app_name = 'accounts'
urlpatterns = [
path('Skolar/',views.base, name= 'base'),
path('Register/',views.register,name='register'),
path('login/', views.my_login_view, name='login'),
path('logout/',views.user_logout,name='logout'),
path('<slug:username>/',views.profile, name='profile'),
path('EditProfile/',views.update_profile,name='editprofile'),
]
html
<a class="dropdown-item" href="{% url 'accounts:profile' request.user.username %}">My Account</a>
Note:it is always better to use pk for the profile.but slug it is also fine

Reverse for 'add_to_cart' with arguments '('',)' not found. 1 pattern(s) tried: ['cart/add/(?P<item_id>[^/]+)/$']

I cant seem to add products/plans to my cart page im getting this error.
This is my views
def add_to_cart(request, item_id):
""" Add plan to shopping cart """
cart = request.session.get('cart', {})
cart[item_id] = cart.get(item_id, 1)
request.session['cart'] = cart
return redirect(reverse('plans'))
This is my plans.html - this is a button where im trying to a plan to my cart
<form method="post" action="{% url 'add_to_cart' item.id %}">
{% csrf_token %}
<div class="text-center">
<span class="input-group-btn">
<button class="btn btn-light color-orange " type="submit">
Add to Cart
</button>
</span>
</div>
</form>
And this is my urls from my cart app
from django.contrib import admin
from django.urls import path
from . import views
urlpatterns = [
path('', views.view_cart, name='view_cart'),
path('add/<item_id>/', views.add_to_cart, name='add_to_cart'),
]
Would be great if someone could guide me
urlpatterns = [
path('', views.view_cart, name='view_cart'),
# path('add/<item_id>/', views.add_to_cart, name='add_to_cart'),
path('add/<int:item_id>/', views.add_to_cart, name='add_to_cart'),
]
Make sure that you are passing a value with key "item" to the context data in your form HTML, or else "item.id" will be None.

'Save html form data in database' 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

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>