如何将信息从html表单传递到django视图

时间:2018-04-19 06:55:09

标签: django django-models django-forms django-views

我正在创建一个网站,用户可以关注某些股票,并根据他们所关注的内容查看新闻。

我有以下models.py:

register

以下是我的def register(request): if request.method == "POST": form = ProfileRegistrationForm(request.POST) if form.is_valid(): user = form.save() user.refresh_from_db() # load the profile instance created by the signal username = form.cleaned_data.get('username') raw_password = form.cleaned_data.get('password') user = authenticate(username=username, password= raw_password) login(request, user) return redirect(follow_stocks_post_registration) else: form = ProfileRegistrationForm() return render(request, 'core/register.html',{'form':form}) 视图,在注册该网站后,用户被重定向到另一个页面,他们可以在第一个时间跟踪股票:

Stock

现在,一旦重定向,我希望用户在我们的数据库中查看所有def follow_stocks_post_registration(request): all_stocks = Stock.objects.all() return render(request, 'core/post_registration_stock_following.html', {'all_stocks': all_stocks}) 的列表,并能够关注某些列表。

{%  extends 'core/base.html' %}

{% load crispy_forms_tags %}

{% block head %}
    <title>Next step follow stocks</title>
{% endblock %}

{%  block body %}
    <form action ="" method="post">
        {% for stock in all_stocks %}
            <input type="checkbox">{{ stock }}
            <br/>
        {% endfor %}
        <button type = "submit"></button>
    </form>


{% endblock %}

和post_registration_stock_following.html:

Stock

这会正确列出所有Stock,但如何在表单的总结中将用户选择的forms.py传递到另一个视图中?另外,如果我使用node('centos-small') { stage('Set Git Config'){ sh 'git config --global user.email "test@test.com"' sh 'git config --global user.name "ci-bot"' sh 'git config --global credential.helper cache' sh "git config --global credential.helper 'cache --timeout=3600'" } stage('Set Git Credentials'){ git credentialsId: 'JenkinsGit', url: '${TFS_REPO}' git credentialsId: 'Second', url: '${SECOND_REPO}' } stage('Syncronize TFS-SECOND'){ sh 'git clone --bare ${TFS_REPO} tfs' dir("tfs") { //add a remote repository sh 'git remote add --mirror=fetch second ${SECOND_REPO}' // update the local copy from the first repository sh 'git fetch origin --tags' // update the local copy with the second repository sh 'git fetch second --tags' // sync back the second repository sh 'git push second --all' sh 'git push second --tags' } } }

,我做错了吗?

1 个答案:

答案 0 :(得分:0)

您可以使用FormSet保存股票:

def follow_stocks_post_registration(request):
    if request.method == 'POST':
        StockModelFormSet = formset_factory(StockModelForm)
        formset = StockModelFormSet(request.POST)
        if formset.is_valid():
            request.user.profile.followed_stocks.add(form.save(commit=False))
    all_stocks = Stock.objects.all()

    return render(request, 'core/post_registration_stock_following.html', {'all_stocks': all_stocks})