for循环输入表单.py数据发送后无法立即加载| Python Djang

2024-05-28 23:00:52 发布

您现在位置:Python中文网/ 问答频道 /正文

在表单.py我有一小段加载数据的代码,但只有在编辑了其中的print("hello")之后。你知道吗

代码如下:

models.py

class CreateAssignment(models.Model):
    user = models.ForeignKey(User, editable=False, blank=True, null=True)
    progress = models.CharField(max_length=254, editable=False, blank=True, null=True)

class SetAssignment(models.Model):
    mechanic = models.ForeignKey(User, editable=False, blank=True, null=True)
    assignment = models.IntegerField(blank=True, null=True)

技工是一个权限,加上这个技工的ID将显示在网站的url,当你将试图设置一个分配给这个技工。你知道吗

forms.py

class SetAssignmentForm(forms.ModelForm):
    ASSIGNMENT_CHOICES = ()

    for item in CreateAssignment.objects.all():
        if item.progress == 'Scheduling':
            user = User.objects.get(id=item.user_id).username

            ASSIGNMENT_CHOICES += (
                (item.id, user + ' - ' + str(item.id)),
            )

    assignment = forms.ChoiceField(choices=ASSIGNMENT_CHOICES, help_text='This is the assignment that you want to apply to this mechanic.')

    class Meta:
        model = SetAssignment
        fields = ('assignment', )

这种情况下的user_id是在CreateAssignment模型中设置的user。你知道吗

现在的问题是:

  • SetAssignmentForm中的for循环可以工作,但在我将print放入循环后或从循环中移除print时,它会加载数据。这当然不应该真正影响代码。你知道吗

有什么我忽略了吗?我已经用pythondjango编程8周了,如果这是一个基本的程序失败,请让我看一页,因为我还没有找到任何关于这个问题的信息。你知道吗

谢谢你的帮助。你知道吗

对于那些想知道的人:

views.py

@login_required
def set_assignment(request):
    form = SetAssignmentForm()
    id = request.GET.get('id')
    user_results = User.objects.filter(pk=id).values()
    return render(request, 'pages/set_assignment.html', {'form': form, 'user_results': user_results})

Gif,以便您可以直观地看到发生了什么:

https://drive.google.com/open?id=1u7gfdiS7KitQWNVuvQEEOFJ9wD3q9rY6


Tags: 代码pyidtruemodelsitemnullclass
1条回答
网友
1楼 · 发布于 2024-05-28 23:00:52

不能在类级别编写这样的代码。在该级别上的任何操作只在定义时执行一次,即在第一次导入类时。你知道吗

如果需要使值动态化,则应将逻辑放在__init__方法中:

class SetAssignmentForm(forms.ModelForm):    
    assignment = forms.ChoiceField(choices=[], help_text='This is the assignment that you want to apply to this mechanic.')

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

        items = CreateAssignment.objects.filter(progress='Scheduling').select_related('user')
        choices = [(item.id, '{} - {}'.format(item.id, item.user.username)) for item in items]
        self.fields['assignment'].choices = choices

(注意,您的查询逻辑非常低效;我的代码只在数据库中命中一次。)

但是,在这里您甚至不需要这样做,因为Django已经有一个表单字段modelcooicefield,它从数据库中获取它的值。您可以使用它的自定义子类来显示表示:

class AssignmentField(forms.ModelChoiceField):
    def label_from_instance(self, item):
        return (item.id, '{} - {}'.format(item.id, item.user.username))

class SetAssignmentForm(forms.ModelForm):    
    assignment = forms.AssignmentField(queryset=CreateAssignment.objects.filter(progress='Scheduling').select_related('user'))

相关问题 更多 >

    热门问题