ValueError в приложении Django Python Forum - PullRequest
0 голосов
/ 12 октября 2019

Я пытаюсь создать форму, в которой пользователи могут добавлять новые темы в категории. Тогда пользователи смогут комментировать каждую тему. Все работало до тех пор, пока я не попытался добавить страницу формы для new_topic

Полученная ошибка:

ValueError at / new_topic / Представление speak_space.views.new_topic не возвращало объект HttpResponse. Вместо этого он вернул None.

Вот код для моих файлов view.py и urls.py:

view.py

from django.shortcuts import render, redirect

from .models import Category
from .models import Topic
from .forms import TopicForm

def index(request):
    """The home page for speak_space"""
    return render(request, 'speak_space/index.html')

def categories(request):
    """Show all categories."""
    categories = Category.objects.order_by('date_added')
    context = {'categories': categories}
    return render(request, 'speak_space/categories.html', context)

def category(request, category_id):
    """Show a single category(tribe) and all of its topics(convos)."""
    category = Category.objects.get(id=category_id)
    topics = category.topic_set.order_by('-date_added')
    context = {'category': category, 'topics': topics}
    return render(request, 'speak_space/category.html', context)

def topics(request):
    """Show all topics within a category(tribe)."""
    topics = Topic.objects.order_by('date_added')
    context = {'topics': topics}
    return render(request, 'speak_space/topics.html', context)

def topic(request, topic_id):
    """Show a single topic(convo/post) and all of it's replies."""
    topic = Topic.objects.get(id=topic_id)
    entries = topic.entry_set.order_by('-date_added')
    context = {'topic': topic, 'entries': entries}
    return render(request, 'speak_space/topic.html', context)

def new_topic(request):
    """Add a new conversation topic."""
    if request.method != 'POST':
        # No data submitted; create a blank form.
        form = TopicForm()
    else:
        # POST data submitted; process data.
        form = TopicForm(data=request.POST)
        if form.is_valid():
            form.save()
            return redirect('speak_space:topics')

        # Display a blank or invalid form.
        context = {'form': form}
        return render(request, 'speak_space/new_topic.html', context)

и вот мой файл URL:

from django.urls import path

from . import views

app_name = 'speak_space'
urlpatterns = [
    # Home page
    path('', views.index, name='index'),

    # Page that shows all categories
    path('categories/', views.categories, name='categories'),

    # Profile page for a category
    path('categories/<int:category_id>/', views.category, name='category'),

    # Page that shows all topics.
    path('topics/', views.topics, name='topics'),

    # Detail page for a single topic(conversation)
    # Where you go after you click on someones post
    path('topics/<int:topic_id>/', views.topic, name='topic'),

    # Page for adding a new conversation topic
    path('new_topic/', views.new_topic, name='new_topic'),
 ]

и страница моих форм:

from django import forms

from .models import Topic

class TopicForm(forms.ModelForm):
    class Meta:
        model = Topic
        fields = ['text']
        labels = {'text': ''}

Ответы [ 2 ]

1 голос
/ 12 октября 2019

Ваш new_topic просмотр ничего не возвращает в случае запроса GET. Вы должны сделать return общее заявление:

def new_topic(request):
    """Add a new conversation topic."""
    if request.method != 'POST':
        # No data submitted; create a blank form.
        form = TopicForm()
    else:
        # POST data submitted; process data.
        form = TopicForm(data=request.POST)
        if form.is_valid():
            form.save()
            return redirect('speak_space:topics')

    # The changes are here, now return will work for all requests types POST and GET
    context = {'form': form}
    return render(request, 'speak_space/new_topic.html', context)
0 голосов
/ 12 октября 2019

Определите следующие строки

# Display a blank or invalid form.
context = {'form': form}
return render(request, 'speak_space/new_topic.html', context)

внутри вашего new_topic метода.

...