Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

214
Visualizações
set slug field form manually in views Django

I'm new in Django and I'm trying to pre fill one of the fields of my form with a slug.

I'm getting the slug from another model. I'm not using ForeignKey because that shows me a list with my objects and I want to save in the form the same slug that I'm using in the url.

Maybe I'm not thinking this right. What should I do?

Thank you!

This are my models:

from django.db import models

class Thing(models.Model):

    name = models.CharField(max_length=255,)
    rut = models.CharField(max_length=12, blank= True)
    cel = models.CharField(max_length=12, blank= True)

    slug = models.SlugField(unique=True)

class Control(models.Model):
    id_p = models.SlugField()
    pa = models.CharField(max_length=3,)

My forms

from django.forms import ModelForm
from collection.models import Thing, Control, Medicamento

class ThingForm(ModelForm):
   class Meta:
       model = Thing
       fields = ('name', 'rut','cel','pet',)

class ControlForm(ModelForm):
   class Meta:
       model = Control
       exclude = ['id_p']

This is what I'm doing in the views

def add_control(request, slug):
    thing = Thing.objects.get(slug=slug)
    form_class = ControlForm

    form_class(initial={'id_p':thing})

    if request.method == 'POST':
        form = form_class(request.POST)
        if form.is_valid():
           form.save()
           return redirect('thing_detail', slug=thing.slug)
    else: form = form_class()

    return render(request, 'things/control.html', {
    'thing': thing,
    'form': form,
})
over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

So, I figure it out! In views.py, after " if form.is_valid():" I put this:

prev = form.save(commit=False)
prev.id_p = thing.slug
prev.save()    

In that way I put the data in the excluded field before I commit the form.

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda