Django表单的下拉选项显示为“对象”,而不是模型的字符串表示形式__str__

时间:2018-08-21 16:56:51

标签: django python-3.x django-models django-forms

在django表单中,我正在使用一种方法将下拉选项筛选为与登录用户相关的选项。实施后,显示的值更改为objects而不是__str__值。我正在发布简化的代码和显示此内容的快照。我已经遵循了所有必要的条件,但是我不知道为什么会发生这种情况:

models.py

class Business(models.Model):
    client=models.ForeignKey('Client',on_delete=models.CASCADE, limit_choices_to={'is_active':True},)
    name=models.CharField(max_length=30,blank=False, unique=True,)

    def __str__(self):
        return self.name


class MMRequestAttributes(models.Model):
    client=models.ForeignKey('Client',on_delete=models.CASCADE, limit_choices_to={'is_active':True},)    
    business=models.ForeignKey('Business', on_delete=models.CASCADE,limit_choices_to={'is_active':True},)

class Ticket(MMRequestAttributes):    
    no=models.CharField('Ticket Number',max_length=50,default=uuid.uuid4,null=False, blank=False, editable=False, unique=True)
    subject=models.CharField('Subject',max_length=100,null=False, blank=False)
    description=models.TextField('Description',max_length=500,null=True,blank=True)
    created_at=models.DateTimeField('Created at',auto_now_add=True, editable=False)
    updated_at=models.DateTimeField('Updated at',auto_now=True, editable=False)
    created_by= models.ForeignKey(settings.AUTH_USER_MODEL)

    status=StateField(editable=False) 

    def __str__(self):
        return 'Ticket #' + str(self.pk)

views.py

def new_ticket(request):
    form=NewTicket(request.user)
    return render(request,'mmrapp/new_ticket.html',{'form':form})

admin.py

class UserExtend(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE, blank=False,null=False,)
    client=models.ForeignKey('Client', on_delete=models.CASCADE,limit_choices_to={'is_active': True},)

forms.py

from django import forms
from .models import Ticket, Business
from .admin import UserExtend
from django.forms import ModelChoiceField

class NewTicket(forms.ModelForm):

    def __init__(self,user, *args, **kwargs):
        super(NewTicket, self).__init__(*args, **kwargs)

        try:
            client_id = UserExtend.objects.values_list('client_id', flat=True).get(user=user)
            self.fields['business'].queryset=Business.objects.filter(client__id=client_id)

        except UserExtend.DoesNotExist:
            ### there is not userextend corresponding to this user, do what you want 
            pass

    class Meta:
        model=Ticket
        fields = ('subject','business')

new-ticket.html

{% extends 'mmrapp/__l_single_column.html' %}
{% load static %}

{% block main_col %}
    <h1>New Ticket</h1>
    <form method="POST" class="new-ticket">{% csrf_token %}
        {{ form.as_p }}
        <button type="submit" class="save btn btn-default">Submit</button>
    </form>
{% endblock main_col %}

snapshot

1 个答案:

答案 0 :(得分:0)

最后我找到了问题。当在下拉列表中将原始模型显示为选项时,django无法以某种方式加载原始模型的对象(__str__)的字符串表示形式。我必须在from模型中再次明确定义它们。该属性称为label_from_instance。好处是,这样可以显示与模型中最初定义的内容不同的内容。

所以猴子的补丁应该是:

self.fields['business'].label_from_instance = self.business_label

@staticmethod
def business_label(self):
    return str(self.name)