How to use MultipleChoiceField in django-widget-tweaks? - python

I have form with MultipleChoiceField field which has dynamic list for choices. With the help of this form users can select data and add them to database.
Sometimes dynamic list can be empty []. So I want to show message in template when its empty but next code didnt show me message. I use django-widget_tweaks application in my template. Where is my mistake?
forms.py:
class RequirementForm(forms.ModelForm):
symbol = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple)
class Meta:
model = Requirement
fields = ('symbol',)
requirement_add.html:
{% load widget_tweaks %}
<form method="post" action="{% url 'project:requirement_add' project_code=project.code %}">
{% for field in form %}
{% render_field field class="form-control" %}
{% empty %}
<p>Form is empty!</p>
{% endfor %}
</form>

The {% empty %} clause will display the text only when the given array is empty or it doesn't exist. In this case the form will always have fields even if the choices are empty.
You should try checking directly with the choices and show the form only when its not empty.

Related

Django rendering Form object rather than form fields

Sure I've missed something obvious, but any help appreciated.
I have a form model:
class UserForm(forms.Form):
name = forms.CharField()
A view:
def userform(req):
context = {}
context['user_form'] = UserForm()
context['message'] = 'test message'
return render(req, 'apps/userform.html', context)
And a template:
{% extends 'base.html' %}
{% block title %} | User Form {% endblock %}
{% block content %}
<h1>Form page</h1>
<form method='POST'>
{% csrf_token %}
{{ user_form }}
<button type='submit'>Send</button>
</form>
{{ message }}
{% endblock %}
I'm pretty sure everything is connected correctly and imported as required - the 'message' property on context renders fine under the form.
However, {{ user_form }} in the template renders the actual Form object instance, rather than the actual form field I'm expecting. I see:
<userform.views.UserForm object at 0x7fcab17e5c10>
Then the form submit button.
What have I missed?
Django 4, if that matters.
So the issue was I had a class based view in the views file with the same name as my Form class - I guess that was getting instantiated, rather than the Form class. Commented out the CBV and everything worked.
If I'd looked harder at the error message, I would have probably seen this sooner as the instantiated object is clearly in the views folder, rather than the forms one...

How to show data from django models whose boolean field is true?

verified = models.BooleanField(default=False)
I want to show only that objects in frontend whose verified field is true in Django models.
There are many ways
you can handle this on your views
in views.py
modelList = modelname.objects.filter(verified=True)
also you can handle it on HTML
in views.py
modelList = modelname.objects.all()
in html
{% for models in modelList %}
{% if models.verified == True %}
# Your Code
{% endif %}
{% endfor %}
You filter the items with:
MyModel.objects.filter(verified=True)
with MyModel the model that contains the verified field.
you have to ways to achive that that either it with your views or html
first views
you can filter your model to return only object which is verfied like this
name = modelname.objects.filter(verified=True)
second way
or you can pass in html while you are requesting all object of that field in views
in views
name = modelname.objects.all()
then in html while fetching data
{% for name in models %}
{% if name.verified == True %}
then pass the object which are verified
{% else %}
pass another data
{% endif %}
{% endfor %}
i hope now you got my point tell me if you got any error while implementing any of these code

Django Populate Dropdown Menu With Choices From Many To Many Database

