Home > Net >  Django model passes wrong value
Django model passes wrong value

Time:07-19

I am making a webapp with Django Framework. I am making a form for creating new "incidents" (this form is using a model called NewIncidents). I am trying to take the values under "title" from my IncidentsType table, and use them as options for a Select menu in the form. But, something weird happens: in the form, the options appear, but when you submit the form and check how it was submitted (in the admin panel), it shows the .object(n) instead of the name of the option.

For example: Result of one submit : in the form showed the correct selection name, which was "Internet", but after submitting, in the admin panel, it showed IncidentsType object (3).

My models:

from django.db import models


class NewUsers(models.Model):
    name = models.CharField(max_length=38)
    user_name = models.CharField(max_length=35)


class NewIncidents(models.Model):
    tipo = models.CharField(max_length = 50)
    titulo = models.CharField(max_length = 200)
    resolucion =  models.CharField(max_length = 300)

class IncidentsType(models.Model):
    title = models.CharField(max_length = 200)
    subtitle = models.CharField(max_length = 200)
    description = models.CharField(max_length = 400)

My form:

from django import forms
from django.db import models
from .models import NewIncidents, IncidentsType



class IncidentForm(ModelForm):
    incidents = IncidentsType.objects.all()
    eleji = []
    for incident in incidents:
        ttype = incident.title
        num = str(incident)
        conjunto = (num, ttype)
        eleji.append(conjunto) 
    tipo = forms.ChoiceField(choices=eleji)
    class Meta:
        model = NewIncidents
        fields = ('tipo', 'titulo', 'resolucion')
        labels = {
            'tipo': 'Tipo de Incidente:',
            'titulo': 'Resumen del Incidente:',
            'resolucion': 'Resolucion del Incidente:',
        }
        widgets = {
            'tipo': forms.Select(attrs={'class' : 'form-control'}),
            'titulo': forms.TextInput(attrs={'class' : 'form-control'}),
            'resolucion': forms.TextInput(attrs={'class' : 'form-control'}),
        }

CodePudding user response:

on your models try defining the str function to help django better represent the objects of the model in the admin page

example for the IncidentsType:

class IncidentsType(models.Model):
    title = models.CharField(max_length = 200)
    subtitle = models.CharField(max_length = 200)
    description = models.CharField(max_length = 400)
    
    def __str__(self):
        return self.title

basicly this function should return a string that represents the object like a name or a title

you can read more about it in the docs here

  • Related