Rendering fields manually and custom css class - django

I am trying to manually render the form fields.
I would like to add a bootstrap and custom css class to rendered html.
How can I do this ?
forms.py
class OrderCreateForm(forms.ModelForm):
class Meta:
model = Order
fields = ['name','postal_code']
widgets = {
'postal_code': forms.RadioSelect(),
}
file.html
<form action="." method="post" class="order-form">
<div class="fieldWrapper">
{{ form.postal_code }}
</div>
<p><input type="submit" value="Send"></p>
{% csrf_token %}
</form>
{% endblock %}
rendered html
<div class="fieldWrapper">
<ul id="id_postal_code">
<li><label for="id_postal_code_0"><input type="radio" name="postal_code" value="Yes" required id="id_postal_code_0" />Yes</label></li>
<li><label for="id_postal_code_1"><input type="radio" name="postal_code" value="No" required id="id_postal_code_1" />No</label></li>
</ul>
</div>
How to solve a problem ?
I would appreciate your help.

You can add css classes to form fields in the following way:
'postal_code': forms.RadioSelect(attrs={"class": "form-control"}),
Another option is to not render the form this way at all, and just write your own html.

Related

Django change textfield

Currently am using this textfield for my model
#model
class NoLoginPsuedoAppointment(models.Model):
...
comments = models.TextField(blank=True)
#form
class NoLoginPsuedoAppointmentForm(forms.ModelForm):
comments = forms.Textarea()
class Meta:
model = NoLoginPsuedoAppointment
fields = [
"comments",
]
Which comes out looking like this
Is there a way to change where the textarea begins so that comments is on top of the textarea or on its top left instead of being on its bottom left? Can this be changed through the django forms? or do I need to change it through css?
sure you can change it. that's only the form field label you can put it anywhere you want. I guess you rendered the form as {{ form.as_p }} or as table or ... so you have to loop through the form fields
<form ... >
{% csrf_token %} <!-- if thats POST -->
{% for field in form %}
<div class="row">
<div class="col-4">{{ field.label }}</div>
<div class="col-8">
{{ field }}
</div>
</div>
{% endfor %}
<button type="submit" class="btn btn-info">Save Changes</button>
</form>
in above example I just created a row and putted the label and field in the same row, you can put it as you wish. and also you can access the field errors with {{ field.errors }}.

Multiple checkboxes validation rules, only works when every checkbox selected

I have a template which goes through a queryset and creates a checkbox for each item which seems to be a validation problem. I can only submit this when I check every checkbox and I just can't seem to figure out what is wrong.
my template:
<form method="POST">
{% csrf_token %}
<fieldset>
{% for choice in choices %}
{{ choice.description }}
<input type="checkbox" value="{{choice.section}}" name="sections" required="">
{% endfor %}
<button type="submit">Submit</button>
</fieldset>
</form>
my forms.py
class AddSectionForm(forms.Form):
sections = forms.MultipleChoiceField(
required=False, widget=forms.CheckboxSelectMultiple())
edit
Urghh, I'm an idiot, it's the required="" in the html checkbox object!
Thanks Willem, you got it! Also needed to change the checkbox values for the primary keys.
forms.py:
class AddSectionForm(forms.Form):
sections = forms.MultipleChoiceField(
required=True, widget=forms.CheckboxSelectMultiple(),
choices=Section.objects.all().values_list())
template:
<form method="POST">
{% csrf_token %}
<fieldset>
{% for choice in choices %}
{{ choice.description }}
<input type="checkbox" value="{{choice.pk}}" name="sections">
{% endfor %}
<button type="submit">Submit</button>
</fieldset>
Your checkboxes should not have required="", otherwise it is required to check these. Furthermore it is probably more elegant to use a ModelMultipleChoiceField:
class AddSectionForm(forms.Form):
sections = forms.ModelMultipleChoiceField(
queryset=Section.objects.all(),
required=True,
widget=forms.CheckboxSelectMultiple()
)

how to grab a data from existing field in Django

I have a web page that I have to connect with Django. So I have an existing form with input and submit button. I have created a model and form. I put {{form}} tag and a little unstyled form appeared. but I want to grab a data from the one in HTML file. The code:
form file:
class NumberForm(ModelForm):
class Meta:
model = Number
fields = "__all__"
HTML:
<form action="#" method="post">
{% csrf_token %}
{{ form }}
<div class="line>
<input type="text" class="form-control" name="phoneNumber" id="phoneNumber2" value="" placeholder="+7 (___) ___-__-__">
<button class="button_blue">t</button>
</div>
<label class="container_checkbox">
<input type="checkbox" checked="checked">
<span class="checkmark"></span>
</label>
</form>

Django BooleanField - Checkbox not showing in form on website

