How to save current CustomUser as person field in my Melk model? There is OneToMany relation

(Amir) #1

I am curious to solve this problem. I use CustomUser I have 2 models CustomUser and Melk In my forms.py, when i use ‘person’ as field, it means user can see all the users but I want current user fill the form and based on onetomany relation, person field fills by id of current user.

I deleted ‘person’ field in forms and tried to use of
form.users_melk.person_id = request.user
or

Melk.objects.create(person_id = user_id)
but it does not solved.

# views.py

@login_required(login_url="home") 
def  melk_new(request):     
    f = MelkForm(request.POST) 
    if f.is_valid():         
        f.save() 
    return render(request,'melk_new.html', { 'form': f})

#forms.py


class MelkForm(forms.ModelForm):

class Meta:
    model = Melk
    fields = ('category', 'type_deal', 'person')

#models.py

class CustomUser(AbstractUser):
     def __str__(self):
        return self.email

class Melk(models.Model):
    category = models.CharField(max_length=50)  
    type_deal= models.CharField(max_length=50) 
    person = models.ForeignKey('CustomUser', on_delete=models.DO_NOTHING) 
    def __str__(self):
        return self.category

Thank you

0 Likes

(Basil Jose) #2

remove person from form fields = (‘category’, ‘type_deal’, ‘person’) and implement logic in view

if form.is_valid():
   melk = form.save(commit=False)
   melk.person = request.user
   melk.save()
   # Redirect here

or initialize form with this value as

form = MelkForm(initial={'person': request.user})
0 Likes

(Amir) #3

Thank you for the reply!
I try it. there is not error but it does not save data.
I changed person.save() by Melk.save() but it does not save.

0 Likes

(Basil Jose) #4

is this True, else try tuo get form.errors

0 Likes

(Amir) #5
@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})
0 Likes