Django Form Field not showing up - python

I just started learning Django and for this project I'm following the "Tango with Django" tutorial book. I have a problem with the input field of a form not showing up, while the button seems to be rendered fine.
Here's my code:
models.py
[...]
class Idea(models.Model):
keyword = models.ForeignKey(Keyword)
word = models.CharField(max_length=120)
count = models.IntegerField(default=1)
def __str__(self):
return self.word
forms.py
[...]
class Meta:
model = Keyword
fields = ('name',)
class IdeaForm(forms.ModelForm):
word = forms.CharField(max_length=120)
count = forms.IntegerField(widget=forms.HiddenInput(), initial=1)
class Meta:
model = Idea
fields = ('word',)
exclude = ('keyword',)
views.py
[...]
def keyword_detail(request, keyword_name_slug):
form = IdeaForm()
context_dict = {}
try:
keyword = Keyword.objects.get(slug=keyword_name_slug)
ideas = Idea.objects.filter(keyword=keyword)
context_dict['keyword'] = keyword
context_dict['ideas'] = ideas
except Keyword.DoesNotExist:
context_dict['keyword'] = None
context_dict['ideas'] = None
if request.method == 'POST':
form = IdeaForm(request.POST)
if form.is_valid():
idea = form.save(commit=False)
idea.keyword = keyword
idea.count = 1
idea.save()
return keyword_detail(request, keyword_name_slug)
else:
print(form.errors)
context_dict['form'] = form
return render(request, 'openminds/keyword.html', context_dict)
keyword.html
[...]
<h3>Add a new Idea</h3>
<div>
<form id="idea_form" method="post" action="">{% csrf_token %}
{% for hidden in forms.hidden_fields %}
{{ hidden }}
{% endfor %}
{% for field in forms.visible_fields %}
{{ field.errors }}
{{ field }}
{% endfor %}
<input type="submit" name="submit" value="Add Idea" />
</form>
</div>

I think you're passing in form to the template, but attempting to use forms.

Related

Select a valid choice. ... is not one of the available choices

I am trying to create a simple Django 2.2 application with single model, single model form + custom field and a simple CreateView. I am populating the choices dynamically based on a http call to a outside url. The dropdown is populated fine, but when I try to submit my form I am getting an error:
Select a valid choice. ... is not one of the available choices and the form is refreshed with new 3 suggestions in the dropdown.
models.py
class GhostUser(models.Model):
first_name = models.CharField("User's first name", max_length=100, blank=False)
last_name = models.CharField("User's last name", max_length=100, blank=False)
ghost_name = models.CharField("User's ghost name", max_length=100, blank=False)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
def __str__(self):
return f"{self.ghost_name}"
def get_absolute_url(self):
return reverse('ghost_names:ghost-update', kwargs={'id': self.id})
views.py
class GhostCreateView(CreateView):
template_name = 'ghost_create.html'
form_class = GhostUserForm
success_url = '/'
# def get_context_data(self, **kwargs):
# data = super().get_context_data(**kwargs)
# url = "https://donjon.bin.sh/name/rpc-name.fcgi?type=Halfling+Male&n=3"
# resp = urllib.request.urlopen(url)
# names = resp.read().decode('utf-8')
# data['ghost_suggestions'] = names.splitlines()
# return data
forms.py
class GhostUserForm(forms.ModelForm):
ghost_name = forms.ChoiceField(choices=[], widget=forms.Select())
class Meta:
model = GhostUser
fields = ['first_name', 'last_name']
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.fields['ghost_name'].choices = tuple(get_ghost_names())
def get_ghost_names():
url = "https://donjon.bin.sh/name/rpc-name.fcgi?type=Halfling+Male&n=10"
resp = urllib.request.urlopen(url)
data = resp.read().decode('utf-8').splitlines()
names = []
for name in data:
existing_ghosts = GhostUser.objects.filter(ghost_name=name)
if existing_ghosts:
continue
else:
print(name.split())
if len(name.split()) > 1:
name = name.split()[0]
names.append((name, name))
return names[:3]
html
{% block content %}
<form action="." method="POST">{% csrf_token %}
{% for field in form.visible_fields %}
<p>
{{ field.label_tag }}
{{ field }}
{{ field.errors }}
</p>
{% endfor %}
<input type="submit" value="Create ghost name">
</form>
{% comment %}{{ghost_suggestions}}
<select name="prefer_car_model" id="id_prefer_car_model" required>
<option value="0" selected disabled> Select ghost name </option>
{% for obj in ghost_suggestions %}
<option value="{{ obj }}">{{ obj }} </option>
{% endfor %}
</select>
{% endcomment %}
{% endblock content %}
What am I doing wrong here? I would appreciate your help on this weird for me issue.
P.S. When I add the commented out code from the view and template and render the fold fields one by one, the form submits without errors.
you did not mention the field name ghost_name in the form.py GhostUserForm class
change the line
fields = ['first_name', 'last_name'] to fields = ['first_name', 'last_name','ghost_name ']

