Django 请帮我在 html 页面上放置一个复选框和一个带有发送按钮的邮箱

Django Please help me place a checkbox and a mail box with a send button on the html page

我的训练项目中的功能之一:

  1. 通过复选框和电子邮件订阅新闻。
  2. 每天发送时事通讯。
  3. 用户可以通过取消选中复选框来取消订阅其个人资料中的邮件列表。

碰巧我首先为 booleanfield = true 的用户设置了每日简报。 为此,我在管理面板中标记了复选框。有用。 现在需要将复选框和邮件字段添加到新闻页面。 我坚持最简单的。又累又迷茫。 请帮我在新闻页面上放置一个复选框和一个带有发送按钮的邮箱

models.py

class Profile(models.Model):
user = models.OneToOneField(settings.AUTH_USER_MODEL,
                            on_delete=models.CASCADE)
hr = models.BooleanField(default=False)
subscribed_for_mailings = models.BooleanField(default=False)
subscription_email = models.EmailField(default="")

def __str__(self):
    return str(self.user)

Forms.py

class MailingForm(forms.ModelForm):
    class Meta:
        model = models.Profile
        fields = ('subscription_email', 'subscribed_for_mailings', )
        widgets = {
            'subscription_email': forms.EmailInput(attrs={"placeholder": "Your Email..."}),
            'subscribed_for_mailings': forms.CheckboxInput,
        }

views.py

    def all_news(request):
    today = date.today()
    today_news = models.TopNews.objects.filter(created__gte=today)
    return render(request, "news.html",
                  {'today_news': today_news})


def mailing_news(request):
    if request.method == 'POST':
        mailing_form = forms.MailingForm(request.POST)
        if mailing_form.is_valid():
            mailing_form.save()
            return HttpResponse('You will receive news by mail')
    else:
        mailing_form = forms.MailingForm()
        return render(request, "news.html", {'mailing_form': mailing_form})

urls.py

...
path('news/', views.all_news, name='all_news'),
...

news.html

{% extends 'base.html' %}

{% block title %}
    News
{% endblock %}

{% block body %}
    <h1>Last news</h1>
    {% for news in today_news%}
        <h3>{{ news.title }}</h3>
        <a href="{{ news.link }}">Read this news</a>
        <p>
              {{ news.created }}
        </p>
        <hr>
    {% endfor %}

<h4>I want to receive news by mail</h4>
        <form action="." method="post">
            {{ mailing_form.as_p }}
            {% csrf_token %}
            <label>
                <input type="submit" value="Subscribe">
            </label>
        </form>

{% endblock %}

页面显示新闻列表,只有“发送”按钮。没有复选框和邮件字段 enter image description here

你需要在 mailing news 中更改 subscribed_for_mailings,像这样

def mailing_news(request):
if request.method == 'POST':
    mailing_form = forms.MailingForm(request.POST)
    if mailing_form.is_valid():
        profile = mailing_form.save(commit=False) ####
        profile.subscribed_for_mailings = mailing_form.cleaned_data.get('subscribed_for_mailings') ####
        profile.subscription_email = mailing_form.cleaned_data.get('subscription_email') ####
        profile.save() #### new_line

        return HttpResponse('You will receive news by mail')
else:
    mailing_form = forms.MailingForm()
    return render(request, "news.html", {'mailing_form': mailing_form})

您可以在 cleaned_data.get('....')

中更改

最后我以不同的方式实现了这个功能:

forms.py

class MailingForm(forms.ModelForm):
class Meta:
    model = models.Profile
    fields = ('subscribed_for_mailings', 'subscription_email', )

views.py

@login_required
def mailing_news(request):
    if request.method == "POST":
        mailing_form = forms.MailingForm(request.POST,
                                             instance=request.user.profile,
                                             )
        if mailing_form.is_valid():
            mailing_news = mailing_form.save(commit=False)
            mailing_news.subscribed_for_mailings = mailing_news.subscribed_for_mailings
            mailing_news.subscription_email = mailing_news.subscription_email
            mailing_news.save()

            return render(request, "subscribe_complete.html",
                          {"mailing_news": mailing_news})
    else:
        mailing_form = forms.MailingForm()
    return render(request, 'subscribe.html', {"mailing_form": mailing_form})

news.html

    {% extends 'base.html' %}

{% block title %}
    News
{% endblock %}
{% block body %}
    <h1>Last news</h1> {{ news.created }}
    {% for news in today_news%}
        <h3>{{ news.title }}</h3>
        <a href="{{ news.link }}">Read this news</a>
        <hr>
    {% endfor %}

<a href="{% url 'basis:subscribe' %}">I want to receive news by mail</a>

{% endblock %}

urls.py

...
path('subscribe/', views.mailing_news, name='subscribe')
...

news.html

    {% extends 'base.html' %}

{% block title %}
    News
{% endblock %}
{% block body %}
    <h1>Last news</h1> {{ news.created }}
    {% for news in today_news%}
        <h3>{{ news.title }}</h3>
        <a href="{{ news.link }}">Read this news</a>
        <hr>
    {% endfor %}

<a href="{% url 'basis:subscribe' %}">I want to receive news by mail</a>

{% endblock %}

subscribe.html

{% extends 'base.html' %}

{% block title %}
    Subscribe
{% endblock %}

{% block body %}
        <form action="." method="post" enctype="multipart/form-data">
            {% csrf_token %}
            {{ mailing_news.as_p }}
                {% if user.profile.subscribed_for_mailings is True %}
                    <input type="checkbox" name="subscribed_for_mailings" id="id_subscribed_for_mailings" checked="">
                    If you don't want to receive emails anymore, uncheck
                    <br>
                    Subscription email: <input type="email" name="subscription_email" value={{ user.profile.subscription_email }} class="vTextField" maxlength="254" id="id_subscription_email">
                {% else %}
                    <label>
                        <input type="checkbox" name="subscribed_for_mailings" id="id_subscribed_for_mailings">
                        I want to subscribe for mailing news
                    </label>
                    <p><label>
                        Send news on my email:
                        <input type="email" name="subscription_email" class="vTextField" maxlength="254" id="id_subscription_email">
                    </label></p>

                {% endif %}
            <p><input type="submit" value="Update"></p>
        </form>

{% endblock %}

subscribe_complete.html

{% extends 'base.html' %}

{% block title %}
    Subscribing complete
{% endblock %}

{% block body %}
    <h3>Hi {{ user.username }}</h3>

    Thanks for subscribing.
    You will receive daily news by email: {{ user.profile.subscription_email }}

{% endblock %}