【问题标题】:How to link foreign key in a class based view in Django如何在 Django 的基于类的视图中链接外键
【发布时间】:2017-03-28 12:28:35
【问题描述】:
class IndexView(generic.ListView):
    template_name = "posts/index.html"

    def get_queryset(self):
        return Inspectionfile.objects.all()

class DetailView(generic.DetailView):
    model = Inspectionfile
    template_name = "posts/detail.html"


class createposts(CreateView):
    model = posts
    fields = ['title','comments']

通过 createposts 和使用表单,我可以填充标题和 cmets,但它们没有与任何 Inspectionfile(外键)链接。我希望用户无需选择即可链接。以下是我的模型。所以我想将每个帖子链接到一个特定的检查文件。

class Inspectionfile(models.Model):
    document_upload = models.FileField()
    document_type = models.CharField(max_length=10)
    document_title = models.CharField(max_length=250)
    document_check = models.CharField(max_length=250)

    def __str__(self):
        return (self.document_title + self.document_type)


class posts(models.Model):
    inspectionfile = models.ForeignKey(Inspectionfile, on_delete=models.CASCADE, default=1)
    title = models.CharField(max_length=120)
    comments = models.TextField()
    flag = models.BooleanField(default=False)

    def get_absolute_url(self):
        return reverse('posts_form', kwargs={'pk': self.pk})

    def __str__(self):
        return self.title 

form 是一个简单的模板:

<form class = "form_horizontal" action = "" method = "post">
    {% csrf_token %}
    {{form.as_p}}
    <button type="submit">Submit</button>
</form>

【问题讨论】:

  • 您需要在此处发布表格以获得帮助
  • 您如何选择新帖子所需的Inspectionfile
  • 这是通过索引模板完成的,因为它通过主键进入特定文件。因此,当您单击文件时,它会转到表单页面,但帖子根本没有连接到我的问题

标签: python django django-views django-generic-views


【解决方案1】:

我认为您需要在 createposts 视图中覆盖 post 方法:

def post(self, request, *args, **kwargs):
    current_inspectionfile = Inspectionfile.objects.get(pk= 
                      #enter id of current file. If id is 
                      #parameter in url then use self.kwargs['file_id'], 
                      #where file_id is name of parameter in url
                      )
    new_post = posts.objects.create(inspectionfile=current_inspectionfile, 
                      #and arguments from the form
                      )
    return new_post

和题外话:python 中的类名通常以单数形式在 CamelCase 中调用。所以class Post(models.Model)class CreatePost(CreateView):

【讨论】:

  • 谢谢,这是有道理的。但是当您说表单参数时,您会看到我没有实际的 form.py ,有没有办法从模板中提取帖子属性。
  • @IshanSubedi 检查this。我所说的“表单”是指模板中的表单。
  • 你知道我为什么一直收到:'posts' 对象没有属性 'get' 错误。 url.py 似乎很好。是不是因为,因为我们正在创建一个新对象 new_post 并且它不知道如何处理它?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-08-29
  • 2018-05-14
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多