如何给django中的提交按钮提供内部链接?

时间:2016-01-22 14:53:35

标签: python django django-templates

这是我的index.html页面的一部分,它生成一个from:

<form id="category_form" method="post" action="/wiki/">

            {% csrf_token %}


            {% for field in form %}
                {{ field.errors }}
                {{ field.help_text }}
                {{ field }}
            {% endfor %}

           <input type="submit" name="submit" value="Create Category" />

当我点击提交按钮时,它存储输入的值我的模型。我现在想要做的是提供这个提交按钮的链接,这样当我点击它时,它必须输入输入到我的模型的值以及转到链接

我试过这样做:

<a href='content.html'>  <input type="submit" name="submit" value="Create Category" /></a>

content.html是另一个html视图。向content.html提供变量的view.py实际上处理在上面的表单中输入的值并将一些变量返回到content.html页面 下面是我的索引视图

def index(request):
    if request.method == 'POST':
        form = scrapform(request.POST)

        if form.is_valid():
            form.save(commit=True)
            return index(request)
        else:
            print ('from.errors')
    else:
        form = scrapform()

    return render(request, 'wiki/index.html', {'form': form})
下面的

是forms.py

LEVEL_CHOICES = (('beg','beginner'),('ind','inter'),('exp','expert'))
class scrapform(forms.ModelForm):
    subject = forms.CharField(help_text="please enter the subject you desire")
    level = forms.CharField(max_length=128,widget=forms.Select(choices=LEVEL_CHOICES))
    time = forms.IntegerField(initial=0)

    class Meta:
        model = scrap
        fields = '__all__'

下面是我的内容视图

def content(request):
    subject = scrap.objects.values_list('subject', flat=True).distinct()
    level = scrap.objects.values_list('level', flat=True).distinct()
    time = scrap.objects.values_list('time', flat=True).distinct()
    page = wikipedia.page(subject)
    title = page.title
    content = page.content
    summary = page.summary
    html = page.html
    wiki_dict = {'summary':summary,'content':content,'title':title,'html':html}

    return render(request, 'wiki/content.html',wiki_dict)

1 个答案:

答案 0 :(得分:1)

为什么不在views.py中使用redirect?除非链接是动态的,否则您应该能够在视图中轻松实现此目的:

from django.shortcuts import redirect
from django.core.urlresolvers import reverse

def index(request):
    if request.method == 'POST':
        form = scrapform(request.POST)

        if form.is_valid():
            # you don't actually need commit=True, that's the default behavior
            form.save()
            return redirect(reverse('url-for-content.html'))

redirectreverse的Django文档。