I am getting the error NameError: name 'Sell' is not defined But I have defined this Model in Models.py
Plz, tell what is the error I have posted my relevant code. Thanks in advance.
Models.py of buy app
from django.db import models
from django.contrib.auth.models import User
# Create your models here.
class Sell(models.Model):
Cats =(
('Course book','Course book'),
('Fiction','Fiction'),
)
Lang =(
('Hindi','Hindi'),
('English','English'),
('Tamil','Tamil')
)
Cond = (
('New','New'),
('Old','old')
)
Title = models.CharField(max_length=400)
Author = models.CharField(max_length=100)
Price = models.DecimalField()
Category = models.CharField(choices=Cats)
Language = models.CharField(choices=Lang)
Condition = models.CharField(choices=Cond)
user = models.ForeignKey(User, on_delete=models.CASCADE)
Views.py of buy app
class sell(TemplateView):
template_name = 'buy/sell.html'
def get(self,request):
form = sellForm()
return render(request,self.template_name,{'form':form})
def post(self,request):
text = None
form = sellForm(request.POST)
if form.is_valid():
print("all good")
text = form.cleaned_data['Title']
form = sellForm()
args = {'form':form,'text':text}
return render(request,self.template_name,args)
Forms.py of accounts app
from django import forms
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserChangeForm
class EditProfileForm(UserChangeForm):
class Meta:
model = User
fields =(
'first_name',
'last_name',
'email',
'password'
)
class sellForm(forms.ModelForm):
Cats =(
('Course book','Course book'),
('Fiction','Fiction'),
)
Lang =(
('Hindi','Hindi'),
('English','English'),
('Tamil','Tamil')
)
Cond = (
('New','New'),
('Old','old')
)
Title = forms.CharField()
Author = forms.CharField()
Price = forms.DecimalField()
Category = forms.ChoiceField(required=False,choices=Cats)
Language = forms.ChoiceField(choices=Lang)
Condition = forms.ChoiceField(choices=Cond)
Description = forms.CharField()
class Meta:
model = Sell
fields = ('Title','Author','Price','Category','Language','Condition','Description')
Sell.html
<form method="POST">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Submit</button>
I didn't use Django UserCreateForm
I created it in this way in another app named accounts :
Views.py of accounts app
def register(request):
if request.method =='POST':
first_name = request.POST['first_name']
last_name= request.POST['last_name']
username= request.POST['username']
password1 = request.POST['password1']
password2 = request.POST['password2']
email = request.POST['email']
if password1 == password2:
if User.objects.filter(username=username).exists():
messages.info(request,'Username taken')
return redirect('register')
elif User.objects.filter(email=email).exists():
messages.info(request,'email exists')
return redirect('register')
else:
user = User.objects.create_user(username=username,password=password1,email=email,first_name=first_name,last_name=last_name)
user.save()
messages.info(request,'user created')
return redirect('login')
else:
messages.info(request,'password not matching')
return redirect('register')
return redirect('/')
else:
return render(request,'buy/register.html')
You just need to import the model
from django import forms
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserChangeForm
from .models import Sell
Related
I don't know why my form after submitting it always returns that the phone is required, i am stuck with this problem about one hour :(, i've seen lots of articles and questions that has been asked but without avail .
views.py:
def register(request):
if request.method == 'POST':
form = SignUpForm(request.POST or None)
if form.is_valid():
user = form.save(commit=False)
telephone = number_prettify(form.cleaned_data.get('telephone'))
user.phone = telephone
raw_password = form.cleaned_data.get('password1')
user.save()
user = authenticate(phone=user.phone, password=raw_password)
auth_login(request, user)
return redirect('/')
else:
form = SignUpForm()
return render(request, 'register.html', {'form': form})
here is my forms.py:
from django import forms
from django.contrib.auth import get_user_model
from django.contrib.auth.forms import UserCreationForm
# from .models import Client
User = get_user_model()
class SignUpForm(UserCreationForm):
telephone = forms.CharField(label='Номер телефона', help_text='Required. Inform a valid phone number.',
widget=forms.TextInput(attrs={'placeholder': '___-__-__-__','class':"uk-input phone_us"}))
password1 = forms.CharField(label='Пароль',widget=forms.PasswordInput())
password2 = forms.CharField(label='Повторите пароль',widget=forms.PasswordInput())
agree_1 = forms.BooleanField()
agree_2 = forms.BooleanField()
def clean(self):
if not self.cleaned_data['agree_1']:
raise forms.ValidateError('You have to agree to out privacy')
class Meta:
model = User
fields = ('phone',)
here is also the models.py:
class Client(AbstractBaseUser, PermissionsMixin):
email = models.EmailField(null=True, blank=True, unique=True)
phone = models.CharField(max_length=18,unique=True)
joined = models.DateTimeField(auto_now_add=True)
password = models.CharField(default='', null=False, max_length=255)
USERNAME_FIELD = 'phone'
class Meta:
db_table = 'client'
unique_together = ('phone',)
my register.html template:
<div class="uk-margin">
<label>
<div class="uk-margin-small-bottom">{{form.telephone.label}} <span>*</span></div>
{{form.telephone}}
</label>
</div>
<div class="uk-margin">
<label>
<div class="uk-margin-small-bottom">{{form.password1.label}} <span>*</span></div>
{{form.password1|add_class:"uk-input"}}
</label>
</div>
You should change the field from telephone to phone.
class SignUpForm(UserCreationForm):
phone = forms.CharField(label='Номер телефона', help_text='Required. Inform a valid phone number.',
widget=forms.TextInput(attrs={'placeholder': '___-__-__-__','class':"uk-input phone_us"}))
password1 = forms.CharField(label='Пароль',widget=forms.PasswordInput())
password2 = forms.CharField(label='Повторите пароль',widget=forms.PasswordInput())
agree_1 = forms.BooleanField()
agree_2 = forms.BooleanField()
def clean(self):
if not self.cleaned_data['agree_1']:
raise forms.ValidateError('You have to agree to out privacy')
class Meta:
model = User
fields = ('phone',)
ive been struggling with this particular part for days now, and other posts on this problem dont seem to help me out.
So I have connected the User model with my own Gebruiker model that has fields like city, postalcode etc. Now I have managed to show them up on the registerform, but they dont seem to work. My second question is about the order of the inputfields, every time they appear in a random order. How can I set up a steady order?
This is my forms.py
from django import forms
from django.contrib.auth.models import User
from .models import Gebruiker
from django.contrib.auth.forms import UserCreationForm
class RegistrationForm(UserCreationForm):
woonplaats = forms.CharField(required=True)
postcode = forms.CharField(required=True)
class Meta:
model = User
fields = {'username','email', 'password1', 'password2', 'first_name', 'last_name', 'woonplaats', 'postcode'}
def save(self, commit=True):
user = super(UserCreationForm, self).save(commit=False)
user.email = self.cleaned_data['email']
user.first_name = self.cleaned_data['first_name']
user.last_name = self.cleaned_data['last_name']
gebruiker = Gebruiker(user=user, woonplaats=self.cleaned_data['woonplaats'], postcode=self.cleaned_data['postcode'])
gebruiker.save()
if commit:
gebruiker.save()
user.save()
return user, gebruiker
(where woonplaats = place of residence)
Here is a part from views.py
def register(request):
if request.method == 'POST':
form = RegistrationForm(request.POST)
if form.is_valid():
form.save()
return redirect('/aanmelden')
else:
form = RegistrationForm()
args = {'form' : form}
return render(request, 'aanmelden/reg_form.html', args)
Models file:
from django.db import models
from django.contrib.auth.models import User
from django.dispatch import receiver
from django.db.models.signals import post_save
# Create your models here.
class Gebruiker(models.Model):
user = models.OneToOneField(User, null=True)
woonplaats = models.CharField(max_length=100)
postcode = models.CharField(max_length=100, default="")
email = models.CharField(max_length=100, default="")
#receiver(post_save, sender=User)
def create_user_profile(sender, instance, created, **kwargs):
if created:
Gebruiker.objects.create(user=instance)
#receiver(post_save, sender=User)
def save_user_profile(sender, instance, **kwargs):
instance.gebruiker.save()
Gebruiker part in User:
!(http://imgur.com/RKVCbc2)
You have to create object Gebruiker. So, instead of this line:
gebruiker = Gebruiker(user = user, woonplaats = self.cleaned_data['woonplaats'], postcode = self.cleaned_data['postcode'])
gebruiker.save()
change to this:
gebruiker = Gebruiker.objects.create(user = user, woonplaats = self.cleaned_data['woonplaats'], postcode = self.cleaned_data['postcode'])
gebruiker.save()
if Gebruiker created already, you have to get this object:
gebruiker = Gebruiker.objects.get(your_parameter)
gebruiker = Gebruiker(user = user, woonplaats = self.cleaned_data['woonplaats'], postcode = self.cleaned_data['postcode'])
gebruiker.save()
And the second answer, about ordering of the fields. As I understand your template looks something like that:
{{form}}
but you can access to the different fields using this code:
<form action="" method="post">
...
{{ form.woonplaats }}
{{ form.postcode }}
...
<input type="submit" alt="register" value="Order" />
</form>
In this case you can change the order as you want
UPDATE:
gebruiker = Gebruiker.objects.get(user = user)
gebruiker.woonplaats = self.cleaned_data['woonplaats'],
gebruiker.postcode = self.cleaned_data['postcode'])
gebruiker.save()
I am trying to understand how to expand the CreationForm library to utilize some custom fields I have in another model. Basically, in my model, I have a field called codeid and my goal is to have the user type in an integer and have that store into the database as they register. I know I'm somewhat on the right track, but there is some flawed logic behind my current code.
Forms.py
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
from .models import Address, Job
class MyRegistrationForm(UserCreationForm):
username = forms.CharField(required = True)
#udid = forms.CharField(required = True)
class Meta:
model = Address
fields = ('username', 'codeid', )
def save(self,commit = True):
user = super(MyRegistrationForm, self).save(commit = False)
user.codeid = self.cleaned_data['codeid']
if commit:
user.save()
return
Views.py
from django.shortcuts import render
from django.http import HttpResponseRedirect
from django.contrib import auth
from django.core.context_processors import csrf
from forms import MyRegistrationForm
def register_user(request):
if request.method == 'POST':
form = MyRegistrationForm(request.POST) # create form object
if form.is_valid():
form.save()
return HttpResponseRedirect('/')
args = {}
args.update(csrf(request))
args['form'] = MyRegistrationForm()
print args
return render(request, 'register.html', args)
Models.py
from django.db import models
from django.contrib.auth.models import User
class Address(models.Model):
user = models.ForeignKey(User)
street_address = models.CharField(max_length = 200)
city = models.CharField(max_length = 100)
state = models.CharField(max_length = 100)
zipcode = models.IntegerField(max_length = 5)
updated = models.DateTimeField(auto_now = True, auto_now_add = False)
timestamp = models.DateTimeField(auto_now = False, auto_now_add = True)
active = models.BooleanField(default = True)
codeid = models.IntegerField(max_length = 10, default = 0)
image = models.ImageField(upload_to='profiles/', default="")
def __str__(self,):
return 'test'
Registration HTML
{% extends 'home.html' %}
{%block content %}
<h2>Register</h2>
<form action='/register/' method = "post"> {% csrf_token %}
{{ form }}
<input type = "submit" value = "Register" />
</form>
{% endblock %}
Make change in forms.py :
return user
I am trying to assign the user value in my views.py from another form but I always seem to get the following error. Cannot assign "u'applematter'": "Student.user" must be a "User" instance.
how can I get the hidden field user to match what I am writing in another field.
views.py File
from django.shortcuts import render
from django.http import HttpResponse
from django.http import HttpResponseRedirect
from famu.forms import *
from django.contrib.auth.decorators import login_required
#login_required(login_url='')
def enroll(request):
if request.method == 'POST':
form = UserForm(request.POST,)
form2 = StudentCreate(request.POST)
if form.is_valid() and form2.is_valid():
new_user = form.save(commit=False)
new_student = form2.save(commit=False)
new_student.user = (new_user.username)
new_user.save()
new_student.save()
return HttpResponseRedirect('/')
else:
form = UserForm# An unbound form
form2 = StudentCreate
return render(request, 'famu/enroll.html', {
'form': form,
'form2': form2
})
forms.py
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User
from django import forms
from famu.models import Student
class UserForm(UserCreationForm):
class Meta:
model = User
fields = ('first_name', 'last_name', 'email','username',)
class StudentCreate(forms.ModelForm):
class Meta:
model = Student
exclude =['user',]
model.py
from django.db import models
from django.contrib.auth.models import User
class Student(models.Model):
CLASSIFICATION = (
('FR', 'Freshman'),
('SO', 'Sophomore'),
('JR', 'Junior'),
('SR', 'Senior'),
('GR', 'Graduate'),
)
TERMS = (
('F', 'Fall'),
('S', 'Spring'),
('Su', 'Summer'),
)
MAJOR = (
('CS', 'Computer Science'),
('CY', 'Computer Systems'),
('IT', 'Information Technology'),
)
user = models.ForeignKey(User)
student_id = models.IntegerField(primary_key=True, max_length=9)
classification = models.CharField(max_length=2, choices=CLASSIFICATION)
enrolled_year = models.IntegerField(max_length=4)
enrolled_term = models.CharField(max_length=2, choices=TERMS)
major = models.CharField(max_length=2, choices=MAJOR)
street_number = models.IntegerField(max_length=10)
street_name = models.CharField(max_length=45)
apt_number = models.CharField('apt #', max_length=10, blank=True, )
city = models.CharField(max_length=30)
state = models.CharField(max_length=2)
zipcode = models.IntegerField('Zip Code', max_length=5, )
last_modified = models.DateTimeField(auto_now=True)
You should first save new_user instance and then assign it in new student instance.
Relevant code
#login_required(login_url='')
def enroll(request):
if request.method == 'POST':
form = UserForm(request.POST,)
form2 = StudentCreate(request.POST)
if form.is_valid() and form2.is_valid():
new_user = form.save(commit=False)
new_user.save() #form.save() should also work rather than this 2 statements
new_student = form2.save(commit=False)
new_student.user = new_user #assign user instance, not username
new_student.save()
I am still experiencing some problems with understanding forms and relationships between model-forms.
I am getting an error:
UserProfile.location" must be a "Location" instance.
I've set location in models to blank=True, null=True and required=False in forms.py.
And I dont really know at this point what to do with that.
How I can fix that problem?
from django.db import models
from django.contrib.auth.models import User
class Location(models.Model):
location = models.CharField(max_length=32)
#county = models.CharField(max_length=32)
#province = models.CharField(max_length=32)
class UserProfile(models.Model):
user = models.OneToOneField(User, unique=True, primary_key=True)
location = models.ForeignKey("Location", null=True, blank=True)
website = models.URLField("Site", null=True, blank=True)
accepted_rules = models.BooleanField(default=False)
accepted_rules_date = models.DateTimeField(auto_now_add=True)
#points_count = models.IntegerField(default=0, null=True, blank=True)
#posts_count = models.IntegerField(default=0, null=True, blank=True)
#comments_count = models.IntegerField(default=0, null=True, blank=True)
Forms:
from django import forms
from django.forms import Form
from django.forms.models import ModelForm
from accounts.models import UserProfile, Location
from django.contrib.auth.models import User
class UserCreationForm(forms.Form):
username = forms.CharField(max_length=32)
password = forms.CharField(widget=forms.PasswordInput())
email = forms.EmailField()
#password_repeat = forms.CharField(widget=forms.PasswordInput(render_value=False))
def clean_username(self):
try:
# iexact = case-insensitive match / important for validation
User.objects.get(username__iexact=self.cleaned_data['username'])
print "User does already exist"
except User.DoesNotExist:
return self.cleaned_data['username']
else:
raise forms.ValidationError("User already exists")
def clean_email(self):
if User.objects.filter(email__iexact=self.cleaned_data['email']):
print u'Adres email jest już używany.'
raise forms.ValidationError('Adres email jest już używany.')
else:
return self.cleaned_data['email']
def save(self):
user = User.objects.create(username = self.cleaned_data['username'], email = self.cleaned_data['email'],)
user.set_password(self.cleaned_data['password'])
return user
class UserProfileForm(ModelForm):
website = forms.URLField(label="website", required=False)
location = forms.ChoiceField(required=False)
class Meta:
model = UserProfile
include = ['website', 'location']
exclude = ('user', 'type', 'accepted_rules')
Views
contrib.auth.models import User
from django.template.response import TemplateResponse
from django.views.decorators.csrf import csrf_protect
from django.core.context_processors import csrf
from django.forms.models import inlineformset_factory
from django.http import HttpResponseRedirect
from accounts.forms import UserCreationForm, UserProfileForm
def index(request):
return TemplateResponse(request, "base.html")
#csrf_protect
def register(request):
form = UserCreationForm()
user_profile = UserProfileForm()
if request.method == "POST":
form = UserCreationForm(prefix='user', data=request.POST or None)
user_profile = UserProfileForm(prefix='profile', data= request.POST or None)
if form.is_valid() and user_profile.is_valid():
user = form.save()
profile = user_profile.save(commit=False)
profile.user = user
profile.save()
return HttpResponseRedirect("/")
return TemplateResponse(request, 'accounts/register.html', {
'form':form,
'user_profile':user_profile ,
}
)
The problem is here.
class UserProfileForm(ModelForm):
website = forms.URLField(label="website", required=False)
location = forms.ChoiceField(required=False)
class Meta:
model = UserProfile
include = ['website', 'location']
exclude = ('user', 'type', 'accepted_rules')
ModelForm will generate needed fields for your form. You don't need to define them manually. So you should use something like this.
class UserProfileForm(ModelForm):
class Meta:
model = UserProfile
include = ['website', 'location']
exclude = ('user', 'type', 'accepted_rules')
Another thing. There is no include option, I think you wanted to use fields. But you don't have to use both fields and exclude, usually you need to use one them. In your case exclude is enough. Final result:
class UserProfileForm(ModelForm):
class Meta:
model = UserProfile
exclude = ('user', 'type', 'accepted_rules')