Django - objects.all() shows nothing

I'm trying to get a list of objects in Django from a model.
I just want to get the list of 'dht node' from the request user, but it shows nothing in the html file (as if the list was empty). The user that I'm using has 2 'dht nodes' and they're shown in the django admin.
I don't know what is wrong, because if I use the instruction "member.dht.create(...)" in the views function and a create a new 'dht node' like this, this is shown. Only 'dht nodes' that I enter by form do not show. Can be the form?
Thanks a lot, Here's my code:
Models.py
class Node(models.Model):
name = models.CharField(primary_key=True, null=False, max_length= 50)
description= models.CharField(default=None, null=False, max_length= 250)
topic=models.CharField(default=None, null=False, max_length= 50, unique=True)
def __unicode__(self):
return self.name
class dht(Node):
temp = models.IntegerField(default=None, null=True)
hum = models.IntegerField(default=None, null=True)
class UserProfile(User):
uid = models.CharField(default=None, null=False, max_length= 250)
dht = models.ManyToManyField(dht, blank=True)
def __unicode__(self):
return self.user.username
Views.py -dht list-
#login_required(login_url = '/web/login')
def listDhtSensor(request):
member = request.user.userprofile
list = member.dht.all()
return render(request, 'web/listDhtSensor.html', {'list':list})
Html -listDhtSensor.html-
{% block content %}
{% for dht in list %}
{{ dht.name }}
{{ dht.topic }}
{% endfor %}
{% endblock %}
Forms.py
class newDHTSensorForm(forms.ModelForm):
class Meta:
model = dht
field = ['name',
'description',
'topic',]
labels = {'name': 'Name' ,
'description': 'Description',
'topic': 'Topic',}
exclude = ['temp', 'hum']
Views.py -dht form-
#login_required(login_url = '/web/login')
def newDHTSensor(request):
if request.method == "POST":
form = newDHTSensorForm(request.POST)
if form.is_valid():
post = form.save(commit=False)
post.save()
return redirect('/web/dhtDetail')
else:
form = newDHTSensorForm()
return render(request, 'web/newDhtSensor.html', {'form': form})
Html -newDhtSensor.html-
{% block content %}
<div class="boxReg">
<form method="post">
{% csrf_token %}
<h2>{{ form.name.errors.as_text }}</h2>
<p><label for="id_name">Name:</label> <input class="barraForm" type="text" name="name" maxlength="150" autofocus="" required="" id="id_name"></p>
<p><label for="id_description">Description:</label> <input class="barraForm" type="text" name="description" maxlength="150" id="id_description"></p>
<h2>{{ form.topic.errors.as_text }}</h2>
<p><label for="id_topic">Topic:</label> <input class="barraForm" type="text" name="topic" maxlength="254" id="id_topic"></p>
<div class="boxButtonReg">
<button class="buttonReg" type="submit">Save</button>
</div>
</form>
</div>
{% endblock %}
It shows nothing because you did not link you dht objects to that UserProfile, so if you later query for the dhts for that UserProfile, evidently the list is empty. You should add it to the dht relation, like:
#login_required(login_url = '/web/login')
def newDHTSensor(request):
if request.method == "POST":
form = newDHTSensorForm(request.POST)
if form.is_valid():
post = form.save()
request.user.userprofile.dht.add(post)
return redirect('/web/dhtDetail')
else:
form = newDHTSensorForm()
return render(request, 'web/newDhtSensor.html', {'form': form})
Note that you first need to save the post, so you should omit the commit=False aprameter.

