In models.py,I created a character type field called "category".After the user enters the category name,it is saved in the database and now I want to display all the category names stored in the database.I created four category names.I can see all four in the database but when displaying it in the UI, I see NONE instead of the category names.
views.py,
def add_cat(request):
form = CatForm(request.POST or None)
context = {"form":form}
if form.is_valid():
instance = form.save(commit=False)
category = form.cleaned_data.get("category")
instance.category = category
instance.save()
messages.add_message(request, messages.INFO, 'Category Added')
return render(request,"add-cat.html",context)
forms.py,
class CatForm(forms.ModelForm):
class Meta:
model = Add_cat
fields = ['category']
My template file,
{% extends "admin-menu.html" %}
{% block content %}
{% load staticfiles %}
<head>
<link rel="stylesheet" href="{% static 'style.css' %}">
</head>
<h2 style="text-align: center;">Add Category</h2>
<form method="POST">
{% csrf_token %}
<table align="center">
{{form.as_table}}
</table>
<input type="submit" value="Add" style="margin-left: 48%;"/>
<input type="reset" value="Cancel"/>
</form>
{% if messages %}
<ul class="messages" style="list-style-type: none;">
{% for message in messages %}
<li{% if message.tags %} class="{{ message.tags }}"{% endif %}>{{ message }}</li>
{% endfor %}
</ul>
{% endif %}
 
