我希望我的表单检查PostgreSQL中是否已经存在相同的名称和日期,所以它不会产生重复。
models.py:
class Event(models.Model):
week = models.DateField(blank=False)
name = models.ForeignKey(Employee, default=None, on_delete=models.CASCADE)
sunday = models.CharField(max_length=50, default=None, null=True)
monday = models.CharField(max_length=50)
tuesday = models.CharField(max_length=50)
wednesday = models.CharField(max_length=50)
thursday = models.CharField(max_length=50)
friday = models.CharField(max_length=50)
saturday = models.CharField(max_length=50, default=None, null=True)
def __str__(self):
return self.week
views.py:
def test2(request):
locationList = Location.objects.all().order_by('name') #Pulls location data from location table
clientList = Client.objects.all().order_by('name') #Pull client data from client table
if request.method == 'POST':
form1 = EventForm2(request.POST) #Displays form to be filled out by user
if form1.is_valid():
event = form1.save() #Saves form if valid data is entered
messages.info(request, 'Successfully added')
return HttpResponseRedirect(reverse('test2')) #Refreshes page to default
else:
form1 = EventForm2() #Form remains the same until valid data has been entered
eventList = Event.objects.all().order_by('week', 'name')
return render(request, 'app/test2.html', { # brings all the data into selected html
"form": form1,
"locationList": locationList,
"clientList": clientList,
"eventList": eventList,
})
因此,例如2019年1月27日;鲍勃·迪伦(Bob Dylan)已存在于数据库中,该表格将无法提交
答案 0 :(得分:0)
在视图中,您可以执行以下操作:
name = form1.cleaned_data['name']
week = form1.cleaned_data['week']
E = Event.objects.filter(name=name, week=week)
因此,如果len(e)> 0,则数据库中存在一个具有相同数据的对象
如果len(E)== 0:然后根据需要添加