I am trying to initiate a registration process for my website. I am using Python 3.3.5, and Django 1.6.
I receive an error saying No module named 'forms'. I am fairly new to Python/Django.
Here are my files:
Views.py:
from django.shortcuts import render_to_response
from django.http import HttpResponseRedirect
from django.contrib import auth
from django.core.context_processors import csrf
from django.contrib.auth.forms import UserCreationForm
from forms import MyRegistrationForm
def register_user(request):
if request.method == 'POST':
form = MyRegistrationForm(request.POST)
if form.is_valid():
form.save()
return HttpResponseRedirect('/accounts/register_success')
else:
form = MyRegistrationForm()
args = {}
args.update(csrf(request))
args['form'] = form
return render_to_response('register1.html', args)
def register_success(request):
return render_to_response('register_success.html')
Forms.py
from django import forms
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm
class MyRegistrationForm(UserCreationForm):
email = forms.EmailField(required=True)
class Meta:
model = User
fields = ('username', 'email', 'password1', 'password2')
def save(self, commit=True):
user = super(MyRegistrationForm, self).save(commit=False)
user.email = self.cleaned_data['email']
# user.set_password(self.cleaned_data['password1'])
if commit:
user.save()
return user
the forms.py is located in the same folder as views.py. I tried from django.forms import MyRegistrationForm but then the error cannot import name MyRegistrationForm arises.
If you didn't change the default location of views.py, then it's likely to be in your application folder. Try something like from myapp.forms import MyRegistrationForm where myapp is the name of your application
if thats an app module, change your 6th line:
from forms import MyRegistrationForm
to:
from .forms import MyRegistrationForm
(just add a dot before forms)
Related
When I am registering as a new user or want to change my password, then the Message which is needed to be sent to the email is showing in the terminal instead. Here is the terminal picture:
enter image description here
Here is the views.py function.
from aiohttp import request
from django.contrib.sites.models import Site
from django.shortcuts import render, redirect, get_object_or_404
from django.contrib.auth.decorators import login_required
from django.contrib import messages
from companies.models import Company
from accounts.roles import UserRole
# User mode
from .models import CustomUser
from domains.models import Domain
from dashboard.models import MarketingHome, SliderHome
# Custom forms
from .forms import PublicCustomUserChangeForm, CustomChangePasswordForm
from django.contrib.auth import views as auth_views
from django.shortcuts import resolve_url
from allauth.account.views import SignupView, LoginView
#login_required
def change_password_user(request):
company = CustomUser.get_company(request.user)
if request.method == "GET":
form = CustomChangePasswordForm(request.user)
context = {
'form': form,
'company': company
}
return render(request, 'account/change_password_user.html', context)
else:
form = CustomChangePasswordForm(request.user, request.POST)
if form.is_valid():
form.save()
# update_session_auth_hash(request, user)
messages.success(request, 'Your password was successfully updated!')
return redirect('account_change_password_user')
else:
messages.error(request, form.errors)
return redirect('account_change_password_user')
here is the registration function:
class AccountSignupView(SignupView):
template_name = "account/signup.html"
def get_context_data(self, **kwargs):
current_site = self.request.META['HTTP_HOST']
context = super(SignupView, self).get_context_data(**kwargs)
context = {
'slider': SliderHome.objects.filter(domain_site__domain__contains=current_site, is_active=True),
# 'current_domain': Domain.objects.filter(site__domain__contains=current_site).first()
}
return context
account_signup_view = AccountSignupView.as_view()
You may be using EMAIL_BACKEND in settings.py as this way:
EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'
Instead change it to your desired email backend.
Example -
'django.core.mail.backends.filebased.EmailBackend'
'django.core.mail.backends.smtp.EmailBackend'
I would like to send a contactform to an emailid as well as save it to postgresql database.The following code helps me to send it to the mail id but can't save it in the database. can anyone please help me to solve this one which would be very much appreciated
urls.py
from django.contrib import admin
from django.urls import path
from.import views
urlpatterns = [
path('email/', views.email, name='email'),
path('success/', views.success, name='success')
]
models.py
from django.db import models
from django.forms import ModelForm
class Comment(models.Model):
what_about = models.CharField(max_length=255)
contact_email = models.EmailField(max_length=255)
content = models.TextField()
Name = models.CharField(max_length=255)
Phone_Number = models.CharField(max_length=255)
def __str__(self): # __unicode__ on Python 2
return self.what_about
forms.py
from django.forms import ModelForm
from django import forms
from .models import Comment
class MyCommentForm(forms.ModelForm):
class Meta:
model = Comment
fields = ['what_about', 'content', 'contact_email', 'Name', 'Phone_Number']
views.py
from django.shortcuts import render, redirect
from django.core.mail import send_mail, BadHeaderError
from django.http import HttpResponse, HttpResponseRedirect
from django import forms
from django.utils import timezone
from.forms import MyCommentForm
def email(request):
if request.method == 'GET':
form = MyCommentForm()
else:
form = MyCommentForm(request.POST)
if form.is_valid():
form.save()
cd = form.cleaned_data
subject = form.cleaned_data['what_about']
from_email = form.cleaned_data['contact_email']
message = 'contact_email: "{}"\n Phone_Number: "{}"\n Name: "{}"\n content: "{}"'.format(cd['contact_email'],
cd['Phone_Number'],
cd['Name'],
cd['content'])
try:
send_mail(subject, message, from_email, ['prasanth#interloggg.net'])
except BadHeaderError:
return HttpResponse('Invalid header found.')
return redirect('success')
return render(request, "email.html", {'form': form})
def success(request):
return HttpResponse('Success! Thank you for your message.')
You need to import your models in the views and make "Comment.save()"
You're importing ur forms but it isn't ur database, place it in the moment where you think suit the best, save every answer to the right column.
I am trying to filter user's alias. I am using Django's userform and its authentication.
forms.py
from django import forms
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User
class SignupForm(UserCreationForm):
email = forms.CharField(
retuired=True,
widget=EmailInput(
attrs={'class':'validate',}
)
)
views.py
from django.shortcuts import render,redirect
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth import login as auth_login
def signup(req):
if req.method == "POST":
form = UserCreationForm(req.POST)
if form.is_valid():
user = form.save()
auth_login(req, user)
return redirect('home')
else:
form = UserCreationForm()
context = {
'form':form,
}
return render(req, "signup.html", context)
I believe that I need to filter inside of views.py. For example, if I want to filter alias which is not gmail, they cannot signup. How can I filter email?
Thanks in advance!
You can use clean_<field_name> method.
def clean_email(self):
email = self.cleaned_data['email']
if not email.endswith('gmail.com'):
raise forms.ValidationError("Invalid email", code='invalid email')
return email
https://docs.djangoproject.com/en/1.11/ref/forms/validation/#cleaning-a-specific-field-attribute
First attempt at trying to create a student user by extending the User model.
Issue: Upon clicking register btn i.e.Login (btn) instead of
redirecting to home it shows the following: NameError at /register/
...name 'user' is not defined
File "E:\ifb299\tutorial2\accounts\views.py", line 33, in register
Students.objects.create(user=user) NameError: name 'user' is not defined [25/Mar/2018 14:38:07] "POST /register/ HTTP/1.1" 500 67801
Not really sure what I'm doing wrong, why is Students.objects.create(user=user) wrong and how do i fix it, please?
views.py
from django.shortcuts import render
from django.shortcuts import redirect
from accounts.forms import RegistrationForm, EditProfileForm
from django.contrib.auth.models import User
from accounts.models import Students
from django.contrib.auth.forms import UserChangeForm
from django.http import HttpResponse
from django.contrib.auth.decorators import login_required
def home(request):
return render(request, 'accounts/home.html')
def login_redirect(request):
return redirect('/login/')
def register(request):
# Once register page loads, either it will send to the server POST data (if the form is submitted), else if it don't send post data create a user form to register
if request.method == "POST":
form = RegistrationForm(request.POST)
if form.is_valid():
form.save()
Students.objects.create(user=user)
return redirect('../home/')
else:
# Create the django default user form and send it as a dictionary in args to the reg_form.html page.
form = RegistrationForm()
args = {'form': form}
return render(request, 'accounts/reg_form.html', args)
#login_required
def view_profile(request):
args = {'user': request.user}
return render(request, 'accounts/profile.html', args)
#login_required
def edit_profile(request):
# Handle post request - if the user submits a form change form details and pass the intance user
if request.method == 'POST':
form = EditProfileForm(request.POST, instance=request.user)
if form.is_valid():
form.save()
return redirect('../profile')
# Handles the get request - if no post info is submitted then get the form and display it on the edit profile page.
else:
form = EditProfileForm(instance=request.user)
args = {'form': form}
return render(request, 'accounts/profile_edit.html', args)
models.py
from django.db import models
from django.contrib.auth.models import AbstractUser
from django.contrib.auth.models import User
from django.db.models.signals import post_save
from django.db.models.signals import *
from django.conf import settings
class Students(AbstractUser):
bio = models.TextField(max_length=500, blank=True)
location = models.CharField(max_length=30, blank=True)
birth_date = models.DateField(null=True, blank=True)
forms.py
from django import forms
from django.contrib.auth.models import User
from .models import *
from django.contrib.auth.forms import UserCreationForm, UserChangeForm
from betterforms.multiform import MultiModelForm
from django.contrib.auth.forms import UserCreationForm
# Create a custom form that inherites form UserCreationForm (adding our own fields to save i db)
# Inheriting form in the paramters ()
class RegistrationForm(UserCreationForm):
email = forms.EmailField(required=True)
class Meta:
model = Students
fields = (
'username',
'first_name',
'last_name',
'email',
'password1',
'password2',
'bio',
'location',
'birth_date',
)
def save(self, commit=True):
user = super(RegistrationForm, self).save(commit=False)
user.first_name = self.cleaned_data['first_name']
user.last_name = self.cleaned_data['last_name']
user.email = self.cleaned_data['email']
if commit:
user.save()
return user
# Inherits from UserChangeForm class - we keep everything i.e. methods, functionality same but change the things we want to show - connected to the User model
class EditProfileForm(UserChangeForm):
class Meta:
model = User
# Create fields variable get has all the fields we want to show
fields = (
'email',
'first_name',
'last_name',
'password'
)
first, you did not save the return value of form.save() to the variable user.
second, there is no field user your model Student.
I want to save the email and name fields in django default table called UserSignup
my models.py is:
from django.db import models
class UserSignup(models.Model):
mailid = models.CharField(max_length=100)
name = models.CharField(max_length=100)
my views.py is:
from django import views
from django.shortcuts import render_to_response
from django.template import RequestContext
from Deals.signup.forms import signup
from django.contrib.auth.models import User
from django.http import HttpResponse
def usersignup(request,form_class=signup):
form = form_class()
print form
if form.is_valid():
mail= UserSignup(mailid=request.POST['mailid'])
mail.save()
name= UserSignup(name=request.POST['name'])
name.save()
else:
form = form_class()
return render_to_response('signup/registration_form.html',{'form':form})
and forms.py is
from django import forms
from django.contrib.auth.models import User
from Deals.signup.models import *
from django.utils.translation import ugettext_lazy as _
class signup(forms.Form):
email = forms.EmailField(widget=forms.TextInput(),
label=_("Email address:"))
username = forms.RegexField(regex=r'^\w+$',
max_length=30,
widget=forms.TextInput(),
label=_("Name:"))
def save(self,request,update):
name = self.cleaned_data['name']
name.save()
email = self.cleaned_data['email']
email.save()
Please help me in saving my forms input in database
Check the Django documentation properly http://docs.djangoproject.com/en/dev/topics/forms/
Just change your code in views.py.
def usersignup(request,form_class=signup):
if request.method == 'POST': #If its a form submission, the method is POST
form = form_class(request.POST)
if form.is_valid():
newuser = form.save()
else: #Else display the form
form = form_class()
return render_to_response('signup/registration_form.html',{'form':form})
The 'save' function in your forms file is incorrect and is not needed.
On a side note, your "UserSignup" is not a default User Table. That would be the user model provided by Django. And that already has the fields that you are creating in UserSignup. Why don't you use that feature of Django?
It might be better to save the model elements in the form in one time.
def save(self):
new_user = User.objects.create_user(name = self.cleaned_data['name'],
email = self.cleaned_data['email'])
return new_user