一起提交2个表单,将其中一个主键作为外键传递给另一个表单

时间:2022-05-08 18:09:26

I have created a form using python and django from 2 seperate modelForms in the one html template. Models:

我在一个html模板中使用了来自2个单独的modelForms的python和django创建了一个表单。楷模:

class Action(models.Model):
    name = models.CharField("Action name", max_length=50)
    keywords = models.CharField("Keywords", max_length=50)
    object = models.CharField("Object", max_length=50, blank=True, null=True)
    uploadDate = models.DateField("Date", default=get_current_date)
    UploadedBy = models.CharField("UploadedBy", max_length=50, default="")

class Image(models.Model):
    image = models.FileField(upload_to=get_upload_file_name, default="") 
    action = models.ForeignKey(Action)

def get_upload_file_name(instance, filename):
    return "uploaded_files/%s_%s" % (str(datetime.now().day).replace('.','_'), filename)

forms:

class ActionForm(ModelForm):
    #bind form to Action model
    class Meta:
        model = Action
        fields = ['name','keywords', 'object', 'UploadedBy', 'uploadDate']

class ImageForm(ModelForm):
    class Meta:
        model= Image
        fields =['image']

The code which creates the form in views:

在视图中创建表单的代码:

def actioncreate(request):
    if request.method == "GET":
        #create the object - Actionform 
        form = ActionForm;
        form2 = ImageForm;
        #pass into it 
        return render(request,'app/createForm.html', { 'form':form, 'form2':form2})
    elif request.method == "POST":
        # take all of the user data entered to create a new action instance in the table
        form = ActionForm(request.POST, request.FILES)
        form2 = ImageForm(request.POST, request.FILES)
        if  form.is_valid() and form2.is_valid():
            act = form.save(commit=False)
            img = form2.save(commit=False)
            #set the action_id Foreignkey 
            act.id = img.action_id                 
            act.save()
            img.save()
            return HttpResponseRedirect('/actions')
        else:
            form = ActionForm()
            form2 = ImageForm;
            return render(request,'app/createForm.html', { 'form':form, 'form2':form2 })

The form is created fine but when it is submitted, it trys to save image.id, image.image (filename) and returns null for image.action_id I am getting the error:

表单创建正常但在提交时,它试图保存image.id,image.image(filename)并为image.action_id返回null我收到错误:

null value in column "action_id" violates not-null constraint
DETAIL:  Failing row contains (2, uploaded_files/29_personrunning_Hq8IAQi.jpg, null).   

I obviously need to populate the third column with the action.id which django creates itself on submitting the first part 'form'. Is there a way I can get the action.id value and populate the action_id field in the image table in the one form submission? image.action_id is declared initially as a foreignKey related to action in models.

我显然需要用action.id填充第三列,django在提交第一部分'form'时创建了自己。有没有办法可以获取action.id值并在一个表单提交中填充图像表中的action_id字段? image.action_id最初被声明为与模型中的操作相关的foreignKey。

1 个解决方案

#1


0  

The first problem is related to act = form.save(commit=False) because it will return an object that hasn’t yet been saved to the database, then act doesn't have an ID. You need to save (and commit) act first.

第一个问题与act = form.save(commit = False)有关,因为它将返回一个尚未保存到数据库的对象,然后act没有ID。您需要先保存(并提交)行为。

Also there is another error in following line:

以下行还有另一个错误:

act.id = img.action_id  # It should be: img.action_id = act.id

You may want to assign act to img.action. Please note that you are doing it in the wrong way (you are assigning in img.action to act). The best way to do it is:

您可能希望将act分配给img.action。请注意,您正在以错误的方式执行此操作(您将在img.action中进行操作以进行操作)。最好的方法是:

img.action = act  # This is equivalent to img.action_id = act.id

Try swapping these lines:

尝试交换这些行:

        act.save()
        img.action = act

#1


0  

The first problem is related to act = form.save(commit=False) because it will return an object that hasn’t yet been saved to the database, then act doesn't have an ID. You need to save (and commit) act first.

第一个问题与act = form.save(commit = False)有关,因为它将返回一个尚未保存到数据库的对象,然后act没有ID。您需要先保存(并提交)行为。

Also there is another error in following line:

以下行还有另一个错误:

act.id = img.action_id  # It should be: img.action_id = act.id

You may want to assign act to img.action. Please note that you are doing it in the wrong way (you are assigning in img.action to act). The best way to do it is:

您可能希望将act分配给img.action。请注意,您正在以错误的方式执行此操作(您将在img.action中进行操作以进行操作)。最好的方法是:

img.action = act  # This is equivalent to img.action_id = act.id

Try swapping these lines:

尝试交换这些行:

        act.save()
        img.action = act