I have a custom user model with a field 'customer'. Each user has a customer. I am trying to get the logged in users customer so that when I add infringer, the correct customer is added for the record.
- I think below is wrong in views. customer=request.user.customer
- think below is wrong in forms. customer__user=self.customer
views.py
@login_required(login_url='login')
def createInfringer(request):
customer=request.user.customer
form = InfringerForm(customer=request.customer)
if request.method == 'POST':
form = InfringerForm(customer, request.POST)
if form.is_valid():
form.save()
return redirect('infringer-list')
context ={'form': form}
return render (request, 'base/infringement_form.html', context)
forms.py
class InfringerForm(ModelForm):
def __init__(self, customer, *args, **kwargs):
self.customer = customer
super(InfringerForm,self).__init__(*args, **kwargs)
self.fields['customer'].queryset = Customer.objects.filter(customer__user=self.customer)
class Meta:
model = Infringer
fields = ['name', 'brand_name','status' , 'customer']
models.py
class Infringer (models.Model):
name = models.CharField(max_length=200)
brand_name = models.CharField(max_length=200, null=True)
updated = models.DateTimeField(auto_now=True)
created = models.DateTimeField(auto_now_add=True)
groups = models.ForeignKey(Group, on_delete=models.CASCADE,default=1)
status = models.ForeignKey(Status, on_delete=models.SET_NULL,null=True)
customer = models.ForeignKey(Customer, on_delete=models.SET_NULL,null=True)
class Meta:
ordering = ['-updated', '-created']
def __str__(self):
return self.name
class Customer (models.Model):
name = models.CharField(max_length=200)
email = models.EmailField(max_length=254, default='@cudo.ai')
updated = models.DateTimeField(auto_now=True)
created = models.DateTimeField(auto_now_add=True)
phone_number = PhoneNumberField(blank=True)
groups = models.ForeignKey(Group, on_delete=models.CASCADE,default=1)
player = models.ManyToManyField(Player, related_name='player', blank=True)
is_active = models.BooleanField(default=False)
class Meta:
ordering = ['name']
def __str__(self):
return self.name
class User(AbstractUser):
email = models.EmailField(unique=True, null=True)
avatar = models.ImageField(null=True, default="logo.svg")
username = models.CharField(max_length=40, unique=False,
default='')
customer = models.ForeignKey(Customer, on_delete=models.SET_NULL,null=True)
CodePudding user response:
If I understand correctly, you identified the problems correctly. So I think you need to:
- Change line 5 in views.py:
form = InfringerForm(customer=customer)
- Change line 5 in form.py"
self.fields['customer'].queryset = Customer.objects.filter(customer=customer)
CodePudding user response:
- views.py customer=request.user.customer form = InfringerForm(customer=customer)
- forms.py self.fields['customer'].queryset = Customer.objects.filter(name=customer)