python django: error using inline formset

I have the following models:
class Equipment(models.Model):
asset_number = models.CharField(max_length = 200)
serial_number = models.CharField(max_length = 200)
class Calibration(models.Model):
cal_asset = models.ForeignKey(Equipment, on_delete = models.CASCADE)
cal_by = models.CharField(max_length = 200)
cal_date = models.DateField()
notes = models.TextField(max_length = 200)
and view:
def default_detail (request, equipment_id):
equipment = Equipment.objects.get(id = equipment_id)
if request.method == "POST":
if 'calibration' in request.POST:
EquipmentInlineFormSet = inlineformset_factory(Equipment, Calibration, fields = ('cal_by', 'cal_dates', 'notes')
formset = EquipmentInlineFormSet(request.POST, request.FILES, instance=equipment)
if formset.is_valid():
formset.save()
return HttpResponseRedirect(reverse('calbase:default_detail', args=(post.id)))
else:
formset = EquipmentInlineFormSet(instance=equipment)
return render(request, 'calbase/default_detail.html', {'formset' : formset})
and template for this view:
<h1>{{ equipment.serial_number }}</h1>
{{equipment.serial_number}} -- {{equipment.asset_number}} <br>
calibration history:
{% for calibrations in equipment.calibration_set.all %}
<ul>
<li>
{{calibrations.cal_by}} -- {{calibrations.cal_date}} -- {{calibrations.notes}}
</li>
</ul>
{% endfor %}
{% if error_message %}<p><strong>{{ error_message }}</strong></p>{% endif %}
<form method="POST" action = "{% url 'calbase:default_detail' equipment.id %}">{% csrf_token %}
{{ formset }}
<button type="submit" class="save btn btn-default" name = "calibration">Save</button>
</form>
Back?
This view is simply a detail view of equipment, showing some information (asset and serial # of this piece of equipment). I am trying to add a formset that let user add calibration record to this equipment in this view and display them if any. I learned that using inline formset is probably the way to go. However, after following documentation step by step, I am having a
equipmentInlineFormSet = EquipmentInlineFormSet(request.POST, request.FILES, instance=equipment)
SyntaxError: invalid syntax
error even though I checked to make sure that there is no typos or so. I am just trying to figure out what I did wrong here.
Isn't it a missing closing parenthesis on this line?
EquipmentInlineFormSet = inlineformset_factory(Equipment, Calibration, fields = ('cal_by', 'cal_dates', 'notes')

How can I add the actual date automatically in Django Forms?

Im new in Django, and Im trying to create a form for add books for my app. But I want the date of publication not included in the form. Instead I want the current system date is obtained and will " add" the form to save my model . How could I do this?
There is part of my views.py:
def add_book(request):
if request.method == 'POST':
form = BookForm(request.POST)
if form.is_valid():
new_book = form.save(commit=False)
new_book.publication_date = django_timezone
new_book.save()
return HttpResponseRedirect('/thanks/')
else:
print form.errors
else:
form = BookForm()
return render_to_response('add_book.html',{'form':form})
There is my forms.py:
class BookForm(ModelForm):
class Meta:
model = Book
exclude = ('publication_date',)
And my model Book:
class Book(models.Model):
title = models.CharField(max_length = 100)
authors = models.ManyToManyField(Author)
publisher = models.ForeignKey(Publisher)
publication_date = models.DateField()
num_pages = models.IntegerField(blank = True, null = True)
class Admin:
list_display = ('title', 'publisher', 'publication_date')
list_filter = ('publisher', 'publication_date')
ordering = ('-publication_date',)
search_fields = ('title',)
def __str__(self):
return self.title
I used this template for form:
{% extends 'base.html' %}
{% block title %}Add a new Book{% endblock %}
{% block content %}
<h3> Here you can add a new book into the local DataBase </h3>
<form action="." method="post">{% csrf_token %}>
<div class="fieldWrapper">
{{ form.title.errors }}
<label for="id_title">Book Title</label>
{{ form.title }}
</div>
<div class="fieldWrapper">
{{ form.authors.errors }}
<label for="id_authors">Authores</label>
{{ form.authors }}
</div>
<div class="fieldWrapper">
{{ form.publisher.errors }}
<label for="id_publisher">Publishers</label>
{{ form.publisher }}
</div>
<div class="fieldWrapper">
{{ form.num_pages.errors }}
<label for="id_num_pages">Number of Pages</label>
{{ form.num_pages }}
</div>
<p><input type="submit" value="Submit"></p>
</form>
{% endblock %}
I've temporarily disabled Django csrf because I do not need for my purpose
To do that, you need to pass the default argument as timezone.now in publication_date model field.
models.py
class Book(models.Model):
title = models.CharField(max_length = 100)
authors = models.ManyToManyField(Author)
publisher = models.ForeignKey(Publisher)
# pass the default argument in publication_date field
publication_date = models.DateField(default=timezone.now)
num_pages = models.IntegerField(blank = True, null = True)
class Admin:
list_display = ('title', 'publisher', 'publication_date')
list_filter = ('publisher', 'publication_date')
ordering = ('-publication_date',)
search_fields = ('title',)
def __str__(self):
return self.title
views.py
After doing that, you can directly call .save() on modelform. Now, the book object will be created with the aware datetime.
def add_book(request):
if request.method == 'POST':
form = BookForm(request.POST)
if form.is_valid():
new_book = form.save() # directly save the book object
return HttpResponseRedirect('/thanks/')
else:
print form.errors
else:
form = BookForm()
return render_to_response('add_book.html',{'form':form})
Why we did not use auto_now_add argument in the model field?
From django's auto_now_add documentation:
Django's auto_now_add uses current time which is not timezone aware. So, it is better to explicitly specify default value using default argument.
If you want to be able to modify this field, set default=timezone.now
(from django.utils.timezone.now()) instead of auto_now_add=True.

How to autofill a form template with values stored in database in Django?

I would like to fill my edit_post.html with the values already stored in the database .
My edit url is http://hostname/edit_Post/960 . "960" corresponds to the item id in my database . I request with that ID to update its contents.
I wann the contents to appear here :-
edit_Post.html
<form id="category_form" method="post" action="/edit_Post/">
{% csrf_token %}
{% for field in form.visible_fields %}
{{ field.errors }}
<input type="text" placeholder='{{ field.help_text }}'>
{% endfor %}
<input type="submit" name="submit" value="Create Post" />
</form>
urls.py
url(r'^edit_Post/(?P<id>\d+)', 'blog.views.edit_Post'),
forms.py
class addPostForm(forms.ModelForm):
title = forms.CharField(max_length=128, help_text="Please enter the title ")
author = forms.CharField(max_length=128, help_text="Please enter the Author ")
bodytext = forms.CharField(max_length=128,
help_text="Please enter the Body",
required=False)
# An inline class to provide additional information on the form.
class Meta:
# Provide an association between the ModelForm and a model
model=posts
fields = ('title', 'author','bodytext')
finally views.py
def edit_Post(request, id):
context = RequestContext(request)
instance=posts.objects.get(id=id)
form = addPostForm(instance=instance)
if request.method == "POST":
form = addPostForm(request.POST,instance=instance)
if form.is_valid():
form.save(commit=True)
confirmation_message = "Post information updated successfully!"
return HttpResponseRedirect('/home')
else:
print form.errors
else:
form=addPostForm(instance=instance)
return render_to_response('edit_Post.html', {'form': form}, context)
my model.py
class posts(models.Model):
author = models.CharField(max_length = 30)
title = models.CharField(max_length = 100)
bodytext = models.TextField()
timestamp = models.DateTimeField(default=datetime.now, blank=True)
Django would already do this, if you hadn't bypassed its mechanism of outputting fields. In your template you should do this:
{% for field in form.visible_fields %}
{{ field.errors }}
{{ field }}
{% endfor %}
If you want to keep the placeholder functionality, add that in the form class itself:
class addPostForm(forms.ModelForm):
title = forms.CharField(max_length=128, widget=forms.TextInput(attrs={'placeholder': 'Please enter the title'}))
Django provides CRUD(Create -> CreateView, Remove ->DeleteView, Update -> UpdateView, Details -> DetailView) Views. If you can, use them.
You can change your method from views.py in a class.
class PostDetail(DetailView):
model = posts
form_class = addPostForm
template = "edit_post.html"
Then you can add methods there :).

Categories