简体   繁体   English

Django如何添加除表单以外的模型

[英]Django How to add a model other than a form

I am making an app using Django2.0. 我正在使用Django2.0开发应用程序。 But There are things that I do not know even if I investigate. 但是有些事情即使我进行调查也不知道。 There are models as follows. 有以下模型。

class Picture(models.Model):
    place = models.ForeignKey(Place, on_delete=models.CASCADE)
    title = models.CharField(max_length=255)
    image = models.ImageField(upload_to='image/')

using the following form 使用以下形式

class PictureForm(forms.ModelForm):
    class Meta:
        model = Picture
        fields = ['place', 'title', 'image']

And run following code on views.py 并在views.py上运行以下代码

obj = Picture()
pic = PictureForm(request.POST, request.FILES, instance=obj)
pic.save()

I can add model peacefully. 我可以和平添加模型。 But in this way, I should select place and title on form every time. 但是通过这种方式,我应该每次在表单上选择位置和标题。 Beforehand I decide place and title, I will only select image on the form. 在确定位置和标题之前,我只会在表格上选择图像。 It reduces my work. 它减少了我的工作。 Since there are several place and title, I do not want to set them to default values. 由于有多个位置和标题,因此我不想将它们设置为默认值。 I succeeded in making a form. 我成功地制作了表格。

class PictureForm(forms.ModelForm):
    class Meta:
        model = Picture
        fields = ['image',]

But I don't know how to add title and place on views.py 但是我不知道如何在views.py上添加标题和位置

I'm not good at English. 我不擅长英语。 Thank you for seeing the bad sentensecs to the end 感谢您看到糟糕的句子

Your issue comes from the view code, where you instantiate your new model. 您的问题来自于视图代码,您在其中实例化新模型。 If you want to create a new model you don't need to pass the insance argument, just edit the lines to get the following : 如果要创建新模型,则不需要传递insance参数,只需编辑以下行即可获得以下内容:

pic = PictureForm(request.POST, request.FILES)
pic.save()

See https://docs.djangoproject.com/en/2.0/topics/forms/modelforms/#the-save-method 参见https://docs.djangoproject.com/en/2.0/topics/forms/modelforms/#the-save-method

To be able to set only a few fields you should update your model declaration, with for example null=True, Blank=True, default=None in the optional fields arguments. 为了仅设置几个字段,您应该更新模型声明,例如在可选字段参数中使用null=True, Blank=True, default=None

PS : the django documentation is transalated in many languages, but if you don't find yours try the IRC channels. PS:django文档已翻译成多种语言,但如果找不到,请尝试使用IRC频道。

If I understand your problem clearly, 如果我清楚地了解您的问题,
You have predecided the place and the title and want the user to enter only the image. 您已预先确定地点和标题,并希望用户仅输入图像。
Only image should be kept in the form, but you want to enter the title and the place in the view. 表单中应仅保留图像,但您要在视图中输入标题和位置。
If that's the case,do this : 如果是这样,请执行以下操作:

Your view function: 您的查看功能:

def some_view(request):
    if request.method == "POST":

        T,P = get_title_and_place() 
        # This fuction will return a tuple with the title and the place that you need.
        # Or Alternatively, you can pass the title and place as argument to the view

        obj = Picture(title=T,place=P)
        #Initialise object with title and place received from function or arguments

        pic_form = PictureForm(request.POST, request.FILES)
        #The form contains only the image field as in your last block of code

        if pic_form.is_valid():
            obj.image = request.FILES['image']
            obj.save()
            #Save the object
            return redirect('some_url')

        else:          
           return render('xyz.html',{"form":pic_form})
           #Incoming image is invalid. Throw back the invalid form to the user

    else:
        #Incoming method is not POST, give user the form to fill the image
        pic_form = PictureForm()
        return render('xyz.html',{"form:pic_form})

On submission of the form from xyz.html, you should redirect back to this view. 从xyz.html提交表单后,您应该重定向回该视图。
This is the reason why I made a seperate function to get the title and place so that user doesn't know about it via the url. 这就是为什么我制作了一个单独的函数来获取标题和位置的原因,以便用户无法通过url知道标题和位置。


However be careful with this method. 但是,请谨慎使用此方法。 You have to take care of validating the title and place. 您必须注意验证标题和位置。 Otherwise the obj.save() will throw error 否则obj.save()会抛出错误

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM