Home > Software engineering >  Automatically link form and user using OneToOneField
Automatically link form and user using OneToOneField

Time:10-09

I have create a model form using also OneToOneField field to link it to my user, my problem is that I have to go to the admin section to manually select the user to make it works. Is it possible to have the user linked to the form submitted automatically? Also this may be stupid but when I use user.userinformation.gender to get the info about gender I get back "m", is there a way to access the label "Male" instead? TThank for yours help! My code:

models.py

class UserInformation(models.Model): 
   gender_choice = [('m', 'Male'),('f', 'Female')]  

   user = models.OneToOneField(User, blank=True,  null=True, on_delete=models.CASCADE)   
   first_name = models.CharField(max_length=120)
   last_name = models.CharField(max_length=120)
   gender = models.CharField(max_length=120, choices=gender_choice)    
   phone = models.CharField(max_length=10)
   email = models.EmailField()

forms.py

class UserInformationForm(forms.ModelForm):
   class Meta:
       model = UserInformation
       fields = ('first_name', 'last_name', 'gender', 'phone', 'email',)
views.py 
def add_information(request):
   if request.method == "POST":
       form = UserInformationForm(request.POST)        
       if form.is_valid():          
           form.save()
           messages.success(request, 'Form submitted')         
   else:
       form = UserInformationForm()
   return render(request, 'accounts/profile/add_information.html', {'form': form})

def show_profile(request):
   profile_info = UserInformation.objects.all()

   return render(request, 'accounts/profile/user_profile.html', {'profile_info': profile_info})

CodePudding user response:

Yes, you can link the .user of the UserInformation to the logged in user with:

from django.shorcuts import redirect
from django.contrib.auth.decorators import login_required

@login_required
def add_information(request):
   if request.method == 'POST':
       form = UserInformationForm(request.POST, request.FILES)
       if form.is_valid():          
           form.instance.user = request.user
           form.save()
           messages.success(request, 'Form submitted')
           return redirect('name-of-some-view')
   else:
       form = UserInformationForm()
   return render(request, 'accounts/profile/add_information.html', {'form': form})

Note: In case of a successful POST request, you should make a redirect [Django-doc] to implement the Post/Redirect/Get pattern [wiki]. This avoids that you make the same POST request when the user refreshes the browser.


Note: You can limit views to a view to authenticated users with the @login_required decorator [Django-doc].

CodePudding user response:

I think that what you are looking for is the initial attribute of UserInformationForm instance but you need to add user to the form fields.

form = UserInformationForm(initial={"user":request.user.id})

If you dont want your user to see/edit the information, consider using a HiddenInput widget in your ModelForm or set disabled attribute.

class UserInformationForm(forms.ModelForm):
   class Meta:
       model = UserInformation
       fields = '__all__'
       widgets = {'user': forms.HiddenInput()}
  • Related