<form id="id1">
{% for field in form %}
<table align="center">
<tr><th>Category Name</th></tr>
<tr><td>{{field.value}}</td></tr>
</table>
{% endfor %}
</form>
{% endblock %}
Try like this
def add_cat(request):
form = CatForm(request.POST or None)
catagories = <model>.objects.all()
context = {"form":form, 'categories':categories}
if form.is_valid():
instance = form.save(commit=False)
category = form.cleaned_data.get("category")
instance.category = category
instance.save()
messages.add_message(request, messages.INFO, 'Category Added')
return render(request,"add-cat.html",context)
In templates
{% for category in categories %}
<table align="center">
<tr><th>Category Name</th></tr>
<tr><td>{{ category }}</td></tr>
</table>
{% endfor %}
Related
One of functionality in my training project:
subscribe to the news by check-box and e-mail.
Send newsletter daily.
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>
Read this news
<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
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>
Read this news
<hr>
{% endfor %}
I want to receive news by mail
{% 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>
Read this news
<hr>
{% endfor %}
I want to receive news by mail
{% 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 %}
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('....')
I just want to put the username of the logged in user inside the author field and at the same time assign the author field as the user's username in the database.
def create_vacation(request):
form = creationForm(request.POST or None)
vacations = Vacation.objects.all()
vacations.author=request.user.username
if form.is_valid():
form.save()
return redirect('/vacations/all')
return render(request, 'creationForm.html', {'form': form})
and this is the vacation model
class Vacation(models.Model):
vacationInformation = models.TextField()
startDate= models.DateTimeField('start date')
endDate = models.DateTimeField('end date')
author = models.ForeignKey(User, null=True, on_delete=models.SET_NULL)
def __str__(self):
return self. vacationInformation
this is the form template
<form method="post" novalidate>
{% csrf_token %}
{% for hidden_field in form.hidden_fields %}
{{ hidden_field }}
{% endfor %}
{% if form.non_field_errors %}
<div class="alert alert-danger" role="alert">
{% for error in form.non_field_errors %}
{{ error }}
{% endfor %}
</div>
{% endif %}
{% for field in form.visible_fields %}
<div class="form-group">
{{ field.label_tag }}
{% if form.is_bound %}
{% if field.errors %}
{% render_field field class="form-control is-invalid" %}
{% for error in field.errors %}
<div class="invalid-feedback">
{{ error }}
</div>
{% endfor %}
{% else %}
{% render_field field class="form-control is-valid" %}
{% endif %}
{% else %}
{% render_field field class="form-control" %}
{% endif %}
{% if field.help_text %}
<small class="form-text text-muted">{{ field.help_text }}</small>
{% endif %}
{% if vacation %}
{% endif %}
</div>
{% endfor %}
<button type="submit" class="btn btn-primary">Submit</button>
</form>
I can render all of the vacation data in the homepage normally except for sure the author name
{% for vacation in vacations %}
<tr>
<td>{{ vacation.vacationInformation }}</td>
<td>{{ vacation.startDate }}</td>
<td>{{ vacation.endDate }}</td>
<td>{{ vacation.author }}</td>
It is giving me the entire user names in the author field in the form but I just want the user whom is logged in.
You need to get the currently logged in User. Then you can use the User to fill in the initial values in the form.
from django.contrib.auth import get_user
# ...
def create_vacation(request):
if request.method == 'POST':
form = creationForm(request.POST)
if form.is_valid():
form.save()
return redirect('/vacations/all')
else:
# Get the currently logged-in User.
user = get_user(request)
# Provide User as initial data to the form
form = creationForm(initial={'author': user})
return render(request, 'creationForm.html', {'form': form})
Relevant documentation:
ModelForm - Providing initial values
django.contrib.auth.get_user
I am working with inlineformset_factory and created a forms.BaseInlineFormSet to override the clean function to make some validations. the validation works and the form isn't accepted but the ValidationError message doesn't appear when the page is reloaded.
here is my form class:
class BaseDetailFormSet(forms.BaseInlineFormSet):
def clean(self):
super(BaseDetailFormSet, self).clean()
if any(self.errors):
return self.errors
for form in self.forms:
product = form.cleaned_data['product']
if form.cleaned_data['quantity_sold'] > product.quantity_in_stock:
raise forms.ValidationError(_('not enough products'))
DetailFormset = inlineformset_factory(Invoices,
InvoiceDetail,
fields=('product', 'quantity_sold'),
widgets= {'product': forms.Select(
attrs={
'class': 'search',
'data-live-search': 'true'
})},
formset=BaseDetailFormSet,
extra=1)
and my html code:
<form class="form-inline" method="post" action="">
{% csrf_token%}
{% include '_layouts/form_snippet.html' %}
<table class="table">
{{inlines.management_form}}
{%for form in inlines.forms%}
{% if forloop.first%}
<thead>
<tr>
{%for field in form.visible_fields%}
<th>{{field.label|capfirst}}</th>
{%endfor%}
{%endif%}
</tr>
</thead>
<tr class="formset_row">
{{ form.non_form_errors }}
{% for field in form.visible_fields %}
<td>
{# Include the hidden fields in the form #}
{% if forloop.first %}
{% for hidden in form.hidden_fields %}
{{ hidden }}
{% endfor %}
{% endif %}
{{ field }}
</td>
{% endfor %}
</tr>
{% endfor %}
</table>
<button type="submit" value="Add" class="btn btn-inverse">{% trans 'Submit Invoice' %}</button>
</form>
any ideas how to show the validation error message or why it isn't shown.
non_form_errors belongs to the formset not the form.
So you can display it with:
{{ formset.non_form_errors }}
Or in your case, since you use the variable inlines:
{{ inlines.non_form_errors }}
Since it belongs to the formset, you should do this outside of the forloop through the forms.
If you have errors on the form that don't belong to any field, then you access these with
{{ form.non_field_errors }}
I want to display the necessary field errors when the user who is populating the form does not enter valid information into the forms.
However, each I time I test the error script by clicking the submit button without populating any of the fields I get this error :
UnboundLocalError at /nesting/ local variable 'content' referenced
before assignment
How do I correct this?
This is my code :
veiws.py
from django.shortcuts import render, redirect
from django.views.generic import TemplateView
from nesting.forms import Identity_form
from nesting.models import Identity_unique
class Identity_view(TemplateView):
template_name = 'nesting/nesting.html'
def get(self, request):
form = Identity_form()
Identities = Identity_unique.objects.filter(user = request.user)
var = {'form': form, 'Identities': Identities}
return render(request, self.template_name, var)
def post(self, request):
form = Identity_form(request.POST or None)
if form.is_valid():
NIS = form.save(commit = False)
NIS.user = request.user
NIS.save()
content = form.cleaned_data['NIS']
form = Identity_form()
return redirect('nesting:nesting')
var = {'form': form, 'content': content}
return render(request,self.template_name, var)
The error messages is saying the error is caused by this line
var = {'form': form, 'content': content}
return render(request,self.template_name, var)
nesting.html
{% extends 'base.html' %}
{% load widget_tweaks %}
<html>
<head>
{% block head %}
<title>nesting</title>
{% endblock %}
</head>
<body>
{% block body %}
<div class = "container" style = "margin-top: 80px;">
<form method = 'post' novalidate>
{% csrf_token %}
{% for hidden_field in form.hidden_fields %}
{{ hidden_field }}
{% endfor %}
<div class = "col-sm-8 col-md-8 col-lg-6">
<p class = "font-weight-bold">Create Patient</p>
{% if form.non_field_errors %}
<div class = "alert alert-danger" role = "alert">
{% for error in form.non_field_errors %}
{{ error }}
{% endfor %}
</div>
{% endif %}
{% for field in form.visible_fields %}
<div class = "form-group">
{% if form.is_bound %}
{% if field.errors %}
{% render_field field class="form-control is-invalid" %}
{% for error in field.errors %}
<div class = "invalid-feedback ">
{{ error }}
</div>
{% endfor %}
{% else %}
{% render_field field class="form-control is-valid" %}
{% endif %}
{% else %}
{% render_field field class="form-control" %}
{% endif %}
{% if field.help_text %}
<small class = "form-text text-muted">{{ field.help_text }}</small>
{% endif %}
</div>
{% endfor %}
<button class = "btn-primary btn-large btn ">Submit</button>
</div>
</form>
</div>
<div class = "col-sm-8 col-md-6 col-lg-6">
{% for Identity in Identities %}
<div class = "card" style = "margin-top: 40px;">
<div class = "card-header">
<p class="font-weight-bold"> {{Identity.First_Name}} {{Identity.Last_Name}} </p>
</div>
<div class = "card-body">
<div class = "card-title">
<p class = "font-weight-light" style = "font-family: Optima">National Insurance Scheme : {{ Identity.NIS }}</p>
</div>
<p><small class = "card-text">Created On : {{ Identity.Timestamp }}</small></p>
<p><small class = "card-text">Address : {{ Identity.Residence }}</small></p>
</div>
</div>
{% endfor %}
</div>
</div>
{% endblock %}
</body>
</html>
In your views. content is referenced in var = {'form': form, 'content': content}. It is only instantiated after if form.is_valid() block.
The unboundError occurs when your form is invalid, then the var = {'form': form, 'content': content} does not have any variable named content to refer to.
The Fix: instantiate content before the if form.is_valid() block.
content = None
I'm doing a function to upload a file with a example that I found here on Stack Overflow, everything works fine, the problem is that when I try to access the document by a URL, the click sends me to the app url not the photo url, for example I'm trying to access to this
http://localhost:8000/media/documents/2013/10/01/Desert.jpg
and it should be the image URL
documents/2013/10/01/Desert.jpg
view.py
def list(request):
# Handle file upload
if request.method == 'POST':
form = DocumentForm(request.POST, request.FILES)
print form
if form.is_valid():
newdoc = Document(docfile=request.FILES['docfile'],credencial_miembro=request.POST['credencial_miembro'])
print newdoc
newdoc.save()
# Redirect to the document list after POST
return HttpResponseRedirect(reverse('expmedico.views.list'))
else:
form = DocumentForm() # A empty, unbound form
# Load documents for the list page
documents = Document.objects.all()
# Render list page with the documents and the form
return render_to_response(
'upload.html',
{'documents': documents, 'form': form},
context_instance=RequestContext(request)
)
forms.py
class DocumentForm(forms.Form):
docfile = forms.FileField(
label='Select a file',
help_text='max. 42 megabytes'
)
credencial_miembro=forms.CharField(max_length=20)
model.py
class Document(models.Model):
docfile = models.FileField(upload_to='documents')
credencial_miembro= models.CharField(max_length=20,null=False, blank=False)
ulr
url(r'^list/$', 'expmedico.views.list',name='list'),
Setting.py
MEDIA_ROOT = os.path.join(RUTA_PROYECTO, 'media')
MEDIA_URL = '/media/'
template.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Minimal Django File Upload Example</title>
</head>
<body>
<!-- List of uploaded documents -->
{% if documents %}
<ul>
{% for document in documents %}
<li>{{ document.docfile.name }}</li>
{% endfor %}
</ul>
{% else %}
<p>No documents.</p>
{% endif %}
<!-- Upload form. Note enctype attribute! -->
<form action="{% url list %}" method="post" enctype="multipart/form-data">
{% csrf_token %}
<table style="width:150%;">
<div style="text-align:center; font-style: oblique; color: red" >
{% if messages %}
<ul class="messages">
{% for message in messages %}
<li{% if message.tags %} class="{{ message.tags }}"{% endif %}><b>{{ message }}</b></li>
{% endfor %}
</ul>
{% endif %}
</div>
<tr>
<td><label>Fecha:</label></td>
<td>
<output><b>{% now "D d M Y" %}</b></output>
</td>
<td>{{ form.credencial_miembro.errors }}<label>Credencial:</label></td>
<td>{{ form.credencial_miembro }} </td>
</tr>
</table>
<p>{{ form.non_field_errors }}</p>
<p>{{ form.docfile.label_tag }} {{ form.docfile.help_text }}</p>
<p>
{{ form.docfile.errors }}
{{ form.docfile }}
</p>
<p><input type="submit" value="Upload" /></p>
</form>
</body>
</html>
You are accessing a model not an image. Also, this might help:
https://docs.djangoproject.com/en/1.2/howto/static-files/
Please take a look there as i don't see this added to the urls.py you pasted.