为什么我的更新URL链接将我踢到CreateNew html视图

时间:2018-03-18 00:48:56

标签: django django-forms django-views

所以这是我之前的stackoverflow帖子上的一个标记:

asynchronous delegate type

我想我已经把它缩小了。发生的事情是,当我点击链接更新我的视图时,它会将我发送到“创建新”页面。我的问题是,我无法弄清楚为什么这样做。

感谢任何和所有帮助。

这是代码:

question_form.html

{% extends "base.html" %}
{% load bootstrap3 %}
{% block content %}
<h4>Create New Question</h4>
<form method="POST" action="{% url 'questions:create' %}" id="questionForm">
    {% csrf_token %}
    {% bootstrap_form form %}
    <input type="submit" value="Post" class="btn btn-primary btn-large">
</form>
{% endblock %}

question_update.html

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

<h4>Update Question</h4>
<form method="POST" action="{% url 'questions:update' pk=question.pk %}" id="questionForm">
    {% csrf_token %}
    {% bootstrap_form form %}
    <input type="submit" value="Update" class="btn btn-primary btn-large">
</form>
{% endblock %}

question_detail.html

{% block content %}
    this is the question detail view
<h3>{{ question.question_html|safe }}</h3>
<h3>{{ question.answer_html|safe }}</h3>
<a href="{% url 'questions:update' pk=question.pk %}"> Update Question</a>
{% endblock %}

urls.py

url(r'new/$', views.CreateQuestion.as_view(), name='create'),
url(r'questionupdate/(?P<pk>\d+)/$', views.QuestionUpdate.as_view(), name='update'),
url(r'questiondetail/(?P<pk>\d+)/$', views.QuestionDetail.as_view(), name='single'),

views.py

class CreateQuestion(generic.CreateView):
    model = models.Question
    form = QuestionForm
    fields = ('question', 'answer')
    success_url = reverse_lazy('questions:all')

    def form_valid(self, form):
        self.object = form.save(commit=False)
        self.object.user = self.request.user
        self.object.save()
        return super().form_valid(form)

class QuestionDetail(generic.DetailView):
    model = models.Question

class QuestionUpdate(generic.UpdateView):
    model = models.Question
    form_class = QuestionForm
    context_object_name = 'question'

2 个答案:

答案 0 :(得分:0)

从您的urls.py更新视图名称仅update。您只能在html文件中尝试更新标记,如

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

<h4>Update Question</h4>
<form method="POST" action="{% url 'update' pk=question.pk %}" id="questionForm">
    {% csrf_token %}
    {% bootstrap_form form %}
    <input type="submit" value="Update" class="btn btn-primary btn-large">
</form>
{% endblock %}

答案 1 :(得分:0)

我已经弄明白了。事实证明我错过了我的创建和更新视图下的模板名称部分,它将它们引导到他们自己的html模板:

class CreateQuestion(generic.CreateView):
    model = models.Question
    form_class = QuestionForm
    fields = ('question', 'answer')
    template_name = "questions/question_form_create.html"
    success_url = reverse_lazy('questions:all')

class QuestionUpdate(generic.UpdateView):
    model = models.Question
    form_class = QuestionForm
    template_name = "questions/question_form_update.html"