Django - Update User/Account Management - python

I am trying to update my user account info through a form. I have the form ok which just displays a password/email field and cleans the email field. I am having a problem with my views. This is the error I get: Manager isn't accessible via User instances.
This is my views: my_account function.
def my_account(request):
user = request.user
if request.method == 'POST':
form = MyAccountForm(request.POST)
if form.is_valid():
user = user.objects.get(username=username),
password = user.set_password('password2'),
email = forms.cleaned_data['email']
user.save()
return HttpResponseRedirect('/')
else:
form = MyAccountForm()
variables = RequestContext(request, {
'form': form,
})
return render_to_response(
'my_account.html',
variables
)

where you have
user.objects.get
you want
User.objects.get
objects is the manager referred to in the error message, and user is the instance referred to (an instance of User, the actual class)

Related

How I can escape from using sessions in Django?

What I'm trying to do?
I want to display 2 registration forms separately of each other on the same page. The forms are: built-in User model and my self created UserProfile. To track, on what form user is now, I use sessions. It some sort of flags for me at the moment.
Why I don't want to use sessions?
I discovered a 'bug', at least for me, that I don't know how to fix. Bug appears if user passed first registration form, and close browser/tab. Next time user opens registration page, it will show second registration form, instead of first, as expected.
Where bug happens, but now with code.
When user opens register page first time, built-in UserCreationForm will be show, because there is no session called username yet.
def get(self, request):
if request.session.get("username", None):
self.context["form"] = RegisterProfile()
else:
self.context["form"] = UserCreationForm()
I'm using CBV, so it's OK that function called get and first argument is self. Also I created context dictionary as instance variable, so I can just add new field form to it.
Next, if user fill in given form (note, that first form is built-in User's form) built-in User instance will be created and it's username will be stored in username session.
If you confused at the moment don't worry much, I leave full view code at the bottom.
form = UserCreationForm(request.POST)
if form.is_valid():
form.save()
request.session["username"] = request.POST["username"]
return redirect("register")
Now, when session username exsists, and user redirected to same view, my self-created form will be shown. As in first code example.
Now, bug happens. User can freely leave page, and when he come back, second registration form will be shown again. That's not what I want.
Full view code:
class Register(View):
context = {"title": "Register new account"}
def get(self, request):
if request.session.get("username", None):
self.context["form"] = RegisterProfile()
else:
self.context["form"] = UserCreationForm()
return render(request, "users/register.html", context=self.context)
def post(self, request):
if request.session.get("username", None):
form = RegisterProfile(request.POST, request.FILES)
if form.is_valid():
username = request.session.get("username", None)
if not username:
messages.error(request, "We are sorry, but error happend. Try again!")
return redirect("index")
user = User.objects.filter(username=username).first()
profile = UserProfile(
user=user,
nickname=request.POST["nickname"],
sex=request.POST["sex"],
age=request.POST["age"],
profile_picture=form.files["profile_picture"],
)
profile.save()
del request.session["username"]
messages.success(request, "Profile created successfully!")
return redirect("index")
else:
form = UserCreationForm(request.POST)
if form.is_valid():
form.save()
request.session["username"] = request.POST["username"]
return redirect("register")
self.context["form"] = form
return render(request, "users/register.html", context=self.context)
UPD 1:
I changed register logic a little, now full code looks like this:
class Register(View):
context = {"title": "Register user page"}
def get(self, request):
if request.session.get("user_data", None):
form = ProfileRegisterForm()
else:
form = UserCreationForm()
self.context["form"] = form
return render(request, "users/register.html", context=self.context)
def post(self, request):
if request.session.get("user_data", None):
form = ProfileRegisterForm(request.POST, request.FILES)
if form.is_valid():
user = User.objects.create_user(*request.session["user_data"])
user.save()
UserProfile.objects.create(
user=user,
nickname=request.POST["nickname"],
sex=request.POST["sex"],
age=request.POST["age"],
profile_picture=form.files["profile_picture"],
)
del request.session["user_data"]
messages.success(request, "Profile created successfully!")
return redirect("index")
else:
form = UserCreationForm(request.POST)
if form.is_valid():
request.session["user_data"] = [
request.POST["username"],
request.POST["password1"],
request.POST["password2"]
]
return redirect("register")
self.context["form"] = form
return redirect("register")
But anyway, I need place to store temporary data like username, password1 and password2. If someone knows, where I can store data like in sessions, please, answer bellow.

Allow users to create an "appointment" using a django form

I am trying to male a django webapp; the app has several forms that are submitted by users and I was wondering if there was a way to tell which user submitted the form so that I could bind the form input to that particular user. The form is for an "appointment" as if the patient that were logged in is making an appointment to go see their doctor.
Model:
class Appointment(models.Model):
user = models.OneToOneField(User)
schedule = models.ForeignKey(Schedule)
doctorName = models.CharField(max_length=50)
date = models.DateTimeField(auto_now_add=True)
Form:
class CreateAppointment(forms.ModelForm):
class Meta:
model = Appointment
fields = ("doctorName", "date")
View:
def create_appointment(request):
if request.POST:
form = CreateAppointmentForm(request.POST, instance=request.user.profile)
if form.is_valid():
form.save()
return render_to_response('index.html', context_instance=RequestContext(request))
else:
form = CreateAppointmentForm()
args = {}
args.update(csrf(request))
args['form'] = form
return render_to_response('create_appointment.html', args, context_instance=RequestContext(request))
If the user is logged in then you can simply use this:
user=request.user
In your views.py. It will return AnonymousUser if the user is not logged in, so first make sure the user is authenticated.
if request.user.is_authenticated ():
#Do stuff
You are using instance improperly, it's for when you want to update a specific row in the database. You need to create the form without the user field (adding exclude=['user',] to the meta of the form f.ex.) then change the contents of the if request.method="POST" a bit:
form_obj = CreateAppointmentForm(request.POST).save(commit=False)
form_obj.user = request.user
form_obj.save()

django auth framework prepopulating form incorrectly, giving random data to fields upon load

I am trying to create a portable auth system that can be plugged in apps, and each different app I reimplement it in has the same issues.
1-Sometimes the user that recently logged in gets their sn in the email address field when a new user tries to register, as below
2- Sometimes a new user registers and logs out but the form will put the old user's email address and password in the appropriate fields, when of course I want the form to be blank if the user has logged out
3- always the last password used is filled in upon reload
I just want the form to completely clear itself when reloaded
How to clear form fields after a submit in Django
I have tried all 3 solutions from a similar question, I reinstantiated the from after saving the valid one, made a copy of request.POST and used that instead, and I was already redirecting to begin with. Here is my form
from django.contrib.auth.models import User
class UserForm(forms.ModelForm):
password = forms.CharField(widget=forms.PasswordInput())
class Meta:
model = User
fields = ('username', 'email', 'password')
in views.py
def register(request):
context = RequestContext(request)
registered = False
user_form = UserForm()
if request.method == 'POST':
pDict = request.POST.copy()
form = UserForm(pDict)
if form.is_valid():
user = form.save()
user.set_password(user.password)
user.save()
user_form = UserForm()
registered = True
username = pDict['username']
password = pDict['password']
user = authenticate(username=username, password=password)
login(request, user)
#locals isn't working? won't print user
return HttpResponseRedirect('/url/')
else:
print user_form.errors
template_name = 'accounts/register.html'
user_form = UserForm()
response = TemplateResponse(request, 'accounts/register.html', locals())
return response
thank you

How to combine 2 forms for use on the same page?

I have a UserProfile model to add extra metadata around the standard Django User model. I am creating a registration page, and I want the user to input both the basic user information captured in the User model as well as the general profile information captured in the UserProfile model.
How can we capture and validate both of these models in one request in Django, presumably through forms?
There is valid debate about whether to keep the User and UserProfile separated. If you want to use separate classes:
#csrf_protect
def register(request, extra_context=None):
if request.method == 'POST':
user_form = AddUserForm(data=request.POST, files=request.FILES)
user_profile_form = AddUserProfileForm(data=request.POST, files=request.FILES)
if user_form.is_valid() and user_profile_form.is_valid():
new_user = user_form.save(request.get_host())
new_user_profile = user_profile_form.save(request.get_host(), new_user)
return HttpResponseRedirect(reverse('registration_complete'))
else:
user_form = AddUserForm()
user_profile_form = AddUserProfileForm()
context = {}
return render_to_response('registration_form.html',
{ 'user_form': user_form,
'user_profile_form': user_profile_form },
context_instance=context)

Django - User creation with custom user model results in internal error

Ok, I know this is a silly question but I am blocked and I can't figure out what to do.
I have searched on google and stackoverflow but did not found any answer :
I tried this :
Adding custom fields to users in django
Django - Create user profile on user creation
https://docs.djangoproject.com/en/dev/topics/auth/#storing-additional-information-about-users
My model is the following :
class UserProfile(models.Model):
user = models.OneToOneField(User)
quota = models.IntegerField(null = True)
def create_user_profile(sender, instance, created, **kwargs):
if created:
UserProfile.objects.create(user=instance)
post_save.connect(create_user_profile, sender=User)
And my view for user registration is the following :
def register(request):
if request.method == 'POST': # If the form has been submitted...
form = RegistrationForm(request.POST) # A form bound to the POST data
if form.is_valid(): # All validation rules pass
# Process the data in form.cleaned_data
cd = form.cleaned_data
#Then we create the user
user = User.objects.create_user(cd['username'],cd["email"],cd["password1"])
user.get_profil().quota = 20
user.save()
return HttpResponseRedirect('')
else:
form = RegistrationForm() # An unbound form
return render(request, 'registration_form.html', {'form': form,})
The line that launches an InternalError is :
user = User.objects.create_user(cd['username'],cd["email"],cd["password1"])
And the error is :
InternalError at /register/
current transaction is aborted, commands ignored until end of transaction block
Thank you for your help
user = User.objects.create_user(username=form.cleaned_data['username'],
password=form.cleaned_data['password'],
email=form.cleaned_data['email'])
user.is_active = True
user.save()

Categories

Resources