Hi all, i am really fed up and have tried number of way. Please read
my last line which really describe where i am facing problem.
First Attempt.
models.py
-------------
class UserProfile(models.Model):
user = models.ForeignKey(User, unique=True, verbose_name=_
('user'))
gender = models.CharField(_('gender'), max_length=1,
choices=GENDER_CHOICES, blank=True)
dob = models.DateField(_('dob'), max_length=10, help_text=_
("Should be in date format"), null=True, blank=True)
city = models.CharField(_('res_city'), max_length=30,
choices=CITY_CHOICES, blank=True)
class RegistrationForm(forms.Form):
"""The basic account registration form."""
title = forms.CharField(max_length=30, label=_('Title'),
required=False)
email = forms.EmailField(label=_('Email address'),
max_length=75, required=True)
password2 = forms.CharField(label=_('Password (again)'),
max_length=30, widget=forms.PasswordInput(), required=True)
password1 = forms.CharField(label=_('Password'),
max_length=30, widget=forms.PasswordInput(), required=True)
first_name = forms.CharField(label=_('First name'),
max_length=30, required=True)
last_name = forms.CharField(label=_('Last name'),
max_length=30, required=True)
#gender = forms.CharField(label = _('Gender'), widget =
forms.Select(choices=GENDER_CHOICES,attrs=attrs_dict))
#dob = forms.DateTimeField(widget=forms.DateTimeInput(attrs=dict
(attrs_dict, max_length=75)), label=_(u'date of birth'))
#city = forms.CharField(label = _('res_city'), widget =
forms.Select(choices=CITY_CHOICES,attrs=attrs_dict))
def __init__(self, *args, **kwargs):
self.contact = None
super(RegistrationForm, self).__init__(*args, **kwargs)
newsletter = forms.BooleanField(label=_('Newsletter'),
widget=forms.CheckboxInput(), required=False)
def clean_password1(self):
"""Enforce that password and password2 are the same."""
p1 = self.cleaned_data.get('password1')
p2 = self.cleaned_data.get('password2')
if not (p1 and p2 and p1 == p2):
raise forms.ValidationError(
ugettext("The two passwords do not match."))
# note, here is where we'd put some kind of custom
# validator to enforce "hard" passwords.
return p1
def clean_email(self):
"""Prevent account hijacking by disallowing duplicate
emails."""
email = self.cleaned_data.get('email', None)
if email and User.objects.filter(email=email).count() > 0:
raise forms.ValidationError(
ugettext("That email address is already in use."))
return email
def save(self, request=None, **kwargs):
"""Create the contact and user described on the form. Returns
the
`contact`.
"""
if self.contact:
log.debug('skipping save, already done')
else:
self.save_contact(request)
return self.contact
def save_contact(self, request):
print " i am in save_contact "
log.debug("Saving contact")
data = self.cleaned_data
password = data['password1']
email = data['email']
first_name = data['first_name']
last_name = data['last_name']
username = data['title']
#dob = data['dob']
#gender = data['gender']
#city = data['city']
verify = (config_value('SHOP', 'ACCOUNT_VERIFICATION') ==
'EMAIL')
if verify:
from registration.models import RegistrationProfile
user = RegistrationProfile.objects.create_inactive_user(
username, password, email, send_email=True)
else:
user = User.objects.create_user(username, email, password)
user.first_name = first_name
user.last_name = last_name
user.save()
# If the user already has a contact, retrieve it.
# Otherwise, create a new one.
try:
contact = Contact.objects.from_request(request,
create=False)
#profile = UserProfile.objects.form_request(request,
create=False)
except Contact.DoesNotExist:
contact = Contact()
contact.user = user
contact.first_name = first_name
contact.last_name = last_name
contact.email = email
contact.role = 'Customer'
contact.title = data.get('title', '')
contact.save()
if 'newsletter' not in data:
subscribed = False
else:
subscribed = data['newsletter']
signals.satchmo_registration.send(self, contact=contact,
subscribed=subscribed, data=data)
def save_profile(self, request):
user_obj = User.objects.get(pk=request.user.id)
#user_obj.first_name = self.cleaned_data['first_name']
#user_obj.last_name = self.cleaned_data['last_name']
try:
profile_obj = request.user.get_profile()
except ObjectDoesNotExist:
profile_obj = UserProfile()
profile_obj.user = user
profile_obj.dob = self.cleaned_data['dob']
profile_obj.gender = self.cleaned_data['gender']
profile_obj.city = self.cleaned_data['city']
profile_obj.mobile = self.cleaned_data['mobile']
profile_obj.save()
return profile_obj
#user_obj.save()
regview.py
------------
def register_handle_form(request, redirect=None):
"""
Handle all registration logic.This is broken out from "register"
to allow easy overriding/hooks such as a combined login/register
page.
This method only presents a typical login or register form, not a
full address form (see register_handle_address_form for that one.)
Returns:
- Success flag
- HTTPResponseRedirect (success) or form (fail)
"""
print "I am in handle form"
form_class = utils.get_profile_form()
if request.method == 'POST':
print "i am in profile post"
profileform = form_class(data=request.POST,
files=request.FILES)
form = RegistrationForm(request.POST)
print "Form errror :", form.errors, profileform.errors //for
this no error is coming so both form valid
if form.is_valid():
contact = form.save(request)
data= profileform.cleaned_data
user = form.data['title']
gender = data['gender']
dob = data['dob']
city = data['city']
profile_obj = profileform.save(commit=False)
profile_obj.user = request.user
profile_obj.save()
if not redirect:
redirect = urlresolvers.reverse
('registration_complete')
return (True, http.HttpResponseRedirect
(urlresolvers.reverse('registration_complete')))
#return HttpResponseRedirect(reverse
('registration_complete'))
else:
initial_data = {}
try:
contact = Contact.objects.from_request(request,
create=False)
initial_data = {
'email': contact.email,
'first_name': contact.first_name,
'last_name': contact.last_name }
except Contact.DoesNotExist:
log.debug("No contact in request")
contact = None
signals.satchmo_registration_initialdata.send(contact,
contact=contact,
initial_data=initial_data)
form = RegistrationForm(initial=initial_data)
profileform = form_class(data=request.POST,
files=request.FILES)
return (False, form, profileform)
Problem:Data is saving for register and contact but for profile i get
error
ValueError
Exception Value:
Cannot assign "<django.contrib.auth.models.AnonymousUser object at
0x916b0cc>": "UserProfile.user" must be a "User" instance.
Please look in to regview.py this line
I am trying to get the user = form.data['title'] which is currently
created and with that user the profile would saved.
I will be very thankful for your suggestion
--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups
"Django users" group.
To post to this group, send email to [email protected]
To unsubscribe from this group, send email to
[email protected]
For more options, visit this group at
http://groups.google.com/group/django-users?hl=en
-~----------~----~----~----~------~----~------~--~---