I have a model named profile and it has a one to one relationship with the User model. profile contains unnecessary information about the user like bio, gender, country, etc. So when the user signs up, they won't have a profile yet. When the user goes into settings and starts entering details, then they will have a profile.
That being said, how do I create a view in Django that can both create profile details about the user or update existing information.
Form
class ProfileForm(ModelForm):
class Meta:
model = Profile
fields = ['avatar', 'bio', 'gender', 'dob', 'country']
View
class SettingsView(FormView):
template_name = 'oauth/settings.html'
form_class = ProfileForm
success_url = reverse_lazy('oauth:settings')
redirect_field_name = "next"
Try this:
from django.views import View
from .forms import ProfileForm
from .models import Profile
class Settings(View):
form_class = ProfileForm
template_name = 'oauth/settings.html'
def post(self, request):
form = self.form_class(request.POST)
data = {'error':''}
if form.is_valid():
user = request.user
bio = form.cleaned_data['bio']
# more fields here
try:
profile = user.profile
# update user profile
profile.bio = bio
# add more fields here
profile.save()
data['response'] = 'profile updated!'
except:
profile = Profile(user=user,bio=bio) #add more fields
profile.save()
data['response'] = 'profile created!'
else:
data['error'] = 'Invalid form!'
return render(request, self.template_name,{'data':data})
Edit:
Or we can use update_or_create() as suggested by the OP in comments.
By replacing try and except blocks with:
updated_values = {'bio':bio} # add more fields
obj, created = Profile.objects.update_or_create(user=user,bio=bio, defaults=updated_values) # add more fields
if created:
data['response'] = 'profile created!'
else:
data['response'] = 'profile updated!'
Related
I want to create a PostModel(just like instagram) and while the form is created to connect the user to the model with One-to-one/foreign key relationship, anyway I'm getting a problem while trying to upload an image and the db doesn't updates.
I've tried this solution
...
# models.py
from django.contrib.auth.models import User
from django.conf import settings
class Post(models.Model):
owner = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
description = models.CharField(max_length=255, blank=True)
image = models.ImageField(upload_to='images')
uploaded_at = models.DateTimeField(auto_now_add=True)
...
# forms.py
class PostForm(forms.ModelForm):
class Meta:
model = Post
fields = ('description', 'image', )
def save(self, commit=True):
if commit:
Post.save()
return Post
...
# views.py
def account(request):
post = PostForm(request.POST, request.FILES)
if request.method == "POST":
if post.is_valid():
post.save(commit=False)
post.owner = request.user
post.save(commit=True)
messages.success(request, f"you had successfully updated your profile image")
return redirect("main:account")
else:
for msg in form.error_messages:
messages.error(request, f"{msg}: {form.error_messages[msg]}")
return render(request = request,
template_name = "main/account.html",
context={'PostForm':post})
post = PostForm()
return render(request = request,
template_name = "main/account.html",
context={'PostForm':post})
You should not override the def save() method, this is fine as it is now, so:
class PostForm(forms.ModelForm):
class Meta:
model = Post
fields = ('description', 'image', )
# no save
as for the view, you need to add the owner to the object, but here you are adding it to the form, and that thus has no effect (on the object):
from django.contrib.auth.decorators import login_required
#login_required
def account(request):
post = PostForm(request.POST, request.FILES)
if request.method == 'POST':
if post.is_valid():
post.instance.owner = request.user
post.save()
messages.success(request, f'you had successfully updated your profile image')
return redirect('main:account')
# …
I would also advise to rename post to post_form, since this is a form, not a post object.
Note: You can limit views to a view to authenticated users with the
#login_required decorator [Django-doc].
what I am trying to accomplish is to send the "requester" model, using the logged-in user to a form ...
Mainly the problem that I have is that the views.py "class CreateOrderView(CreateView)" does not have a parameter "request" , so I cannot get the request.user, and therefore get requester_obj and automatically select this requester_obj in the form field "requester", when entering this page.
models.py Order:
DEFAULT_REQUESTER_ID= 1
requester = models.ForeignKey(Profile, on_delete=models.CASCADE, default=DEFAULT_REQUESTER_ID, verbose_name="usuario")
forms.py:
class OrderCreateForm(BaseForm, forms.ModelForm):
date = forms.DateField(label="Fecha" , widget=forms.DateInput(attrs={'type': 'date'}))
class Meta:
model = Order
fields = ['requester','title' , 'date', ]
views.py:
#method_decorator(staff_member_required, name='dispatch')
class CreateOrderView(CreateView):
template_name = 'form.html'
form_class = OrderCreateForm
model = Order
def get_success_url(self):
self.new_object.refresh_from_db()
return reverse('update_order', kwargs={'pk': self.new_object.id})
def form_valid(self, form):
object = form.save()
object.refresh_from_db()
self.new_object = object
return super().form_valid(form)
I get the requester like this:
#login_required
def create(request):
#return render(request, 'app_client/create.html')
if request.method == 'POST':
if request.POST['value'] and request.POST['products']:
logged_user = request.user
user_obj = get_object_or_404(User, username=logged_user)
requestor_obj = get_object_or_404(Profile, user=user_obj)
....
I just found a solution for my issue...
What I did was to remove the "requester" field in forms.py, and send the requester obj to the form after user presses the submit form button
def form_valid(self, form):
logged_user = self.request.user
user_obj = get_object_or_404(User, username=logged_user)
requester_obj = get_object_or_404(Profile, user=user_obj)
form.instance.requestor = requestor_obj
object = form.save()
object.refresh_from_db()
self.new_object = object
return super().form_valid(form)
form.instance.requestor = requestor_obj was the line that I needed to send it to form before saving it.
ref: Django CreateView Foreign key
I want to create a Registration form which includes two models. One model is my custom model (Profile) and the other is the default User model in Django. I created two separate forms within the same template but the data is not successfully stored. This is what I had done so far:
models.py:
from django.db import models
from django.contrib.auth.models import User
class Profile(models.Model):
user = models.OneToOneField(User, on_delete = models.CASCADE)
company = models.CharField(max_length=100, blank=True, null=True)
address = models.TextField()
views.py:
def register(request):
if request.method == 'POST':
user_form = UserForm(request.POST)
profile_form = ProfileForm(request.POST)
if user_form.is_valid() and profile_form.is_valid():
user_form.save()
profile_form.save()
return redirect('login')
else:
user_form = UserForm()
profile_form = ProfileForm()
return render(request, 'register_page.html', {'user_form': user_form, 'profile_form': profile_form})
forms.py:
from django import forms
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm
from .models import Profile
class UserForm(UserCreationForm):
email = forms.EmailField()
class Meta:
model = User
fields = ['username', 'email', 'password1', 'password2']
class ProfileForm(forms.ModelForm):
class Meta:
model = Profile
fields = ['company', 'address']
However, when I tried to register a new user, the data gets saved in the User model (username, email, password) but not in the Profile model (company, address).
I am getting this error instead:
RelatedObjectDoesNotExist at /
Profile has no user.
What should I do?
Since your Profile model is connected to the User model through OneToOne relation so you need to assign the user to your profile like this.:
if user_form.is_valid() and profile_form.is_valid():
user = user_form.save()
profile = profile_form.save(commit = False)
# assign user to your profile
profile.user = user
profile.save()
return redirect('login')
I am new in Django and I really need help,
I do not know how to save my form data to database. I have problem to views.py
I will user's id who filled the form added into the foreign key field.
If there is any link or example that help me I appreciate you.
# views.py
#login_required(login_url="home")
def melk_new(request):
form = MelkForm()
???
return render(request, 'melk_new.html',{'form': form})
# models.py
class Melk(models.Model):
category = models.CharField(max_length=50)
city = models.CharField(max_length=100)
person = models.ForeignKey('CustomUser', on\_delete=models.CASCADE)
def \_\_str\_\_(self):
return self.category
class CustomUser(AbstractUser):
def __str__(self):
return self.email
---------------------------------------------------------------------------
# forms.py
class MelkForm(forms.ModelForm):
class Meta:
model = Melk
fields = ('category', 'city')
class CustomUserCreationForm(UserCreationForm):
class Meta(UserCreationForm):
model = CustomUser
fields = ('username', 'email')
To get the currently logged in user you'll find it within request.user object. but before you assume that there is a currently logged in user, you need to validate that so you have 2 widely known options:
request.user.is_authenticated()
#login_required() decorator used if you from django.contrib.auth.decorators import login_required
if request.user.is_authenticated():
Car.objects.create(model_id=some_id, person=request.user)
Note:
The #login_required() is added above the function
#login_required(login_url="home")
def melk_new(request):
form = MelkForm(request.POST)
if form.is_valid():
instance = form.save(commit=False)
instance.user_id = request.user.id
instance.save()
return render(request,'melk_new.html', { 'form': form})
I have an account app in which I have created a Profile model by extending the custom user model. I have created a view which allows the user to edit his profile info and also I have corresponding UserEditForm and ProfileEditForm. As of now, no user has a profile so when I open the edit form I get an error: "RelatedObjectDoesNotExist at /account/edit/".
" User has no profile "
I tried to create the profile using admin , then the error goes away. How can I correct this in my views.py file.
views.py
#login_required
def edit(request):
if request.method =='POST':
user_form = UserEditForm(instance=request.user,data=request.POST)
profile_form = ProfileEditForm(instance=request.user.profile,data=request.POST,files=request.FILES)
if user_form.is_valid() and profile_form.is_valid():
user_form.save()
profile_form.save()
messages.success(request,'Profile updated successfully')
else:
messages.error(request,'Error updating your profile')
else:
user_form = UserEditForm(instance=request.user)
profile_form = ProfileEditForm(instance=request.user.profile)
context = {
'user_form':user_form,
'profile_form': profile_form
}
return render(request,'account/edit.html',context)
models.py
CATEGORY_CHOICES = (
('SA','School Admin'),
('T','Teacher'),
('S','Student'),
('P','Parent'),
)
class Profile(models.Model):
eduser = models.OneToOneField(settings.AUTH_USER_MODEL)
photo = models.ImageField(upload_to='users/%Y/%m/%d',blank=True)
about_me = models.TextField(max_length=200,blank=True)
category = models.CharField(max_length=1,choices=CATEGORY_CHOICES,blank=True)
date_of_birth = models.DateField(blank=True,null=True)
def __str__(self):
return 'Profile for user {}'.format(self.eduser.username)
forms.py
class UserEditForm(forms.ModelForm):
class Meta:
model = User
fields = ('first_name','last_name','email')
class ProfileEditForm(forms.ModelForm):
class Meta:
model = Profile
fields = ('category','date_of_birth','about_me','photo')
You need to catch the error. You can do it at the top of the function:
try:
profile = request.user.profile
except ObjectDoesNotExist:
profile = Profile(user=request.user)
and pass that profile into the ProfileEditForm in both if branches.