Django messages framwork, возвращающие None при печати
Я новичок в django, я столкнулся с очевидной проблемой, которую я не могу решить, при успешной отправке формы я поместил сообщение на главную страницу, куда пользователь будет перенаправлен, проблема в том, что он не возвращает сообщение.см. ниже view:
def service(request):
form = GetStartedForm(request.POST or None)
if form.is_valid():
form.save()
x = messages.success(request, 'We have recorded your request and we will contact you soon!')
print(x)
print('Form Successfull!')
return HttpResponseRedirect(reverse_lazy('home'))
context = {'form': form}
return render(request, 'bluetec/service.html', context)
Форма:
class GetStartedForm(forms.ModelForm):
class Meta:
model = GetStarted
fields = '__all__'
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.fields['name'].widget.attrs.update({'size': 5, 'class': 'form-control', 'placeholder': 'Enter your name:'})
self.fields['phone_no'].widget.attrs.update({'size': 5, 'title': 'Phone No', 'class': 'form-control', 'placeholder': 'Enter your phone no:'})
self.fields['email'].widget.attrs.update({'size': 10, 'title': 'Email', 'class': 'form-control', 'placeholder': 'Enter your email:'})
self.fields['description'].widget.attrs.update({'size': 10, 'title': 'description', 'class': 'form-control', 'placeholder': 'Enter your projects description:'})
а html -
<body>
<div id="wrapper" >
{% include 'bluetec/messages.html' %}
<!-- header begin -->
<header class="{% block class %} header-light transparent scroll-light {% endblock class %}">
<div class="container">
<div class="row">
файл messages.html является
{% if messsages %}
{% for message in messages %}
<div class="alert alert-{{ message.tags }}" id="msg" role="alert">
{{ message }}
</div>
{% endfor %}
{% endif %}
Когда я печатаю значение x, чтобы посмотреть, что он возвращает, он возвращает "None" и "Form Successfull". Я перепробовал много ответов, но ни один не указывает на мою проблему. Я не знаю, в чем проблема. Любая помощь будет признательна,
#you can use in views.py like this
form.save()
messages.success(request, 'Your message')
return HttpResponseRedirect(reverse_lazy('home'))
#and in html template like this
{% for msg in messages %}
<div class="alert {{msg.tags}} alert-dismissible fade show" role="alert">
<strong>{{msg}}</strong>
<button type="button" class="close" data-dismiss="alert" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
{% endfor %}
#tags will show type of message like success, error, warning...etc
{{msg.tags}}
#this will show the your custom text message sent from views
{{msg}}
#i guess there is no need for this
{% if messsages %} #it should be messages
{% endif %}
#hope this works for you
Вот проблема
x = messages.success(request, 'We have recorded your request and we will contact you soon!')
Просто поместите сообщение следующим образом:
messages.success(request, 'We have recorded your request and we will contact you soon!')
Вы не должны присваивать сообщение переменной
проблема была в том, что я не использовал cdn и использовал платный шаблон, в котором не использовался класс alert, поэтому я экспортировал cdn в начало всего импорта, чтобы он не переопределял уже переопределенные стили, это решило мою проблему