Django change textfield - django

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 }}.

Related

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.

Rendering fields manually and custom css class

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.

User entered links display as text in Django

I just finished creating a user commenting system on a social networking app I am building with Django (python version 2.7.8, Django verion 1.6).
Everything is working well with the commenting system, but I have encountered an issue. If a user submits a link to an external site in one of their comments, that link appears as plain text. I would like the user submitted link to automatically be viewed as a link to that other users can click on.
Does anyone know a potential solution to this problem?
models.py
class Comment(models.Model):
#Model that defines the Commenting system
created = models.DateTimeField(editable =False)
author = models.CharField(max_length = 200, editable = False)
body = models.TextField()
item = models.ForeignKey(BucketListItem)
def __unicode__(self):
return self.body
comment-template.html
<h2>Comments:</h2>
<br>
{% if comments %}
{% for comment in comments %}
<div class = "comment-div">
<h5>{% avatar comment.author 40 %}</h5>
<h5> {{comment.author}}</h5>
<h5 class ="timesince">{{ comment.created|timesince}} ago.</h3>
<br>
<br>
<p>{{comment.body}}</p>
{% if comment.author == current_user %}
<span class = "fa fa-close"></span>
{% endif %}
</div>
{% endfor %}
<br>
<hr>
<br>
{% else %}
<p>There are no comments yet. Be the first to add one!</p>
{% endif %}
<h5 class = "leave-comment">Leave a Comment Here: </h5>
<br>
<form action="/bucketlist/item/{{id}}/" method = "post" role = "form">
<div class = "form-group">
{% csrf_token %}
{% for field in form %}
{{ field.errors }}
{{ field }}
<br>
{% endfor %}
<br>
<input type = "submit" value = "Submit" class="btn btn-warning">
</div>
<br>
You should be able to do this using the urlize template tag that Django provides.
<p>{{ comment.body | urlize }}</p>
This should convert any links within the body of the comment to an actual <a> tag.

Why aren't labels appearing in my Django ModelForm?

I have a very simple ModelForm in my app that looks like this:
# ModelForm
class ProductForm(ModelForm):
class Meta:
model = MyModel
exclude = ['created', 'last_modified', 'serial_number']
# Model
class BaseModel(models.Model):
created = models.DateTimeField(auto_now_add=True, blank=True, null=True)
last_modified = models.DateTimeField(auto_now=True, blank=True, null=True)
class MyModel(BaseModel):
product = models.TextField(verbose_name='Product Name')
serial_number = models.TextField(verbose_name='Serial Number')
And a form that looks like this:
# Form
<form method="POST" action="{% url some_url %}">
{% csrf_token %}
{{ formset.management_form }}
{% for form in formset %}
{% for field in form %}
{% if field.errors %}
<div>{{ field.errors }}</div>
{% endif %}
<div>
{{ field.label_tag }}:
{{ field }}
</div>
{% endfor %}
{% endfor %}
<div class="actions">
<input class="button submit focus" type="submit" value="{% trans "Save" %}" />
</div>
</form>
When I check out the view using this, I just see a colon (:) followed by the textfield: The label is gone.
According to the documentation for ModelForm:
In addition, each generated form field has attributes set as follows:
...
The form field’s label is set to the verbose_name of the model field, with the first character capitalized.
What mistake have I made?
I am using Django 1.4.1 if it matters.
You have to put the field label inside a <label> tag. So:
<div>
<label for="id_{{field.html_name}}">{{field.label}}:</label>
{{ field }}
</div>
The only solution I managed to find that still allowed me to separate each row of the form was doing the following:
<form method="POST" action="{% url some_url %}">
{% csrf_token %}
{{ formset.as_ul }}
<div class="actions">
<input class="button submit focus" type="submit" value="{% trans "Save" %}" />
</div>
</form>
... the key piece being the {{ formset.as_ul }} instead of iterating through each field.
As for why the other listed solution (or the solution in the documentation) didn't work, I will remain baffled.

django change form field in .html template output

I create a form based on a model , like seen below:
class ContactSelectionForm(forms.ModelForm):
contacts = ManyToManyByLetter(Contact, field_name="first_name")
class Meta:
model = ContactSelection
exclude = ('created_by',)
When I process this view I see at the .html output a field labeled with "Contact".
Now I`m wondering whether it is possible to change this output. For example I want to name this field not "Contact" but "Selected Contacts".
This is the form processing part of the .html template:
<form action="{{ request.path }}" method="POST">
<div>
<fieldset class="module aligned">
{% for field in form.visible_fields %}
<div class="form-row">
{# Include the hidden fields in the form #}
{% if forloop.first %}
{% for hidden in form.hidden_fields %}
{{ hidden }}
{% endfor %}
{% endif %}
{{ field.errors }}
{{ field.label_tag }} {{ field }}
</div>
{% endfor %}
<p><input type="submit" value="Save" /></p>
</fieldset>
</div>
</form>
If somebody is wondering what ManyToManyByLetter(Contact, field_name="first_name") in the form is, check out http://code.google.com/p/django-ajax-filtered-fields/ . A very helpful many2many javascript library.
Did you try setting the fields label?
(the docs)
contacts = ManyToManyByLetter(Contact, field_name="first_name", label="Selected Contacts")