how to creater a signup register form with my own reqired field form in django? - django

Im new to django i want create signup form with my own feild ,i dont want to signup form in default that is in user table i want to created own custom sign up forn any can hepl plz
Im new to django i want create signup form with my own feild ,i dont want to signup form in default that is in user table i want to created own custom sign up forn any can hepl plz
here is my example how my form feild look like
[enter link description here][1]
<form id="contact-form" method="post" action="/addyourschool/" role="form">
<input type="hidden" name="csrfmiddlewaretoken" value="vhcAZ5w1HpK2mUXMhdqHR1to9Yv2LeOB85E2kR7Z1ZsPo5fjtWZ5P7o23kj8lDsk">
<div class="messages"></div>
<div class="controls">
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label for="form_name">School Name</label>
<input type="text" name="schoolname" id="product" class="form-control ui-autocomplete-input" placeholder="Type few letter & select from down *" required="required" data-error="Lastname is required." autocomplete="off">
<div class="help-block with-errors"></div>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label for="form_cfschp">Can't find your School *</label>
<input id="form_cfschp" type="text" name="form_cfschpool" class="form-control" placeholder="Can't find your School *" required="required" data-error="Can't find your School">
<div class="help-block with-errors"></div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label for="Pessonname">Contact person Name *</label>
<input id="Pessonname" type="text" name="Pessonname" class="form-control" placeholder="Contact person Name *" required="required" data-error="Contact person Name ">
<div class="help-block with-errors"></div>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label for="DesignationatSchool">Designation at School(job title at this section) *</label>
<select id="DesignationatSchool" name="DesignationatSchool" class="form-control" required="required" data-error="Designation at School">
<option value=""></option>
<option value="Request principal">Principal</option>
<option value="Request quotation">Founder</option>
<option value="Request order status">Management</option>
<option value="Request copy of an invoice">Teachers</option>
<option value="Other">Others</option>
</select>
<div class="help-block with-errors"></div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label for="pwd">Password *</label>
<input id="pwd" type="password" name="password" class="form-control" placeholder="Enter your Password *" required="required" data-error="password">
<div class="help-block with-errors"></div>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label for="pwd">Confirm Password *</label>
<input id="pwd" type="password" name="password" class="form-control" placeholder="Confirm Password *" required="required" data-error="Lastname is required.">
<div class="help-block with-errors"></div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label for="email">Email *</label>
<input id="email" type="email" name="email" class="form-control" placeholder="Please enter your email *" required="required" data-error="Valid email is required.">
<div class="help-block with-errors"></div>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label for="tel">Mobile No. *</label>
<input id="tel" type="tel" name="phone" class="form-control" placeholder="Please enter your Mobile No *" required="required" data-error="Valid email is required.">
<div class="help-block with-errors"></div>
</div>
</div>
</div>
<div class="col-md-12">
<div class="text-center"> <input type="submit" class="btn btn-success btn-send" value="Register"></div>
<div class="text-center">Aready Register / have an account ? Login here</div>
</div>
</div>
</form>

from django import forms
class RegisterForm(forms.Form):
username = forms.CharField(max_length=50)
email = forms.EmailField(max_length=50)
subject = forms.CharField(max_length=50)
message = forms.CharField(widget=forms.Textarea)
You have to first create the forms.py file in your app as e.g(contact_us)
from django.shortcuts import render
from django.core.mail import send_mail
from .forms import RegisterForm
from django.http import HttpResponse
Create your views here.
def contact_us(request):
#request for POST
if request.method == 'POST':
form = RegisterForm(request.POST)
if form.is_valid():
sender_name = form.cleaned_data['username']
sender_email = form.cleaned_data['email']
message = "{0} has sent you a new message:\n\n{1}".format(sender_name, form.cleaned_data['message'])
send_mail('New Enquiry', message, sender_email, ['example#gmail.com'])
return HttpResponse('Thanks for Contacting US')
else:
form = RegisterForm()
return render(request, 'Contactus/contact.html', {'form': form})
After created the forms you have to insert the forms class name in views.py to display the custom form on browser.
#Create Your Template
<form id="contactform" method="POST">
{% csrf_token %}
<div class="column one-second">
{{ form.username }}
</div>
<div class="column one-second">
{{form.email }}
</div>
<div class="column one">
{{ form.subject }}
</div>
<div class="column one">
{{ form.message }}
</div>
<div class="column one">
<input type="submit" value="submit">
</div>
</form>
After this you have to call the form in template. To display your own custom form.
As i did above.

