Note that there are some explanatory texts on larger screens.

plurals
  1. POunique_together validation fails if one of the fields is excluded from form
    primarykey
    data
    text
    <p>I have a model Menu:</p> <pre><code>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 </code></pre> <p>The Menu form:</p> <pre><code>class MenuForm(ModelForm): class Meta: model = Menu exclude =('loja', 'ordenacao',) </code></pre> <p>Add menu view:</p> <pre><code>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 }) </code></pre> <p>The error:(no longer occurs with the added validation on the addmenu view)</p> <pre><code>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 </code></pre> <p>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?</p> <p>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?</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload