'Django - Assign & limit every logged-in user to create only one instance
How to limit every logged-in user to create only one instance/object from the frontend?
here's my model looks like:
class MyModel(models.Model):
u_name = models.OneToOneField(User, on_delete=models.CASCADE)
category = models.ForeignKey(Category, blank=True, null=True, on_delete=models.CASCADE)
...
...
my_linkedin = models.URLField(unique=True, blank=True, null=True)
my_price = models.CharField(max_length=20, default=0)
joined = models.DateTimeField(default=now, editable=False)
def __str__(self):
return self.my_name
def clean(self):
model = self.__class__
if model.objects.count() > 0 and \
self.id != model.objects.get().u_name_id:
print('hell')
raise ValidationError("You can only create 1 profile ")
my views:
class MyCreateView(LoginRequiredMixin, CreateView):
model = MyModel
fields = [
'category',
....
....
]
template_name = 'index/form.html'
success_url = '/'
def form_valid(self, form):
form.instance.u_name = self.request.user
return super().form_valid(form)
And my form:
class MyModelForm(forms.ModelForm):
class Meta:
model = MyProfile
fields = '__all__'
exclude = ['u_name']
The problem is, that the current code here, they can't assign on every logged-in user. So when I try to login using a different user, The error looks like:
get() returned more than one MyModel -- it returned 3!
How can I achieve this?
Solution 1:[1]
def clean(self):
model = self.__class__
if model.objects.count() > 0 and \
self.id != model.objects.get().u_name_id:
print('hell')
raise ValidationError("You can only create 1 profile ")
model.objects.get() -> This is the cause of this error. get() must return only one object from this table. But this table has 3 rows from what I can see. You must add parameters in get function returning one object then you can access this object u_name_id. Like this:
if model.objects.count() > 0 and model.objects.filter(u_name_id = self.u_name_id).count > 0:
print("hell")
raise ValidationError("You can only create 1 profile ")
Or:
from django.core.exceptions import ObjectDoesNotExist
.
.
.
if model.objects.count() > 0:
try:
obj = model.objects.get(u_name_id = self.u_name_id)
print("hell")
raise ValidationError("You can only create 1 profile ")
except ObjectDoesNotExist:
pass # this is not problem for you because this user have not object
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Dharman |