Related

how to customize the image filed returned by UpdateView

i use the UpdateView to update the products informations in my future webstore
in my temblate .
when i open my template i find a that it renders me the image link
edit_product.html
<form method="post">
<div class="form-group">
<label>Name</label>
{{form.name}}
</div>
<div class="form-group">
<label>Description</label>
{{form.description}}
</div>
<div class="form-group">
<label>Price</label>
{{form.nominal_price}}
</div>
<div class="form-group">
<label>Image</label>
<img src="{{form.instance.photo.url}}" width="200"/>
</div>
<div class="form-group">
{{form.photo}}
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
output
<form method="post">
<div class="form-group">
<label>Name</label>
<input type="text" name="name" value="flawless legs" maxlength="255" required="" id="id_name">
</div>
<div class="form-group">
<label>Description</label>
<textarea name="description" cols="40" rows="10" required="" id="id_description">Epilateur de jambes pour femmes</textarea>
</div>
<div class="form-group">
<label>Price</label>
<input type="number" name="nominal_price" value="199" min="0" required="" id="id_nominal_price">
</div>
<div class="form-group">
<label>Image</label>
<img src="/media/products/images/449165_ALTMORE2.jpeg" width="200">
</div>
<div class="form-group">
Currently: products/images/449165_ALTMORE2.jpeg<br>
Change:
<input type="file" name="photo" accept="image/*" id="id_photo">
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
what should i do to remove this Currently: products/images/449165_ALTMORE2.jpeg<br>
I found a tricky solution :
i replaced the
<div class="form-group">
{{form.photo}}
</div>
in my html file by an input type file <input type="file" name="photo" accept="image/*" id="id_photo"> and i edited my views
views.py
class ProductUpdateView(RedirectToPreviousMixin, UpdateView):
model = Product
form_class = ProductUpdateForm
template_name = 'admin/product_update.html'
def get_object(self):
return Product.objects.get(name=self.kwargs['product_name'])
def form_valid(self, form):
form = form.save(commit=False)
self.photo = form.photo
form.save()
return HttpResponseRedirect(self.get_success_url())

Django form imageupload give empty dic

