Django Помогите пожалуйста разместить чекбокс и почтовый ящик с кнопкой отправки на html странице

Одна из функциональных возможностей в моем учебном проекте:

  1. subscribe to the news by check-box and e-mail.
  2. Send newsletter daily.
  3. The user can unsubscribe from the mailing list in his profile by unchecking the checkbox.

Так получилось, что сначала я настроил ежедневную рассылку для пользователей, у которых booleanfield = true. Для этого я отметил чекбоксы в панели администратора. Все работает. Теперь необходимо добавить чекбокс и поле mail на страницу новостей. Я застрял на самом простом. Устала и запуталась. Помогите пожалуйста разместить чекбокс и почтовое поле с кнопкой отправки на странице новостей

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 %}

На странице отображается список новостей и только кнопка "отправить". Отсутствует флажок и поле для почты Введите описание изображения здесь

вам нужно изменить subscribed_for_mailings в mailing news, вот так

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 %}
Вернуться на верх