I would like to create a contact form on my Django website.
For now, this is my code:
models.py:
from django.db import models
from phonenumber_field.modelfields import PhoneNumberField
class Client(models.Model):
phone = PhoneNumberField(null=False, blank=True, unique=True)
forms.py:
from django import forms
from phonenumber_field.modelfields import PhoneNumberField
class ContactForm(forms.Form):
fullName = forms.CharField(max_length=100)
email = forms.EmailField()
phone = PhoneNumberField()
message = forms.CharField(widget=forms.Textarea)
views.py:
def contact(request):
# return render(request, 'contact.html')
if request.method == 'POST':
form = ContactForm(request.POST)
if form.is_valid():
# send email code goes here
return HttpResponse('Thanks for contacting us!')
else:
form = ContactForm()
return render(request, 'contact.html', {'form': form})
html:
<form method="post">
{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Submit" />
</form>
I of course installed phonenumber_field and added it in settings.py
This is the result, phone field missing:
Any help is hugely appreciated! Thanks for your time.
You used a model field, whereas for a form, you need a form field:
from django import forms
# a form field ↓
from phonenumber_field.formfields import PhoneNumberField
class ContactForm(forms.Form):
fullName = forms.CharField(max_length=100)
email = forms.EmailField()
phone = PhoneNumberField()
message = forms.CharField(widget=forms.Textarea)
Related
I am trying to make a contact form but it's html template does not see {{ form }} template. What am I doing wrong? Where is an error.
My code is attached above.
models.py
class Contact(models.Model):
listing = models.CharField(max_length=200)
listing_id = models.IntegerField()
name = models.CharField(max_length=200)
email = models.EmailField()
phone = models.CharField(max_length=100)
message = models.TextField(blank=True)
file = models.FileField(upload_to='files/%Y/%m/%d/', blank=True)
contact_date = models.DateTimeField(default=datetime.now, blank=True)
user_id = models.IntegerField(blank=True)
def __str__(self):
return self.name
def get_absolute_url(self):
return reverse('listings', kwargs={'pk': self.pk})
In views.py file
class ContactCreate(CreateView):
model = Contact
form_class = ContactForm
template_name = 'listing.html'
urls.py
from django.urls import path
from . import views
urlpatterns = [
path('listings/<int:pk>/', views.ContactCreate.as_view(), name='contact-create')
]
html
<form action="{% url 'contact-create' pk=listing.pk %}" method="post">
{{ form }}
{% csrf_token %}
<input type="submit" value="Send" class="btn btn-block btn-secondary">
</form>
forms.py
class ContactForm(forms.ModelForm):
class Meta:
model = Contact
fields = ['name','email','phone','file']
Could you help me out, please
If you provide a form_class with ContactForm, Django is expecting a form to be provided so you have two options:
Create a form.py and add the following:
from django import forms
class ContactForm(forms.Form):
name = forms.CharField()
message = forms.CharField(widget=forms.Textarea)
Don't forget to add that to your view:
from myapp.forms import ContactForm
If you want your custom form to be display you have to specify the form_class in your create view:
form_class = ContactForm
If you are using a custom template to display your form add the following to your create view:
template_name = 'listing.html' # or the path to your template
What I want to do: I want to have a login form that when details are entered they are saved on the admin side.
My problem: the forms are not showing up on my local host page. See image below:
Here is the code from the login form app:
admin.py:
from django.contrib import admin
# Register your models here.
from .models import Contact
admin.site.register(Contact)
from apps.py:
from django.apps import AppConfig
class ContactConfig(AppConfig):
name = 'contact'
from forms.py
from .models import Contact
class ContactForm(forms.ModelForm):
class Meta:
model = Contact
fields = ('username', 'password')
from models.py:
class Contact(models.Model):
username = models.CharField(max_length=100)
password = models.CharField(
max_length=100,
)
def __str__(self):
return f'{self.username} {self.password}'
from views.py:
# Create your views here.
from .forms import ContactForm
def contact(request):
template = "home2.html"
if request.method == "POST":
form = ContactForm(request.POST)
if form.is_valid():
form.save()
else:
form = ContactForm()
context = {
'form': form,
}
return render(request, template, context)
Then finally from the login page:
{% load static %}
<form method="post" class="form">
{% csrf_token %}
{{ form }}
<button type="submit" class="btn">Log In</button>
</form>
Another thing: forms are connected to the admin side but just do not appear on the login page
I am trying to get Seller information, username, password, name, mobile number and address. I have used User to get the username and password, connected the username to my model through OneToOneField relationship and later save the information.
I have made a model named SellerDetails which gets the user field from OneToOneField with User and rest all details are provided as follows:
#models.py
from django.db import models
from django.contrib.auth.models import User
# Create your models here.
class SellerDetails(models.Model):
"""docstring for SellerDetails."""
user = models.OneToOneField(User, on_delete=models.CASCADE)
name = models.CharField(max_length=128, null = True)
address = models.CharField(max_length=256)
mobile_number = models.IntegerField(primary_key=True)
def __str__(self):
return self.user.username
then I have made two forms in my forms.py
#forms.py
from django import forms
from django.contrib.auth.models import User
from avkara.models import SellerDetails, VendorDetails
class UserForm(forms.ModelForm):
password = forms.CharField(widget = forms.PasswordInput())
class Meta:
model = User
fields = ('username', 'password')
class SellerDetailsForm(forms.ModelForm):
"""docstring for SellerDetailsForm."""
class Meta:
model = SellerDetails
fields = ('name','address','mobile_number')
#Then I tried established a relation while saving the form
#views.py
def Signup_seller(request):
seller_registered = False
if request.method == "POST":
user_form = UserForm(data = request.POST)
user_details = SellerDetailsForm(data = request.POST)
if user_form.is_valid() and user_details.is_valid():
seller = user_form.save()
seller.set_password(seller.password)
seller.save()
#saving user_details now
other_details = user_details.save(commit= False)
other_details.user = seller
other_details.save()
seller_registered = True
else:
user_form = UserForm()
user_details = SellerDetailsForm()
return render(request, 'avkara/signup_seller.html',{'seller_registered': seller_registered , 'user_form' : user_form, 'user_details' : user_details})
#Then I tried serving both forms through Html form. Here is my html
#signup_seller.html
<div class="container jumbotron">
<h2>Sign up</h2><br><br><br>
<form class="form-horizontal" method="POST">
{% csrf_token %}
{{ user_form.as_p }}
{{ user_details.as_p }}
<input type="submit" value="Submit">
</form>
</div>
#The desired out should be Thank you for registering but I get following error
IntegrityError at /avkara/signup_seller
NOT NULL constraint failed: avkara_sellerdetails.password
#This is error it is showing
F:\Webpage\python\techforstock\avkara\views.py in Signup_seller
other_details.save() <!--error part --!>
I have worked one it for hours, but no luck, Can Anyone help me out with this.
I want the username and password to be registered in users section and other information saved in Sellerdetails when I open Admin interface, but it should be with respect to the specific username.
I just want to know how to make a register page accept one email address
I have not tried anything yet
def register(request):
if request.method == 'POST':
form = UserRegisterForm(request.POST)
if form.is_valid():
form.save()
username = form.cleaned_data.get('username')
messages.success(request, f'Your account has been created! You are now able to log in')
return redirect('login')
else:
form = UserRegisterForm()
return render(request, 'users/register.html', {'form': form})
I want the register page to accept only one email address so it is used only once to register
Make sure this is the code in Django to make a register page!!!
models.py
from django.db import models
class Register(models.Model):
class Meta:
verbose_name_plural = 'Register'
email = models.EmailField()
forms.py
from django import forms
from index.models import *
class Registerform(forms.ModelForm):
class Meta:
model = Register
fields = '__all__'
views.py
from index import forms as formlocal
def register(request):
form = formlocal.Registerform()
if request.method == 'POST':
form = formlocal.Registerform(request.POST)
some_var = request.POST.getlist('role')
if form.is_valid():
form.save(commit=True)
return render(request,'index/register.html',{'form':form})
urls.py
from django.urls import path, include
from index import views as ind
urlpatterns = [
path('register/', ind.register,name='joincoc'),
]
template - index/register.html
<form method="POST">
<div>
{{ form.errors }}
</div>
<div>
{{ form.email}}
</div>
{% csrf_token %}
<button type="submit" name="submit">Submit</button>
</form>
Hi I have a simple django form, which enables the users to signup to the website. but am confused how can I submit my form fields. Am new to Django. Please help me on it. Thanks in advance.
Forms.py:
from django import forms
from django import forms
from django.contrib.auth.models import User # fill in custom user info then save it
# from django.contrib.auth.forms import UserCreationForm
class UserForm(forms.Form):
email = forms.EmailField(max_length=100, null=True, blank=False)
first_name = forms.CharField(max_length=20)
password = forms.CharField(max_length=20, required=True, label="password", widget=forms.PasswordInput)
last_name = forms.CharField(max_length=20)
date_joined = forms.DateTimeField(auto_now_add=True, auto_now=False)
date_ = forms.DateTimeField(auto_now_add=False, auto_now=True)
Views.py
def register_user(request):
if request.method == 'POST':
print "Saisisis"
form = UserForm(request.POST) # create form object
if form.is_valid():
form.save()
return HttpResponseRedirect('/accounts/register_success')
print "blah"
args = {}
args.update(csrf(request))
args['form'] = UserForm()
# import pdb
# pdb.set_trace()
print args
return render(request, 'pages/signup.html', args)
and my html:
{% extends 'pages/base.html' %}
{% block additional_styles %}
<style>
body{
background:url(static/img/nose.jpg) no-repeat center center fixed;
-webkit-background-size: cover
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
}
</style>
{% endblock %}
{% block contentblock %}
<div class="container well">
<h1> Please Sign Up fellas</h1>
<form method="POST" action="login.html">
{% csrf_token %}
{{ form.as_table }}
<input type="submit" value="OK">
</form>
</div>
{% endblock %}
To do what you've got there, you'd need to have a ModelForm so that when you call form.save() Django knows what the model you are creating an instance of. For example;
Forms.py:
from django import forms
from django.contrib.auth.models import User
class UserForm(forms.ModelForm):
email = forms.EmailField(max_length=100, null=True, blank=False)
first_name = forms.CharField(max_length=20)
password = forms.CharField(max_length=20, required=True, label="password", widget=forms.PasswordInput)
last_name = forms.CharField(max_length=20)
date_joined = forms.DateTimeField(auto_now_add=True, auto_now=False)
date_ = forms.DateTimeField(auto_now_add=False, auto_now=True)
class Meta:
model = User
But going from what you've got you'd need to create the model instance yourself, then set the data, then save it;
def register_user(request):
if request.method == 'POST':
form = UserForm(request.POST) # create form object
if form.is_valid():
email = form.cleaned_data['email']
user = User(email=email)
user.save()
return HttpResponseRedirect('/accounts/register_success')