i am trying to create edit profile form, in which i am trying to data from edit profile form. i am getting all data in request.POST but i am getting empty {} using request.Files
view.py
class EditProfile(View):
template_name="todo_app/edit_profile.html"
def get(self,request,pk):
if request.user.is_authenticated:
user_id=pk
profile=UserProfile.objects.get(user=user_id)
content={
'profile':profile,
}
return render(request,self.template_name,content)
else:
return redirect('todo_app:login')
def post(self,request,pk):
request_data=request.POST
first_name=request_data.get('first_name')
last_name=request_data.get('last_name')
mob_no=request_data.get('mob_no')
address_1=request_data.get('address_1')
address_2=request_data.get('address_2')
gender=request_data.get('gender')
age=request_data.get('age')
state=request_data.get('state')
city=request_data.get('city')
country=request_data.get('country')
bio=request_data.get('bio')
# profile_pic=request.FILES['profile_pic']
print(request_data)
print("_"*123)
print(request.FILES)
return redirect('todo_app:edit_profile',pk)
and print result on console is
<QueryDict: {'csrfmiddlewaretoken': ['mkfuwR6Uc99svosQvsVpho11JOXOdESSmp2sm1ULDFrFu3UHRrkASTWeSyRwXyzH'], 'first_name': ['upasana'], 'last_name': ['kulshresths'], 'address_1': ['9 Purushottam Nagar'], 'address_2': ['Dayal Bagh'], 'mob_no': ['9087654321'], 'gender': ['Male'], 'age': ['12'], 'state': ['Uttar Pradesh'], 'city': ['Agra'], 'country': ['India'], 'bio': ['Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin professo'], 'profile_pic': ['Screenshot from 2021-07-14 16-44-31.png']}>
___________________________________________________________________________________________________________________________
<MultiValueDict: {}>
edit_profile.html
<form method="POST" action="{% url 'todo_app:edit_profile' profile.user.id %}" enctype="multipart/form-data">
{% csrf_token %}
<div class="form-row">
<div class="col-md-6 mb-3">
<label for="first_name">First name</label>
<input type="text" class="form-control" id="first_name" value="{{profile.user.first_name}}" name="first_name" required>
</div>
<div class="col-md-6 mb-3">
<label for="last_name">Last name</label>
<input type="text" class="form-control" id="last_name" value="{{profile.user.last_name}}" name="last_name" required>
</div>
<div class="col-md-6 mb-3">
<label for="address_1">Address line 1</label>
<input type="text" class="form-control" id="address_1" value="{{profile.address_line_1}}" name="address_1" required>
</div>
<div class="col-md-6 mb-3">
<label for="address_2">Address line 2</label>
<input type="text" class="form-control" id="address_2" value="{{profile.address_line_2}}" name="address_2" required>
</div>
</div>
<div class="form-row">
<div class="col-md-6 mb-3">
<label for="mobile_no">Mobile No</label>
<input type="number" min="6000000000" max="9999999999" value="{{profile.user.mob_no}}" class="form-control" id="mobile_no" name="mob_no" required>
</div>
<div class="col-md-3 mb-3">
<label for="gender">Gender</label>
<select class="custom-select" id="gender" name="gender" required>
<option>Male</option>
<option>Female</option>
<option>🏳️‍🌈</option>
</select>
</div>
<div class="col-md-3 mb-3">
<label for="age">Age</label>
<input type="number" min="0" max="120" value="{{profile.age}}" class="form-control" id="age" name="age" required>
</div>
</div>
<div class="form-row">
<div class="col-md-6 mb-3">
<label for="State" class="form-label">State</label>
<input type="text" class="form-control" id="State" name="state" value="{{profile.state}}">
</div>
<div class="col-md-3 mb-3">
<label for="city" class="form-label">City</label>
<input type="text" class="form-control" id="city" name="city" value="{{profile.city}}">
</div>
<div class="col-md-3 mb-3">
<label for="country" class="form-label">Country</label>
<input type="text" class="form-control" id="country" name="country" value="{{profile.country}}" >
</div>
</div>
<div class="form-row">
<div class="col-md-10 mb-3">
<label for="bio">Bio</label>
<textarea class="form-control" placeholder="Leave a comment here" id="bio" style="height: 100px" name="bio">{{profile.bio}}</textarea>
</div>
<div class="col-md-2 mb-3 ml-auto mt-4">
<img src="{{profile.profile_pic.url}}" class="rounded-circle" width="100px" alt="...">
</div>
</div>
<div class="input-group mb-3">
<div class="input-group-prepend">
<span class="input-group-text" id="profile_pc_spam">Profile Pic</span>
</div>
<div class="custom-file">
<input type="file" class="custom-file-input" id="profile_pic" name='profile_pic' >
<label class="custom-file-label" for="profile_pic">Choose file</label>
</div>
</div>
<div class="text-center">
<button class="btn my_button_delete mb-4 ustify-content-center" type="submit" >Submit form</button>
</div>
</form>
what am I doing wrong? i don't want to use django forms.
i try to search old question related this problem on stack overflow but i found that every one suggest using django form. if i missed any answer please tag me

