开发者

How to render CharField into static text in Django?

开发者 https://www.devze.com 2023-01-22 14:01 出处:网络
I started to code in Django quite recently, so maybe my question is a bit wierd. Recently I needed to render the CharField fields from the model into simple static text in html , but I figured out tha

I started to code in Django quite recently, so maybe my question is a bit wierd. Recently I needed to render the CharField fields from the model into simple static text in html , but I figured out that it seems it's not that simple in this case as开发者_Python百科 I could think, or I am doing something wrong...

I have this model:

class Tag(models.Model):
    CATEGORIES = (
        (0, 'category0'),
        (1, 'category1'), 
        (2, 'category2'), 
        (3, 'category3'), 
        (4, 'category4'), 
        (5, 'category5'))
    name = models.CharField(max_length=20)
    description = models.CharField(max_length=100, blank=True)
    category = models.IntegerField(default=0)
    user = models.ForeignKey(User)

Form class for it is:

class TagForm(ModelForm):
    category = ChoiceField(choices=Tag.CATEGORIES)

    class Meta:
        model = Tag

in views I create the formset with multiple Tag objects in a single form with providing TagForm class for each Tag object in it:

TagsFormSet = modelformset_factory(Tag,exclude=('user'),form=TagForm,extra=0)
form = TagsFormSet(queryset=all_tags)

and in the template I have:

{{ form.management_form }}   
{% for tagform in form.forms %}
{{ tagform }} 
<hr>
{% endfor %}

But this way in the html, "name" and "description" fields of the model are always rendered as input text field. I would like to have them in the html just as normal static text without anything (in that html at the moment I only need to display them). Is there any quick solutions for this case?


In your form's meta class, add the following to remove the fields

exclude = ('name', 'description'),

then display the values in your template with

{{ tagform.instance.name }}
{{ tagform.instance.description }}

Also, the choices argument should be passed to the category model field; that way you won't need to explicitly define the field in the form.


It might be sufficient to render the field as readonly (so the browser refuses to modify the data), see this question.


If you absolutely want to render just the text, you need to define a custom widget, then map the form field to this widget. In the widget's render() method, output just the field value.


If you don't want input fields, why do you use Django's forms?

You can also just give an object list to the template and render the object fields any way you like.

0

精彩评论

暂无评论...
验证码 换一张
取 消