Not showing the Form in html - django

This is my model
class showroom(models.Model):
serialno=models.IntegerField(db_index=True,primary_key=True)
carname=models.CharField(max_length=50)
carmodel=models.CharField(max_length=50)
price=models.IntegerField()
rating=models.IntegerField(validators=[MinValueValidator(1),MaxValueValidator(5)])
This is my forms.py
class RegisterForm(ModelForm):
class Meta:
model = showroom
fields =("__all__")
views.py
class carform(CreateView):
model = showroom
form_class=RegisterForm
template_name = "carbrand/carregister.html"
context_object_name='registerform'
html page
{% block content %}
{{registerform}}
{% endblock content %}
It's just showing a blank screen. I have imported all the necessary classes and views. It will make this too long for you so i removed it.can anyone please tell me if anything wrong in my view/form.

The name of the form is not determined by the context_object_name. In fact in a CreateView, the context_object_name does not change anything since no object is passed.
A FormView (and its descendants), always pass the form that is constructed as form to the context. You thus should render this with:
{% block content %}
<form method="post" action="{% url 'some-view-name' %}">
{% csrf_token %}
{{ form }}
<button type="submit">submit</button>
</form>
{% endblock content %}

Related

django form doesn't display labels

I'm new in django. I try to create a simple form based on the model.
Imputs are displayed fine but i have problem with the labels.They don't appears on the page.
I can't figure out where is my mistake. For my it should be working fine.
Any idea what's is wrong here?
class RecForm (ModelForm):
class Meta:
model = Rec
fields = ['name', 'kind',]
labels = {
'name': 'Here put your name',
}
home.html
<form action="addrec" method="post">
{% csrf_token %}
{% for i in form %}
{{ i }}
<br><br>
{% endfor %}
<input type="submit" value="Submit">
{% endblock %}
You're rendering the field in your template as {{ i }}, with i being an instance of a BoundField (code). BoundField.__str__ calls widget.render (code) and returns the output. widget.render renders the value of of the widget's template (see widget templates here https://github.com/django/django/tree/4.0.2/django/forms/templates/django/forms/widgets). None of these templates include the label tag.
To render the label tag your should call {{ i.label_tag }} (code), which will render the tag with all attributes Django knows about. Extra attributes may require adjustments.

How to pass selection from Django template to Class view

I am struggling with something that should be routine for me by now but I have a mental block.
I have a model that stores Country names and a slug version of the name.
Eg. "United States", "united-states"
I want to display the country names in a template for selection, then return the selected country's slug value to the Class based View which will then obtain the data. The list of countries can be links or dropdown - whatever. But I need to obtain the selected value in the View. Here is a simplified version:
Template
{% extends 'base.html' %}
{% block content %}
<form method="POST">
{% for country in object_list %}
{{ country.pretty_name }}</br>
{% endfor %}
</form>
{% endblock content %}
View
class CountryView(TemplateView):
country_name = THE SLUG
country_obj = Country(country_name)
country_obj.build_country_dictionary()
country_obj.display()
So I think I need one of the get methods to access this but I cannot work it out. Thanks for any help.
The "structured way"
Have a look at FormView, where you define your form class (which you also need to create, depends on your situation can be a model form as well). The rest is pretty much handled by the view.
https://ccbv.co.uk/projects/Django/4.0/django.views.generic.edit/FormView/
PSEUDO code
class MyForm(ModelForm):
model = YourModel
class MyFormView(FormView):
form_class = MyForm
# depends on what you want to do, you can overwrite form_valid to do your logic
The quickest way
PSEUDO code
{% extends 'base.html' %}
{% block content %}
<form method="POST">
{% csrf_token %}
<select name="selection">
{% for country in object_list %}
<option value="{{ country.slug_name }}">{{ country.pretty_name }}</option>
{% endfor %}
</select>
<input type="submit">Submit</input>
</form>
{% endblock content %}
class CountryView(TemplateView):
def post(self, request, *args, **kwargs):
selection = request.POST.get('selection')

Using Checkbox in ListView

I'm trying to make Todo app. I want to make checkbox next to task, so when you select it, the task is set to done. The problem is, I can't really know how to change value of my BooleanField in Task Model. There are plenty of posts like this, but they are usually using functions inside views.py or use forms, but I can't relate do my form in ListView.
views.py
class TodolistView(LoginRequiredMixin, ListView):
model = Todolist
template_name = 'todolist.html'
def get_queryset(self):
return Todolist.objects.all().filter(user=self.request.user)
def get(self, request, *args, **kwargs):
todolist_objects = Todolist.objects.all()
return render(request, 'todolist.html', {'todolist_objects': todolist_objects})
todolist.html
{% extends 'base.html' %}
{% load crispy_forms_tags %}
{% block content %}
<p>Add new task</p>
{% for todo in todolist_objects %}
<div>
<form action="" method="post">
<li> {{ todo }} see details</l>
</form>
</div>
{% endfor %}
{% endblock %}

django-taggit add tags form field in DetailView

I'd like to add a single form input field to a DetailView that will append tags to my model. I'm not sure if I need a separate view for that, or I can simply add a form. Using django-bootstrap3, I have the following:
<div class="row">
<form action="add-tag" method="post"
enctype=multipart/form-data>
{% csrf_token %}
{{ form.media }}
{% bootstrap_field form.tags show_label=False %}
<input type="submit" value="{% trans "submit" %}"/>
</form>
</div>
forms.py:
class MyModelAddTagsForm(forms.ModelForm):
class Meta:
model = models.MyModel
fields = ('tags',)
I get the error:
BootstrapError at /someurl/1/view
Parameter "field" should contain a valid Django BoundField.
I'm not sure what else I exactly need. A view and url or modifying my DetailView? Or using an UpdateView instead?

Model Formset - By Default model formset is rendering one extra field (2 fields in total)

My model formset without even defining "extra" parameters in modelformset_factory is rendering one extra field in the template. I have tried many variations but it didn't work. If I print the form (the model form) on the command line it just prints a single form field as required but on model formset it prints 2 by default.
Here is my code.
models.py
class Direction(models.Model):
text = models.TextField(blank=True, verbose_name='Direction|text')
forms.py
class DirectionForm(forms.ModelForm):
class Meta:
model = Direction
fields = ['text',]
views.py
def myview(request):
Dirset = modelformset_factory(Direction, form=DirectionForm)
if request.method == "POST":
dir_formset = Dirset(request.POST or None)
if dir_formset.is_valid():
for direction in dir_formset:
text = direction.cleaned_data.get('text')
Direction.objects.create(text=text)
return render(request, "test/test.html", {'DirFormSet':Dirset})
template
{% block content %}
<form method="POST">{% csrf_token %}
<div id="forms">
{{DirFormSet.management_form}}
{% for form in DirFormSet %}
{{form.text}}
{% if error in form.text.errors %}
{{error|escape}
{% endif %}
{% endfor %}
</div>
<button id="add-another">add another</button>
<input type="submit" />
</form>
{% endblock %}
As a side note, if I submit data on this form it gives the following error.
Error
Exception Type: MultiValueDictKeyError
Exception Value:"u'form-0-id'"
By default, modelformset_factory creates one extra form. If you don't want any extra forms, set extra=0.
Dirset = modelformset_factory(Direction, form=DirectionForm, extra=0)
The KeyError is because you have not included the form's id field in your template. You should have something like:
{% for form in dir_formset %}
{{ form.id }}
{{ form.text }}
...
{% endfor %}
Note that you should be passing the formset instance dir_formset when rendering the template, not the class DirFormSet. Your view should be something like
return render(request, "test/test.html", {'dir_formset': dir_formset})
then the template should be updated to use dir_formset instead of DirFormSet.