my model is not showing up in admin model data is getting visble in link bar in csrf middle ware token

{% block body %}
{% load static %}
<div class="container my-3">
<h3>Contact Us</h3>
<form action="/contact" method="post"> {% csrf_token %}
<div class="form-group">
<label for="name">Name</label>
<input type="text" class="form-control" id="name" name='name' placeholder="Enter Your Name">
</div>
<div class="form-group">
<label for="name">Email</label>
<input type="email" class="form-control" id="email" name='email' placeholder="Enter Your Email">
</div>
<div class="form-group">
<label for="name">Phone</label>
<input type="tel" class="form-control" id="phone" name='phone' placeholder="Enter Your Phone Number">
</div>
<div class="form-group">
<label for="desc">Your requirements:-</label>
<textarea class="form-control" id="desc" name='desc' rows="3"></textarea>
</div>
<button type="submit" class="btn btn-success">Contact</button>
</form>
</div>
def index(request):
return render(request, 'prop/home.html')
def contact(request):
if request.method=='POST':
name = request.POST['name']
email = request.POST['email']
phone = request.POST['phone']
desc = request.POST['desc']
contact=Contact(name=name,email=email,phone=phone,desc=desc)
contact.save()
return render(request, 'prop/contact.html')
result
"GET /prop/contact/?csrfmiddlewaretoken=npxCzACid026bcA0bYugZdAL1K2Ondqu2EtpzTuoDbnYivut9tsHJnh5Tq7NWOdU&name=yashi&email=hyashkzo%40gmail.com&phone=55645blbb&desc= HTTP/1.1" 200 8758
make following changes and try
<form action="{% url 'contact' %}" method="POST"> {% csrf_token %}
instead of button
<input type="submit" value="Contact" class="btn btn-success">
Provided you have a url with name contact

'stripeToken' error when attempting to submit payment form

