When logging in, create a profile, But when logging out and then logging in with that same username, It again says to me to create a profile and creates two profiles instead of one.
#For Cystomer Registration
class CustomerRegistrationView(View):
def get(self,request):
form = CustomerRegistrationForm()
return render(request,'mp/register.html',{'form':form})
def post(self,request):
form = CustomerRegistrationForm(request.POST)
if form.is_valid():
messages.success(request,'Congratulations Registerd Succesfuly ')
form.save()
success_url = reverse_lazy('profilecreate')
return render(request,'mp/register.html',{'form':form})
#For Creating Profile
class ProfileCreate(LoginRequiredMixin,CreateView):#ye hogia hamara upload wala
model = Profile
fields =
['user_name','user_ethnicity','SelectGender','user_job','user_age','mother_additionalinfo']
success_url = reverse_lazy('profile')
def form_valid(self,form):
form.instance.user = self.request.user
success_url = reverse_lazy('profile')
return super(ProfileCreate,self).form_valid(form)
here are my URLs
#for register
path('register/',views.CustomerRegistrationView.as_view(),name= 'register'),
#for CreateProfile
path('profilecreate/',views.ProfileCreate.as_view(),name= 'profilecreate'),
when User Created and I remove the loginrequiredmixin from profilecreateview. It give me an error of Page No Found With This Url:127.0.0.1:8000/accounts/login/?next=/profilecreate. It does not go to Profile Create View because it is not logged in but just Registered. And I want the User Go to Profilecreateview only one time. Later he can Update it. –
Related
Views.py
#For Cystomer Registration
class CustomerRegistrationView(View):
def get(self,request):
form = CustomerRegistrationForm()
return render(request,'mp/register.html',{'form':form})
def post(self,request):
form = CustomerRegistrationForm(request.POST)
if form.is_valid():
messages.success(request,'Congratulations Registerd Succesfuly ')
form.save()
success_url = reverse_lazy('profile')
return render(request,'mp/register.html',{'form':form})
#For Creating Profile
class ProfileCreate(LoginRequiredMixin,CreateView):#ye hogia hamara upload wala
model = Profile
fields = ['user_name','user_ethnicity','SelectGender','user_job','user_age','mother_additionalinfo']
success_url = reverse_lazy('profile')
def form_valid(self,form):
form.instance.user = self.request.user
success_url = reverse_lazy('profilecreate')
return super(ProfileCreate,self).form_valid(form)
Urls.py
#for register
path('register/',views.CustomerRegistrationView.as_view(),name= 'register'),
#for CreateProfile
path('profilecreate/',views.ProfileCreate.as_view(),name= 'profilecreate'),
Also the Important thing is that when i have not setup the Logout Function then it working,But when i steup,Then this not redirect user to another page and stay at Registration Page.
You can use redirect instead, so that will be something like the below
return redirect("profilecreate")
Also another that i noticed is that your ProfileCreate doesnt to be a View i cant see any post or get function, if this will be a page you should add a function, in your case a post function.
I have the following CreateView where I am trying to Mstrstorehead-contactemail with the email address of the person who has logged in.
The problem is that contactemail is not listed as one of the fields to be displayed on the CreateView form (which is MstrstoreheadCreate)
How can I get this field assigned?
views.py
class MstrstoreheadCreate(CreateView):
model = Mstrstorehead
fields = ['companyname',
'taxeinno', 'companyname', 'abanumber', 'businesstypeid', 'ourmission', 'contactsalutationid',
'contactfirstname', 'contactlastname', 'contactofficephoneno', 'contactcellphoneno' ]
template_name_suffix = '_mstr_create_form'
def form_valid(self, form):
mhead = form.save(commit=False)
mhead.contactemail = self.request.user.email << contactemail is part of the model but NOT part of the fields used in CreateView
return super(MstrstoreheadCreate, self).form_valid(form)
TIA
Go to your view (the one you handle the form) and add that over there... something like this:
def MyView(request):
mhead = MstrstoreheadCreate()
if request.method == "POST":
mhead = MstrstoreheadCreate(request.POST)
if mhead.is_valid():
mhead.contactemail = self.request.user.email
mhead.save()
I am a little confused with where validation of form/model fields can happen in generic CreateView/UpdateView. Consider my hypothetical model below. I want the field secret to be hashed using my custom hashfunction and saved and assume some validation for secret field is done(NOT shown in the example below). My options to do this are:
1) in the model save method (I have not shown this below)
2) in the form's save method (I have shown below)
3) in the form_valid method of AccountCreateView (I have shown below)
4) how can I access the cleaned_data in the generic views (cleaned_data is available
only after form_valid is called)
Which is the right way to do it, both pros and cons. I will use the same form for updateView, in which case I will unhash the secret before displaying its data on the form. where this should happen?
My model:
class Account(models.Model):
user = models.ForeignKey(User)
created = models.DateField(auto_now=True)
secret = models.IntegerField()
My form:
AccountCreateForm(forms.ModelForm):
secret = forms.CharField(max_length=100)
class Meta:
model = MediaContent
exclude = (secret,user,created)
def save(self, user, debate):
obj = super(AccountCreateView, self).save(commit=False)
obj.user = self.cleaned_data['user']
obj.secret = myHashfunction(self.cleaned_data['secret'])
obj.save()
My view:
class AccountCreateView(CreateView):
"""
displays form to create a new search
"""
model = Account
form_class = AccountCreateForm
success_url = reverse_lazy('home')
template_name = 'app/account_form.html'
def form_valid(self, form):
f = form.save(commit=False)
secret=myHashfunction(self.request.POST['secret'])
f.user = self.request.user
f.save()
return super(AccountCreateView,self).form_valid(form)
EDIT:
please see the edit to my model and form. the field I use in form is not the field in model.
It is a new Field, that takes CharField but the model saves as IntegerField. my hashfunciton will convert the charField to IntegerField.
I think in this case Form is the better than ModelForm, as excluding every field on your model makes it redundant. You should then do any additional validation for the un-hashed secret here with clean_secret.
AccountCreateForm(forms.Form):
secret=forms.CharField(max_length=100)
Now, if you are not using the ModelForm anymore, I would suggest using FormView over CreateView as the generic CreateView has become less of a good fit.
class AccountCreateView(FormView):
"""
displays form to create a new search
"""
form_class = AccountCreateForm
success_url = reverse_lazy('home')
template_name = 'app/account_form.html'
def form_valid(self, form):
unhashed_secret = form.cleaned_data['secret']
hashed_secret = myHashfunction(unhashed_secret)
user = self.request.user
# Probably put some extra logic here to check if the user already exists
Account.objects.create(
user=user,
secret=hashed_secret,
)
return super(AccountCreateView,self).form_valid(form)
None of the above. The correct place to do this is in the clean_secret method of the form. That is the place for any field-related validation and conversion. Simply return the hashed value from that method.
Whenever I try try to update a userprofile on django powered web, I get the error: "username already exists, please provide another one." I am trying to get it to recognize the authenticated user. Although every other thing works, it will not update until I specify a new username.
views.py
#login_required
def editprofile(request):
registeredmember = request.user.get_profile()
if request.method == 'POST':
userprofile_edit = RegistrationForm(request.POST, instance = registeredmember)
if userprofile_edit.is_valid():
userprofile_edit.save()
return HttpResponseRedirect('/profile/')
else:
userprofile_edit = RegistrationForm(instance = registeredmember)
return render_to_response('carloan/editprofile.html', {'userprofile_edit': userprofile_edit}, context_instance=RequestContext(request))
You have to exclude the username field when you are Editing the profile.
Something like this in your RegistrationForm.
class RegistrationForm(forms.form):
#other code
class Meta:
exclude = ['username',]
You can add multiple field names which you don't want to be included in the form
I'm currently working on an application for user registration on a Django CMS site.
My registration form is working just fine and creates the user, plus adds my custom fields to my registration model.
What I'd like to know is how to update auth_user to contain the user's first and last name.
Currently the user is being created in this manner:
import newform
from betaregistration.newform import RegistrationFormZ
def user_created(sender, user, request, **kwargs):
form = RegistrationFormZ(request.POST)
data = newform.BetaProfile(user=user)
data.first_name = form.data["first_name"]
data.last_name = form.data["last_name"]
data.address = form.data["address"]
data.city = form.data["city"]
data.state = form.data["state"]
data.postal_code = form.data["postal_code"]
data.country = form.data["country"]
data.phone= form.data["phone"]
data.email = form.data["email"]
data.save()
# this was the solution
user.first_name = form_data['first_name']
user.last_name = form_data['last_name']
user.save()
# end solution
from registration.signals import user_registered
user_registered.connect(user_created)
Any help is appreciated. I'm using django-registration for my registration.
Since you are passing user into user_created could you simply modify things as the following:
data.first_name = user.first_name = form.data["first_name"]
data.last_name = user.last_name = form.data["last_name"]
....
user.save()
I may be missing something but if you really do have access to user in user_created that should work. You could also potentially do the same using request.user instead of user.