djang的两个模型

2024-04-24 11:43:50 发布

您现在位置:Python中文网/ 问答频道 /正文

我在学Django,所以我不知道这个。你知道吗

我有两张桌子。你知道吗

  1. 表BlogPost:保存所有帖子。你知道吗
  2. 表Categoria:保存register post类别的ID。你知道吗

我的型号.py

class BlogPost(models.Model):

    title=models.CharField(max_length=150)
    author = models.ForeignKey(User)
    categorias_post = models.ManyToManyField(Categoria)
    body = RichTextField(('Content of post'))
    creada_en = models.DateTimeField(auto_now_add=True)
    actualizada_al = models.DateTimeField(auto_now=True)

我的表单.py

class FormularioPost(forms.ModelForm):

    class Meta:
        model = BlogPost
        fields = ('title', 'author', 'categorias_post', 'body')

我的视图.py

def postregistrado(request):

    if request.method == "POST":
        form = FormularioPost(request.POST)
        if form.is_valid():
            post = form.save(commit=False)
            post.author = request.user
            post.save

        messages.success(request, 'Su post ha sido registrado con éxito.')
    else:
        form = FormularioPost()

    return render_to_response(
        "postRegistrado.html",
        locals(),
        context_instance=RequestContext(request),
        )

我想从同一个views.py插入两个不同的表。有人能帮我吗?你知道吗


Tags: pyformautotitlemodelsrequestbodypost
1条回答
网友
1楼 · 发布于 2024-04-24 11:43:50

使用commit=False时,必须显式调用save_m2m()来保存多对多字段。你知道吗

if form.is_valid():
    post = form.save(commit=False)
    post.author = request.user
    post.save() #Note that it is a function call.  
    post.save_m2m()

您可以在documentation here中阅读更多关于此的内容

Another side effect of using commit=False is seen when your model has a many-to-many relation with another model. If your model has a many-to-many relation and you specify commit=False when you save a form, Django cannot immediately save the form data for the many-to-many relation. This is because it isn’t possible to save many-to-many data for an instance until the instance exists in the database.

To work around this problem, every time you save a form using commit=False, Django adds a save_m2m() method to your ModelForm subclass. After you’ve manually saved the instance produced by the form, you can invoke save_m2m() to save the many-to-many form data.

另一件事是,确保在这个视图中添加^{} decorator,这样当post.author = request.user对匿名用户求值时就不会遇到奇怪的问题

相关问题 更多 >