I'm following an outdate django e-commerce course using django and stripe. The course is about 4 years old so a lot has changed with django and stripe, which has allowed me to do a ton of research on both. I'm at the end of the tutorial and have run into an issue while creating the checkout page and more importantly using stripe to 'Create Charge'. I am receiving the following error message:
django.utils.datastructures.MultiValueDictKeyError
django.utils.datastructures.MultiValueDictKeyError: 'stripeToken'
I read in the documentation for Creating Charge which states
token = request.POST['stripeToken'] # Using Flask
is for Flask (I think), however when i remove ['stripeToken'], I receive this error message:
stripe.error.InvalidRequestError stripe.error.InvalidRequestError:
Request req_kikB88HKbEkq9W: Could not find payment information
I need a way to pass Stripe the payment information when the form is submitted. Also, I came across this post but the publisher was receiving error message do to multiple forms
view.py
from django.conf import settings
from django.contrib.auth.decorators import login_required
from django.shortcuts import render
import stripe
stripe.api_key = settings.STRIPE_SECRET_KEY
# Create your views here.
#login_required
def checkout(request):
publish_key = settings.STRIPE_PUBLISHABLE_KEY
if request.method == 'POST':
token = request.POST['stripeToken']
stripe.Charge.create(
amount=999,
currency='usd',
description='Example charge',
source=token,
statement_descriptor='Custom descriptor',
)
context = {'publish_key': publish_key}
template = 'checkout.html'
return render(request, template, context)
checkout.html
{% extends 'base.html' %}
{% block content %}
<div class="col-sm-6 offset-md-3">
<h4 class="mb-3">Billing address</h4>
<form id="payment-form" action="" method="post">{% csrf_token %}
<div class="row">
<div class="col-md-6 mb-3">
<label for="firstName">First name</label>
<input type="text" class="form-control" id="firstName" required style="background-image: url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAABHklEQVQ4EaVTO26DQBD1ohQWaS2lg9JybZ+AK7hNwx2oIoVf4UPQ0Lj1FdKktevIpel8AKNUkDcWMxpgSaIEaTVv3sx7uztiTdu2s/98DywOw3Dued4Who/M2aIx5lZV1aEsy0+qiwHELyi+Ytl0PQ69SxAxkWIA4RMRTdNsKE59juMcuZd6xIAFeZ6fGCdJ8kY4y7KAuTRNGd7jyEBXsdOPE3a0QGPsniOnnYMO67LgSQN9T41F2QGrQRRFCwyzoIF2qyBuKKbcOgPXdVeY9rMWgNsjf9ccYesJhk3f5dYT1HX9gR0LLQR30TnjkUEcx2uIuS4RnI+aj6sJR0AM8AaumPaM/rRehyWhXqbFAA9kh3/8/NvHxAYGAsZ/il8IalkCLBfNVAAAAABJRU5ErkJggg=="); background-repeat: no-repeat; background-attachment: scroll; background-size: 16px 18px; background-position: 98% 50%;" required/>
<div class="invalid-feedback">
Valid first name is required.
</div>
</div>
<div class="col-md-6 mb-3">
<label for="lastName">Last name</label>
<input type="text" class="form-control" id="lastName" required />
<div class="invalid-feedback">
Valid last name is required.
</div>
</div>
</div>
<div class="mb-3">
<label for="email">Email <span class="text-muted"></span></label>
<input type="email" class="form-control" id="email" placeholder="you#example.com" required />
<div class="invalid-feedback">
Please enter a valid email address for shipping updates.
</div>
</div>
<div class="mb-3">
<label for="address">Address</label>
<input type="text" class="form-control" id="address" placeholder="1234 Main St" required />
<div class="invalid-feedback">
Please enter your shipping address.
</div>
</div>
<div class="mb-3">
<label for="address2">Address 2 <span class="text-muted"></span></label>
<input type="text" class="form-control" id="address2" placeholder="Apartment or suite" />
</div>
<div class="row">
<div class="col-md-5 mb-3">
<label for="city">City</label>
<input type="text" class="form-control" id="city" required />
<div class="invalid-feedback">
Zip code required.
</div>
</div>
<div class="col-md-4 mb-3">
<label for="state">State</label>
<select class="custom-select d-block w-100" id="state" required>
<option value="">Choose...</option>
<option>California</option>
</select>
<div class="invalid-feedback">
Please provide a valid state.
</div>
</div>
<div class="col-md-3 mb-3">
<label for="zip">Zip</label>
<input type="text" class="form-control" id="zip" required />
<div class="invalid-feedback">
Zip code required.
</div>
</div>
</div>
<hr class="mb-4">
<div class="custom-control custom-checkbox">
<input type="checkbox" class="custom-control-input" id="same-address">
<label class="custom-control-label" for="same-address">Shipping address is the same as my billing address</label>
</div>
<div class="custom-control custom-checkbox">
<input type="checkbox" class="custom-control-input" id="save-info">
<label class="custom-control-label" for="save-info">Save this information for next time</label>
</div>
<hr class="mb-4">
<h4 class="mb-3">Payment</h4>
<div class="d-block my-3">
<label for="card-element">Credit or debit card</label>
<div id="card-element" class="form-control" style='height: 2.4em; padding-top: .7em;'>
<!-- A Stripe Element will be inserted here. -->
</div>
<!-- Used to display form errors. -->
<div id="card-errors" role="alert"></div>
</div>
<hr class="mb-4">
<button class="btn btn-outline-success btn-lg btn-block" type="submit">Continue to checkout</button>
</form>
</div>
{% endblock %}
app.js
// Create a Stripe client.
const stripe = Stripe('{{ publish_key }}');
// Create an instance of Elements.
const elements = stripe.elements();
// Create an instance of the card Element.
const card = elements.create('card', {});
// Add an instance of the card Element into the `card-element` <div>.
card.mount('#card-element');
// Handle real-time validation errors from the card Element.
card.addEventListener('change', ({error}) => {
const displayError = document.getElementById('card-errors');
if (error) {
displayError.textContent = error.message;
} else {
displayError.textContent = '';
}
});
// Create a token or display an error when the form is submitted.
const form = document.getElementById('payment-form');
form.addEventListener('submit', async (event) => {
event.preventDefault();
const {token, error} = await stripe.createToken(card);
if (error) {
// Inform the customer that there was an error.
const errorElement = document.getElementById('card-errors');
errorElement.textContent = error.message;
} else {
// Send the token to your server.
stripeTokenHandler(token);
}
});
// Submit the form with the token ID.
const stripeTokenHandler = (token) => {
// Insert the token ID into the form so it gets submitted to the server
const form = document.getElementById('payment-form'),
hiddenInput = document.createElement('input');
hiddenInput.setAttribute('type', 'hidden');
hiddenInput.setAttribute('name', 'stripeToken');
hiddenInput.setAttribute('value', token.id);
form.appendChild(hiddenInput);
// Submit the form
form.submit();
}

