如何在表格中设置初始值

时间:2019-09-13 02:08:33

标签: django django-models django-forms django-views

伙计们,我该如何在表单字段中设置初始值,假设用户在搜索表单中单击“ BidForm”,我希望BidForm值将是其他表单中ProjectName的值...

这是我在搜索视图中的代码

def search_views(request):
    project_list = ProjectNameInviToBid.objects.all()
    query = request.GET.get('query')
    if query:
        project_list = project_list.filter(ProjectName__icontains=query)

    context = {
        'project_list': project_list
    }
    return render(request, 'content/search_views.html', context)

和我的其他观点

def project_name_details(request, sid):

    majordetails = ProjectNameInviToBid.objects.get(id=sid)

    if request.method == 'POST':
        form = invitoBidForm(request.POST, request.FILES)
        form.fields['ProjectName'].initial = majordetails
        if form.is_valid():
            form.save()
            messages.success(request, 'File has been Uploaded')
    else:
        form = invitoBidForm()

    args = {
        'majordetails': majordetails,
        'form': form

    }
    return render(request,'content/invitoBid/bacadmininvitoBid.html', args)

我的form.py

class invitoBidForm(ModelForm):

    class Meta:

        model = InviToBid
        fields = ('ProjectName','NameOfFile', 'Contract_No', 'Bid_Opening',
                  'Pre_Bid_Conference', 'Non_Refundable_Bidder_Fee',
                  'Delivery_Period',
                  'Pdf_fileinvi',)

和我的模型。py

class ProjectNameInviToBid(models.Model):
    ProjectName = models.CharField(max_length=255, verbose_name='Project Name', null=True)
    DateCreated = models.DateField(auto_now=True)

    def __str__(self):
        return self.ProjectName


class InviToBid(models.Model):
    today = date.today()
    ProjectName = models.ForeignKey('ProjectNameInviToBid', on_delete=models.CASCADE)
    NameOfFile = models.CharField(max_length=255, verbose_name='Name of File')
    Contract_No = models.IntegerField(verbose_name='Contract No')

    def __str__(self):
        return self.NameOfFile

1 个答案:

答案 0 :(得分:1)

首先,我会赞赏您的文档。大多数人没有提供重要的代码。

您可以在此处向您的代码中添加类似的内容,从而满足您的要求。

我自己代码中的示例

    if request.method == 'GET' and request.user.is_authenticated:
        study = Study.objects.get(pk=studyID)
        form = ContactForm(initial={'from_email': request.user.email, 'subject': "Study: " + study.name ,'message': study_message.format(request.user.get_short_name(), request.user.get_full_name())})

如何更改代码

通过以下方法更改other views中的代码:

else:
        form = invitoBidForm()

else:
        form = invitoBidForm(initial={'ProjectName': <wherever your project name comes from>})