[英]How to include an object from another model in a generic Django CreateView?
Ok so I am trying to include the corrosponding Comment in my createAnswer View currently the url of the createAnswer page includes the pk ok the right comment so i need to get the comment by the id in the url. 好的,所以我试图在我的createAnswer视图中包含相应的注释,当前createAnswer页面的URL包含pk ok正确的注释,因此我需要通过URL中的ID来获取注释。
My generic CreateView looks like this: 我的通用CreateView看起来像这样:
class createAnswer(CreateView):
model = Answer
fields = ['content']
def getComment(self, request):
???
comment = getComment()
def get_success_url(self):
this_path = self.request.get_full_path()
path_list = this_path.split('/')
def get_comment_id(self):
for i in range(len(path_list)):
if path_list[i].isdigit():
return path_list[i]
return '/blogcontact/comment/'+ get_comment_id(self)
def form_valid(self,form):
this_path = self.request.get_full_path()
path_list = this_path.split('/')
def get_comment_id(self):
for i in range(len(path_list)):
if path_list[i].isdigit():
return path_list[i]
form.instance.author = self.request.user
form.instance.comment = Comment.objects.get(id=get_comment_id(self))
return super().form_valid(form)
My Urls.py looks like this: 我的Urls.py看起来像这样:
from django.urls import path
from . import views
from .views import createAnswer
urlpatterns = [
path('contact/comment/<int:pk>/newanswer', createAnswer.as_view(),
name='answer-create')
]<br>
I would like to save the Comment object in a variable so i Can use it in the html template like this {{comment}} 我想将Comment对象保存在变量中,以便可以在{{comment}}这样的html模板中使用它
I think you you are confusing the function views and the Class Based Views (CBV), and you never import a request, it is just a parameter your views receive. 我认为您使函数视图和基于类的视图(CBV)混淆,并且您从不导入请求,它只是视图接收的参数。
In a function view you do the following: 在功能视图中,执行以下操作:
def my_view(request):
if request.method == 'POST':
# do some stuff
For CBV each method is a function: 对于CBV,每种方法都是一个函数:
from django.views.generic.edit import CreateView
class MyView(CreateView):
model = Answer
fields = ['content']
def get(self, request):
# do some stuff
def post(self, request):
# do some stuff
EDIT: To access the url parameters in class based views use self.kwargs, so you would access the comment pk by doing self.kwargs['pk']. 编辑:要在基于类的视图中访问url参数,请使用self.kwargs,因此您可以通过self.kwargs ['pk']访问注释pk。 Now you just need to get the comment and add it to the context data: 现在,您只需要获取注释并将其添加到上下文数据中:
class CreateAnswer(CreateView):
model = Answer
fields = ['content']
def get_context_data(self, **kwargs):
kwargs['comment'] = Comment.objects.get(pk=self.kwargs['pk'])
return super().get_context_data(**kwargs)
def form_valid(self, form):
# do some stuff
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.