user7084802
user7084802

Reputation:

Django - Limit the number of instances of a model for every user

I want to limit the number of instances of a specific class. I already have limited it by using some HTML, but if someone sneaky reuses the link to the form, one can make another instance.

So in my views.py, I make a query

qry_models = Model.objects.filter(owner=request.user)

In my HTML-template, I already made the adjustments to prevent multiple instances. If there is none, one is redirected to the ModelForm to create an instance. If there is a model in the query, it is displayed/usable.

{% for model in qry_models %}
    {{ model }}
{% empty %}
    <a href="{% url 'app:model_new' %}">Make a new instance</a>
{% endfor %}

But if someone reuses the link one is redirected to in the first place, he can create another instance. That shall be prevented.

I want to have one instance for each user account. If I follow Limit number of model instances to be created, I always get a MultipleObjectsReturned error since it queries all instances from all account and not only the instances from the active/logged in account.

Edit: I made another query that always redirects me, if there already is an instance. But is that good code-design or just a useful logic circle?

def model_new(request):
    mymodel = Model.objects.filter(owner=request.user)
    counter = mymodel.count()
    if counter >0:
        return HttpResponseRedirect('somewhere')

    if request.method != 'POST':
        form = ModelForm()
    ....

Upvotes: 2

Views: 1435

Answers (1)

Ibrahim Kasim
Ibrahim Kasim

Reputation: 1544

Best practices of limiting the instances for a user in Django are mapping one-to-one field relationship to user column in the table.

# models.py
from django.db import models

class Student(models.Model):
    user = models.OneToOneField(User)
    course = models.CharField(max_length=100)

#Refactoring your views.py
from django.http import HttpResponse

def create_student(request):
    if not Student.objects.filter(user=request.user).exists():
        Student.objects.create(user=request.user, course='Engineering')
        return HttpResponse('Student is created')
   else:
       return HttpResponse('Student already exists')

Upvotes: 1

Related Questions