I have a model Menu:
class Menu(models.Model):
loja = models.ForeignKey(Loja, related_name='menus')
nome = models.CharField(max_length=30)
ordenacao = models.IntegerField(blank=True, null=True)
class Meta:
ordering = ('ordenacao',)
#prevent equally named menus within a store(loja)
unique_together = ('loja', 'nome')
def __unicode__(self):
return self.nome
The Menu form:
class MenuForm(ModelForm):
class Meta:
model = Menu
exclude =('loja', 'ordenacao',)
Add menu view:
def addmenu(request, s_loja):
loja = get_object_or_404(Loja, slug=s_loja)
if not loja.activo:
return render_to_response('painelcontrolo/loja_detail.html', {
'notificacoes': ['Loja está definida como inactivo.', \
'Alterações não permitidas']})
if request.method == 'POST':
menu = Menu(loja=loja)
form = MenuForm(request.POST, instance=menu)
if form.is_valid():
menu_existe = Menu.objects.\
filter(nome=form.cleaned_data['nome']).\
filter(loja=loja)
if menu_existe:
return render_to_response(\
'painelcontrolo/loja_detail.html', {
'notificacoes': ['Já existe um menu com esse nome']
})
form.save()
return render_to_response(\
'painelcontrolo/loja_detail.html', {
'notificacoes': ['Menu adicionado']
})
else:
form = MenuForm()
return render_to_response('form_as_p.html', {
'form': form
})
The error:(no longer occurs with the added validation on the addmenu view)
Request Method: POST
Request URL: http://127.0.0.1:8000/painel/bispos/addmenu/
Exception Type: IntegrityError
Exception Value: columns loja_id, nome are not unique
The question: The form is valid, but the model isn't if nome+loja_id already exist on the db. Do I need to add this validation somewhere else? And where?
edit: I wrote a validation on the view and it passes a notification to the template and this is fine, but not perfect. I would like to re-display the form with the user input to give an opportunity to fix what's wrong without losing that information. Is there a way to do that?