Hello!
I am looking to write a validator that will prevent a user from inputting duplicate entries, but would allow duplicate entries in the overall table. For example, let’s say each of my users is a company that needs to input customer info. If two of these companies have the same customer, they should be able to have the same data in their own user-owned rows without throwing an error. On the other hand, I’d like to prevent an individual user from creating duplicates. I had tried the unique_together option on the model only to have it fail because of the owner field being a foreign key. Additionally, the owner field in the form is excluded. I have read through a bunch of the documentation and am still a bit lost. I am new to coding and Django so if anyone could offer some insights, it would be greatly appreciated. TIA
views.py
class CustomerCreate(OwnerCreateView):
model = Customer
form_class = CustomerCreateForm
template_name = ...
success_url = ...
class CustomerUpdate(OwnerUpdateView):
model = Customer
form_class = CustomerUpdateForm
template_name = ...
success_url = ...
owner.py
class OwnerCreateView(LoginRequiredMixin, CreateView):
def form_valid(self, form):
form.instance.owner = self.request.user
return super().form_valid(form)
class OwnerUpdateView(LoginRequiredMixin, UpdateView):
def get_queryset(self):
qs = super(OwnerUpdateView, self).get_queryset()
return qs.filter(owner=self.request.user)
models.py
class Customer(models.Model:
first_name = models.CharField(max_length=50)
last_name = models.CharField(max_length=50)
company = models.CharField(max_length=128, blank=True)
owner = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
forms.py
class CustomerCreateForm(ModelForm):
class Meta:
model = Customer
exclude = ('owner',)
class CustomerUpdateForm(ModelForm):
class Meta:
model = Customer
exclude = ('owner',)