I have the following:
forms.py
class StoreSettingsForm(ModelForm):
enable_repricer = forms.BooleanField(required=True)
enable_ignore_min_price = forms.BooleanField(required=True)
class Meta:
model = Store
fields = '__all__'
exclude = ['user']
models.py
class Store(models.Model):
user = models.ForeignKey(User, models.SET_NULL, blank=True, null=True)
store_name = models.CharField(max_length=100, blank=False)
...
enable_repricer = models.BooleanField(default=False)
enable_ignore_min_price = models.BooleanField(default=False)
template.html
<form method="post">
{% csrf_token %}
<h4>Repricer Settings</h4>
<div class="row">
{{ form.non_field_errors }}
<div class="fieldWrapper col s4">
{{ form.enable_repricer.errors }}
<label for="{{ form.enable_repricer.id_for_label }}">Enable Repricer:</label>
{{ form.enable_repricer }}
</div>
<div class="fieldWrapper col s4">
{{ form.enable_ignore_min_price.errors }}
<label for="{{ form.enable_ignore_min_price.id_for_label }}">Allow Repricer to ignore min_price:</label>
{{ form.enable_ignore_min_price }}
</div>
<div class="fieldWrapper col s4">
{{ form.repricer_factor.errors }}
<label for="{{ form.repricer_factor.id_for_label }}">Repricer aggressiveness factor (1-100):</label>
{{ form.repricer_factor }}
</div>
</div>
<input class="btn" type="submit" value="Submit">
</form>
</div>
view.py
class StoreSettingsView(View):
template_name = 'store_settings.html'
def get(self, *args, **kwargs):
store = Store.objects.get(id=kwargs['id'])
data = {
'store_name': store.store_name,
'store_email': store.store_email,
...
'enable_ignore_min_price': store.enable_ignore_min_price,
'enable_repricer': store.enable_repricer,
'repricer_factor': store.repricer_factor,
}
form = StoreSettingsForm(initial=data)
return render(self.request, self.template_name, {
"store": store,
"form": form,
})
It does not show up in the form. All field are showing on the page but not the 2 boolean fields. The labels are showing and in the HTML.
I have excluded many fields from the code blocks to make it more easy to read.
I was with this problem and I solved it doing that:
#----- My error was caused by Materialize css ----#
Not showing checkbox
<form>
{% for field in form %}
{{field.label_tag}}<br>
{{field}}
<br>
<br>
{% endfor %}
</form>
Using Materialize, You must have a span tag in your label:
Example in Materialize doc:
<label>
<input type="checkbox" class="filled-in" checked="checked" />
<span>Filled in</span>
</label>
I solved the problem refacting to the Materialize's doc structure:
<form>
{% for field in form %}
<label>
{% if field.label == "colorida" %} <!-- 'colorida' is my boolean field -->
{{field}}
<span>{{field.label}}</span> <!-- if boolean field, span must be after input (in materialize) -->
{% else %}
<span>{{field.label}}</span> <!-- description before input if not boolean field -->
{{field}}
{% endif %}
</label>
<br>
<br>
{% endfor %}
</form>
Test your example on a page without any CSS, the problem probably is caused by CSS
Ok. When typing the question something arose to me. What if.... and yes that was it. In some way my CSS is disabling the checkbox and i really do not know why. When removing the CSS it works fine. Sorry.

Django - render custom form fields in custom HTML template

I'm kinda new into Django and I'm facing some troubles using some custom forms.
I'm using a purchased Bootstrap theme which apart from the standard classes that comes with Bootstrap has its own classes and of course, some custom CSS. I find it very difficult how Django deals with custom forms and all the sources/information/examples found online makes no sense to me.
So, my elements from my HTML template use the following classes:
<form action="#" method="post" class="card shadow-soft border p-4 mb-4">
<div class="form-group">
<label for="video">Video url</label>
<input type="text" value="https://video.com/" class="form-control shadow-soft" id="video"
placeholder="Video url" required>
</div>
<div class="row">
<div class="col">
<button class="btn btn-primary btn-dark mt-2 animate-up-2 text-right"
type="submit">Update</button>
</div>
</div>
</form>
In forms.py I have added the following:
class UpdateURLForm(forms.Form):
VideoURL = forms.CharField(
widget=forms.TextInput(
attrs={
'class': 'form-group'
}
)
)
class Meta:
model = Listing
fields = ('VideoURL')
In views.py I have imported the form and added to the view:
from .forms import UpdateURLForm
def updateInfo(request):
if request.method == 'POST':
form = UpdateURLForm(request.POST)
if form.is_valid():
pass
else:
form = UpdateURLForm()
return render(request, 'myapp/editinfo.html', {'form': form})
Now, in my HTML template, I want to render the form field which has to inherit the custom CSS styles but somehow, I'm missing something because the field is being displayed as I was using Crispy forms.
<form action="#" method='post' class="card shadow-soft border p-4 mb-4">{% csrf_token %}
<div class="form-group">
<label for="video">Video URL</label>
<input type="text" value="{{form}}" class="form-control shadow-soft" id="video"
placeholder="{{object.VideoURL}}" required> # the placeholder comes from my class based view
</div>
<div class="row">
<div class="col">
<button class="btn btn-primary btn-dark mt-2 animate-up-2 text-right"
type="submit">Update</button>
</div>
</div>
</form>
What should I do if I need more fields from a custom form to be rendered using my custom CSS classes?
Any suggestion would be much appreciated. Thanks!
You can use Widget Tweaks to achieve what you want. This will allow you to use your own styles:
You can get Django Widget Tweaks by using pip:
$ pip install django-widget-tweaks
To enable widget_tweaks in your project you need to add it to INSTALLED_APPS in your projects settings.py file:
INSTALLED_APPS = [
...
'widget_tweaks',
...
]
Considering your code sample, when you render the form field in the HTML template, do something like:
first you need to load in the top of the HTML file (similar how you load static):
{% load widget_tweaks %}
Then you can add your custom class like this:
<div class="form-group">
<label for="video">Video URL</label>
{{form.VideoURL|add_class:"form-control shadow-soft"}}
</div>