Wednesday, September 2, 2020

How to get a user from a Modelform

Hi all,

I have a model from which I had a form. I would like to show in the form a MultipleChoiceField: customer that shows only the user's customers.
Nothing show in the MultipleChoiceField. I don't know how to succed to get the user in my form. Please help. Thanks a lot

models.py

class Customer(models.Model):
    first_name = models.CharField(max_length=100)
    last_name = models.CharField(max_length=100)
    author = models.ForeignKey(User, on_delete=models.CASCADE, related_name="customer", null=True)

class RiskAssessment(models.Model):
customer = models.ForeignKey(Customer, on_delete=models.CASCADE, related_name="riskassessment", null=True)

models.py

class AddRiskAssessment(forms.ModelForm):

class Meta:
model = RiskAssessment
fields = '__all__'

def __init__(self, *args, **kwargs):
user = kwargs.pop('user', None)
super(AddRiskAssessment, self).__init__(*args, **kwargs)
self.fields['customer'] = forms.ModelChoiceField(queryset=Customer.objects.filter(author=user))


views.py

def add_riskassessment(request):
if request.method == 'POST':
form = AddRiskAssessment(request.POST, user=request.user)
if form.is_valid():
form.save()
messages.success(request, f'Your form has been created!')
return redirect('addriskassessment')
else:
form = AddRiskAssessment()
return render(request, 'app/addriskassessment.html', {'form': form})

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/0ba5d0d3-119b-4723-8b5d-312b2ab05252n%40googlegroups.com.

No comments:

Post a Comment