Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

213
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda