我有一个自定义用户模型,其中有一个字段“客户”。每个用户都有一个客户。我正在尝试获取登录用户的客户,以便在添加侵权者时,将正确的客户添加到记录中。
1.我认为下面的观点是错误的。客户=请求.用户.客户
1.我认为下面的表格是错误的。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)
2条答案
按热度按时间rvpgvaaj1#
如果我的理解正确的话,你正确地发现了问题。所以我认为你需要:
1.更改www.example.com中的第5行views.py:
form = InfringerForm(customer=customer)
1.将中的第5行更改为form.py“
self.fields['customer'].queryset = Customer.objects.filter(customer=customer)
jgovgodb2#
1.用户forms.py名:用户名:用户名:用户名:用户名:用户名:用户名:用户名:用户名:用户名:用户名:用户名