上下文未打印Django

时间:2019-03-14 18:24:19

标签: python django

我知道我的问题可能是缺乏Django知识,但是我试图将用户输入从视图中的一种形式传递到另一种视图,然后将使用给定的输入呈现该视图的HTML页面。 / p>

我被重定向好了,但是没有显示数据。我认为这与无法正确传递上下文有关,但是我不明白哪里出了问题或如何解决。

views.py

def home_view(request, *args, **kwargs):
    print(args, kwargs)
    print(request.user)
    if request.method == 'POST':
        form2 = PostForm(request.POST)
        if form2.is_valid():
            post = form2.save(commit=False)
            post.poster = request.user
            post.content = form2.cleaned_data.get('content')
            post.title = form2.cleaned_data.get('title')
            post.syntax = form2.cleaned_data.get('syntax')
            post.public = form2.cleaned_data.get('public')
            rand = str(uuid.uuid4())[:6]
            while Paste.objects.filter(generated_url=rand):
                rand = str(uuid.uuid4())[:6]
            post.generated_url = rand
            form2.save()
            context = {
                "poster_name": post.poster,
                "paste_contents": post.content,
                "paste_title": post.title,
                "paste_syntax": post.syntax,
                "paste_visible": post.public
            }
            return HttpResponseRedirect(reverse('details', args=(post.generated_url,)), context)
    else:
        form2 = PostForm()

    return render(request, "home.html", {'form2': form2})
def detail_view(request, *args, **kwargs):

    if request.user.is_authenticated:
        if request.method=='POST':
            form3 = PostForm(request.POST)
            url = form3.generated_url
            your_posts = Paste.objects.get(url)
            context = {
                'form3': form3
            }
            return render(request, "paste_detail.html", context)

    return render(request, "paste_detail.html", {'form3': form3})

home.html

{% extends "base.html" %}

{% block content %}
<h1>Your user is {{ request.user }}</h1>
<div class="submit_form">
<form action="" method="POST">
  {% csrf_token %}
  {{ form2.as_p }}<br>
  <input type="submit" name="submit" value="Paste" id="submit">
</div>

{% endblock content %}

还有paste_detail.html

{% extends "base.html" %}
{% block content %}
<!--<h1>Name of post: {{ post.title }}</h1>-->

<p>Content of post:</p>
I AM REDIRECTED
<h1>Name of post: {{ form2.title }}</h1>

<p>Content of post:</p>

<p>{{form3.content|linebreaks}}</p>
{{ form3.poster }}
{{ form3.contents }}
{{ form3.title }}
{{ form3.syntax }}
{{ form3.visible }}
{% endblock %}

编辑:

views.py

def home_view(request, *args, **kwargs):

    if request.method == 'POST':
        form2 = PostForm(request.POST)
        if form2.is_valid():
            post = form2.save(commit=False)
            post.poster = request.user
            post.save()
            rand = str(uuid.uuid4())[:6]
            while Paste.objects.filter(generated_url=rand):
                rand = str(uuid.uuid4())[:6]
            post.generated_url = rand
        #    return HttpResponseRedirect(reverse('details', args=(post.generated_url,)), context)
            return redirect('detail', rand)
    else:
        form2 = PostForm()

    return render(request, "home.html", {'form2': form2})
def detail_view(request, custom_uuid):

    post = get_object_or_404(Paste, pk=pk)
    return render(request, "paste_detail.html", {'post': post})
    #return render(request, "paste_detail.html", {'form3': form3})

paste_detail.html

{% extends "base.html" %}
{% block content %}


<p>Content of post:</p>
I AM REDIRECTED

<h1>Name of post: {{ post.title }}</h1>



<p>Creator of post:</p> {{ post.poster }}
<p>Content of post:</p> {{ post.content }}
<p>Title of post:</p> {{ post.title }}
{{ post.syntax }}
{{ post.visible }}
{% endblock %}

还有urls.py

...
urlpatterns = [
    path('home/', home_view, name='home'),
    path('contact/', contact_view, name='contact'),
    path('admin/', admin.site.urls, name='admin'),
    path('about/', about_view, name='about'),
    url(r'^signup/$', views.signup, name='signup'),
    path('paste_list/', paste_list_view, name='paste_list'),
    url(r'^$', home_view),
    #url(r'^(?P<rand_url>\S{6})/$', detail_view, name='details'),
    path('detail/<str:custom_uuid>/', detail_view, name='detail'),
    path('accounts/', include('django.contrib.auth.urls')),
]

2 个答案:

答案 0 :(得分:2)

上下文是每个请求的。返回视图后,上下文将不再存在。进行重定向时,您将完成该请求/响应周期,并使用title视图开始另一个请求/响应周期。任何上下文都不会延续。

相反,您需要一种在请求之间存储相关信息的方法。一种相当简单的方法是将数据存储在 session 中。

例如,您可以将home_view存储在request.session['title'] = post.title 中这样的会话中:

detail_view

然后在您的context = { 'title': request.session.get('title') } 视图中,可以将其添加到您的上下文中:

version: '2'
services:
  mockup:
    build: mockup/
    ports:
      - 12320:12320
    volumes:
      - /var/lib/tt/:/var/lib/tt/
    networks:
      - test

networks:
   test:
      driver: bridge
      ipam:
        config:
          - subnet: 172.20.1.0/24
            gateway: 172.20.1.1

有关会话的更多信息,请参阅Django文档:https://docs.djangoproject.com/en/2.1/topics/http/sessions/

答案 1 :(得分:2)

您的代码中有几个问题。让我们一个接一个地修复它们(请检查代码注释以获取解释):

home_view中,您正在做一些冗余代码,可以像这样简化:

from django.shortcuts import redirect

...
if request.method == 'POST':
    form2 = PostForm(request.POST)
    if form2.is_valid():
        post = form2.save(commit=False)  # it is not saved in db
        post.poster = request.user
        rand = str(uuid.uuid4())[:6]
        while Paste.objects.filter(generated_url=rand).exists():
            rand = str(uuid.uuid4())[:6]
        post.generated_url = rand
        post.save()  # it will save all information to DB, so you don't need to call form2.cleaned_data.get(..)

       return redirect('details', custom_uuid=rand)  # I am redirecting to `detail_view`. here `rand` is the random uuid of the post which is saved in db
else:
    form2 = PostForm()

return render(request, "home.html", {'form2': form2})  # rendering form for GET request

现在,让更新详细信息视图来捕获redirection

from django.shortcuts import get_object_or_404

def detail_view(request, custom_uuid):
    post = get_object_or_404(Post, generated_url=custom_uuid)  # getting the post object from database using model. 
    return render(request, "post_detail.html", {'post': post})  # sending data in context to template

# url
path('detail/<str:custom_uuid>/', detail_view, name='detail')  # here <str:custom_uuid> will catch the uuid sent in the url

# HTML
{% extends "base.html" %}
{% block content %}

<p>Content of post:</p>
I AM REDIRECTED
<h1>Name of post: {{ post.title }}</h1>  // <-- getting this context from view

<p>Content of post:</p>

<p>{{post.content|linebreaks}}</p>
{{ post.poster }}
{{ post.contents }}
{{ post.title }}
{{ post.syntax }}
{{ post.visible }}
{% endblock %}

在这里get_object_or_404获取模型Post的条目,如果未找到则抛​​出404错误。