猿问

如何使用从变量中获得的默认值自动填充模型表单字段?

    我正在使用 ModelForm,我想用一个初始值填充我的 dataset_id 字段,该初始值将来自争论中传递的“pid”变量。我已经尝试了一些东西并附加了该代码,但它不起作用


views.py


def home(request, pid):

    # if this is a POST request we need to process the form data

    if request.method == 'POST':

        # create a form instance and populate it with data from the request:

        form = DelegateForm(request.POST)

        # check whether it's valid:

        if form.is_valid():

            # process the data in form.cleaned_data as required

            p = form.save()

            # redirect to a new URL:

            return HttpResponseRedirect('/')

        # if a GET (or any other method) we'll create a blank form

    else:



         # Here I want to pass the value of "pid" to the dataset_id field so that when it renders it is populated with the value in the pid variable

        form = DelegateForm(initial={'dataset_id': pid})




    return render(request, 'add_delegate.html', {'dform': form, 'uid': pid})

models.py


class Delegate(models.Model):

    dataset_id = models.CharField(max_length=255, null=True, blank=True)

    first_name = models.CharField(max_length=255)

    last_name = models.CharField(max_length=255, null=True, blank=True)

    email = models.CharField(max_length=255, null=True, blank=True)

    phone = models.IntegerField(null=True, blank=True)

    company = models.CharField(max_length=255, null=True, blank=True)

    designation = models.CharField(max_length=255, null=True, blank=True)

    address = models.CharField(max_length=255, null=True, blank=True)

    city = models.CharField(max_length=255, null=True, blank=True)

    pincode = models.IntegerField(null=True, blank=True)

    image_path = models.CharField(max_length=2083, null=True, blank=True)

forms.py



慕虎7371278
浏览 111回答 2
2回答

Qyouu

我的代码中有一些功能冲突,我将它们分开,所以现在我有了解决方案

慕侠2389804

我想应该在url的签名中使用pid作为参数,以便将其传递给相应的视图(home本例中的视图)。您的 urls 文件将包含path('home_path/<int:pid>',&nbsp;views.home,&nbsp;name='a')而不是在视图文件中:def&nbsp;home(request,&nbsp;pid): &nbsp;&nbsp;&nbsp;&nbsp;...
随时随地看视频慕课网APP

相关分类

Python
我要回答