如何在表单中显示只读唯一标识?

我目前有一个称为服务的模型,显示在这里...


class Services(models.Model):


    service_sku = models.AutoField(primary_key=True)

    name = models.CharField(max_length=200, null=True)

    price = models.FloatField(null=True)


forms.py


class ServiceForm(forms.ModelForm):


    class Meta:

        model = Services

        fields = '__all__'


基于上面显示的代码,我有两个视图,一个将创建上面模型的实例,另一个视图将更新实例,如下所示


def NewServices(request):

    form = ServiceForm()

    if request.method == 'POST':

        form = ServiceForm(request.POST or None)

        if form.is_valid():

            form.save()

            return redirect('/')

    return render(request, 'accounts/new_services.html', {'form': form})



def EditServices(request,pk):



    service = Services.objects.get(service_sku=pk)

    form = ServiceForm(instance=service)

    if request.method == 'POST':

        form = ServiceForm(request.POST, instance=service)

        if form.is_valid():

            form.save()

            return redirect('/')


    context = {'form':form}

    return render(request, 'accounts/edit_services.html',context)


模板如下


<div class="row">

    <div class="col-md-7">

        <div class="card card-body">

            <form action="" method="POST">

                {% csrf_token %}

                {{form}}

                <hr>

                <input type="submit" name="Update">

            </form>

        </div>

    </div>

</div>


是否可以在我的模板表单中显示 service_sku 的 readyonly,当实例需要更新时以及 service_sku readonly 在创建实例时显示为在模板中自动生成?


一只名叫tom的猫
浏览 109回答 1
1回答

白板的微信

是的。您可以在表单中包含该字段,因此您可能应该制作一个单独的表单来更新:class ServiceEditForm(forms.ModelForm):&nbsp; &nbsp; service_sku = forms.IntegerField(disabled=True)&nbsp; &nbsp; class Meta:&nbsp; &nbsp; &nbsp; &nbsp; model = Services&nbsp; &nbsp; &nbsp; &nbsp; fields = ('service_sku', 'name', 'price')在表单中,您只需使用该新表单:def EditServices(request,pk):&nbsp; &nbsp; service = Services.objects.get(service_sku=pk)&nbsp; &nbsp; if request.method == 'POST':&nbsp; &nbsp; &nbsp; &nbsp; form = ServiceEditForm(request.POST, request.FILES, instance=service)&nbsp; &nbsp; &nbsp; &nbsp; if form.is_valid():&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; form.save()&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return redirect('/')&nbsp; &nbsp; else:&nbsp; &nbsp; &nbsp; &nbsp; form = ServiceEditForm(instance=service)&nbsp; &nbsp; context = {'form':form}&nbsp; &nbsp; return render(request, 'accounts/edit_services.html', context)使用disabled=True[Django-doc]不仅可以确保该字段在客户端被禁用,而且还可以防止有人发出恶意的 POST 请求。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python