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

Time:10-23

One of functionality in my training project:

  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.

It so happened that first I set up a daily newsletter for users who have booleanfield = true. For it I marked the checkboxes in the admin panel. It works. Now it is necessary to add the checkbox and the mail field to the news page. I'm stuck on the simplest. Tired and confused. Please help me place a checkbox and a mail box with a send button on the news page

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

The page displays a list of news and only the "send" button. There is no check-box and a field for mail enter image description here

CodePudding user response:

Finally I realized this functionality in a different way:

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

CodePudding user response:

you need to change subscribed_for_mailings in mailing news, like this

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

you can change in cleaned_data.get('....')

  • Related