Reputation: 21
So I have this project where I have several supervisors that can create projects. I want that for each supervisor they can't make a project with the same title. I tried to use UniqueConstraint but now it's not working. Supervisors can still create a project with the same title. Note: Project's supervisor is automatically assigned to the project creator.
models.py
class Project(models.Model):
title = models.CharField(max_length=100)
due_date = models.DateField()
due_time = models.TimeField()
supervisor = models.ForeignKey(User, default=None, on_delete=models.SET_DEFAULT)
class Meta:
constraints = [models.UniqueConstraint(fields=['title', 'supervisor'], name="unique title")]
verbose_name = "Project"
def __str__(self):
return str(self.title) + "-" + str(self.supervisor)
forms.py
class CreateProjects(forms.ModelForm):
class Meta:
model = models.Project
fields = ['title', 'due_date', 'due_time']
widgets = {
'due_date': DateInput()
}
views.py
@login_required(login_url="/signin")
def create_project(response):
if response.user.is_staff:
if response.method == 'POST':
form = forms.CreateProjects(response.POST, response.FILES)
if form.is_valid():
# save project to db
instance = form.save(commit=False)
instance.supervisor = response.user
print(instance.supervisor)
instance.save()
return redirect('/dashboard')
else:
form = forms.CreateProjects(initial={'supervisor': response.user})
ctx = {'form': form, 'FullName': response.user.get_full_name}
else:
form = "Only Teachers can create projects"
ctx = {'form': form, 'FullName': response.user.get_full_name}
return render(response, "create_project.html", ctx)
Upvotes: 1
Views: 92
Reputation: 177
The simplest way is to define unique on the field.
class Project(models.Model):
title = models.CharField(max_length=100,unique=True)
repeat on any field(s) you want it to be unique.
Upvotes: 0