I would like to populate my dropdown menu with records from the Subject table which is a many to many choices field that is populated with subjects by adding them manually from the admin page. A course can have many subjects such as "business" and "marketing".
Code:
https://dpaste.de/825n
How would I do that with django-select2 or use a form with model select or multiple model select?
https://docs.djangoproject.com/en/2.2/ref/forms/fields/#modelchoicefield
https://docs.djangoproject.com/en/2.2/ref/forms/fields/#modelmultiplechoicefield
https://django-select2.readthedocs.io/en/latest/
Or maybe I could do it with a for loop on the template?
For loops I have tried but no luck:
https://dpaste.de/5MVi
Desired Result:
https://imgur.com/a/Iw9lk6I
Can someone please help me figure it out? I have been stuck for a while now.
here hope this helps your missing the .all() on while querying the many to many fields. you're also not going deep enough to the actual name of the many to many fields so you're trying to print the object on your loop.
example view:
def tester(request):
tes = Test.objects.get(id=1)
testlist = tes.category.all()
context = {
'test': testlist,
}
return render(request, 'core/t.html', context)
example loop:
{% for item in test %}
<p>- {{item.cat}}</p>
{% endfor %}
example model:
class cats(models.Model):
cat = models.CharField(max_length=10,)
class Test(models.Model):
name = models.CharField(max_length=10,)
category = models.ManyToManyField(cats)
nested loop example:
{% for item in item_list %}
<h2>{{ item.name }}</h2>
<ul>
{% for sub in item.subjects.all %}
<li>{{ sub.name }}</li>
{% endfor %}
</ul>
{% endfor %}
After creating your model form you can use something like this to get a dropdown
class CourseForm(forms.ModelForm):
subjects = forms.ModelMultipleChoiceField(
queryset=Subject.objects.all(),
required=True,
)
class Meta:
model = Course
fields = [......, subjects]
or you can use the other widget, widget=forms.CheckboxSelectMultiple,depending on your requirement
<form method="post" action="">
<div>
{% csrf_token %}
{{ form }}
<input type="submit" class="btn btn-primary" id="submit" value="Save">
</div>
</form>
Add a create view to create a course something like below
class CourseCreateView(CreateView):
model = Course
form_class = CourseForm
template_name = 'course_form.html'
success_url = reverse_lazy('/')

Django generating the form tags instead of hardcoding them

I am having issues with having to hardcode the tags into the templates in Django. The reason I have issues is that I need to have the forms generated dynamically based on a framework I am working on.
That framework (written in Python) has a webinterface (hence Django) that requires forms for each module in the framework, depending on the data that needs to be submitted to that module.
So I am trying to get the form information (which fields, type of fields, labels etc.) from the module, which I currently am trying like so:
#framework/module.py
def form():
forms = '"upload": {"filename": "file","directory": "text"}'
return forms
The reason it is constructed like that, at this moment, is because I try to pass this information to the forms.py from Django so it can then be translated into what Django needs to create the output for the template.
Now I have tried a couple of ways on how to get it onto the template. The only problem is, that I have to create the form tags hardcoded into the template. I am trying to figure out how to get the form tags also generated dynamically based on the information supplied by the module. Because there could be modules that require multiple forms on the same page.
So in short, I am trying to do this:
{% for f in forms %}
{{f}}
{% endfor %}
Instead of this:
<form name="upload" action="foo" method="POST">
{{form}}
</form>
Is this possible in Django?
You can render your form fields manually in django, here is how.
{% for field in form %}
<div class="fieldWrapper">
{{ field.errors }}
{{ field.label_tag }} {{ field }}
{% if field.help_text %}
<p class="help">{{ field.help_text|safe }}</p>
{% endif %}
</div>
{% endfor %}
EDIT: I didn't get the question properly
You could have your form tag attributes in a dictionary and iterate through your forms in a structure like this:
Python:
forms = {
form_object: {"name": "upload", "action": "foo", "method": "POST"}
}
Template:
{% for form, tag_attributes in forms.items %}
<form name="{{tag_attributes.name}}" action="{{tag_attributes.action}}" action="{{tag_attributes.method}}">
Do stuff with your {{form}}
</form>
{% endfor %}

Django 2: How to loop through form fields where string not in

In a template html, I would like to loop through each form field and display the form if e.g. '_description' is not in the form field name.
I then want to display an extra, associated field next to it. e.g. something like:
{% for field in form.fields %}
{% if "_description" not in field %}
{{ field }}
{{ field + "_description"}} <-- getting the associated form field to display
{% endfor %}
Can this sort of logic be done in Django?

Categories

Resources