How to show error messages in a custom signup template in Django

I'm trying to show error message in my custom signup template. Just to verify my below codes work, I used the {{ form.as_table }} and it shows error message properly. However, when I use my custom signup template, it doesn't show any error message when I cause an error on purpose on the signup form.
HTML
<form class="form-signin" method="POST">
{% csrf_token %}
<div class="container">
<div class="jumbotron">
<a class="navbar-brand js-scroll-trigger" href="{% url 'boutique:index' %}"><img width="165" height="30" src="{% static 'boutique/img/modvisor_logo_black.png' %}"></a>
<br><br>
<div class="text-center mb-4">
<h1 class="h3 mb-3 font-weight-normal">Join Modvisor</h1>
<p class="error-message">
{% if form.non_field_errors %}
{% for error in form.non_field_errors %}
{{ error }}
{% endfor %}
{% endif %}
</p>
</div>
<div class="form-label-group">
<input type="text" id="inputEmail" class="form-control" name="username" placeholder="Email address" required autofocus>
<label for="inputEmail">Email</label>
</div>
<div class="form-label-group">
<input type="password" id="inputPassword1" class="form-control" name="password1" placeholder="Password" required>
<label for="inputPassword">Password</label>
</div>
<div class="form-label-group">
<input type="password" id="inputPassword2" class="form-control" name="password2" placeholder="Password" required>
<label for="inputPassword">Confirm Password</label>
</div>
<!--
<div class="form-label-group">
<input type="password" id="inputPassword" class="form-control" name="password2" placeholder="Password" required>
<label for="inputPassword">Confirm Password</label>
</div>
<div class="checkbox mb-3">
<label>
<input type="checkbox" value="remember-me"> Remember me
</label>
</div>
-->
<button class="btn btn-success btn-block" type="submit">Sign Up</button>
<br>
<button class="btn btn-secondary btn-block" type="button">Back</button>
<p class="mt-5 mb-3 text-muted text-center">© 2018 Modvisor All Rights Reserved.</p></p>
</div>
</div>
</form>
forms.py
class SignupForm(UserCreationForm):
class Meta(UserCreationForm.Meta):
fields = UserCreationForm.Meta.fields
views.py
def signup(request):
if request.method == 'POST':
form = SignupForm(request.POST)
if form.is_valid():
form.save()
return redirect(settings.LOGIN_URL)
else:
form = SignupForm()
return render(request, 'accounts/register.html', {'form': form})
You should use form.errors.field_name for errors related to specific field. Like for error on username field, it will be form.errors.username
You HTML will look like
<div class='error'>{{form.errors.username}}</div>
<div class="form-label-group">
<input type="text" id="inputEmail" class="form-control" name="username" placeholder="Email address" required autofocus>
<label for="inputEmail">Email</label>
</div>