简体   繁体   中英

How do I label fields on a Django form?

I'm trying to figure out how to label my Django form fields- at the moment I'm unable to change them. I have tried amending the field names and adding labels within models.py, but it throws an error, I'm not sure where to add them.

models.py:

from django.db import models
from django.contrib.auth.models import User


class Stats(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    date = models.DateField(auto_now=True)
    weight = models.DecimalField(max_digits=5, decimal_places=2)
    run_distance = models.IntegerField(default=5)
    run_time = models.TimeField()

    class Meta:
        db_table = 'health_stats'
        ordering = ['-date']

    def __str__(self):
        return f"You currently weigh {self.weight}, {self.user}"

views.py:

class UpdateHealth(View):
    
    def get(self, request, *args, **kwargs):

        stats = Stats
        update_form = StatUpdateForm
             
        context = {
            'stats': stats,
            "update_form": update_form,
            'user': stats.user,
            'weight': stats.weight,
            'date': stats.date,
        }
        return render(request, 'health_hub_update.html', context)
    
    def post(self, request, *args, **kwargs):

        stats = Stats
        update_form = StatUpdateForm(data=request.POST)
             
        context = {
            'stats': stats,
            "update_form": update_form,
            'user': stats.user,
            'weight': stats.weight,
            'date': stats.date,
            'run time': stats.run_time,
            'run distance': stats.run_distance
        }

        if update_form.is_valid():
            update_form.save()
            
        return render(request, 'health_hub_update.html', context)

forms.py:

class StatUpdateForm(forms.ModelForm):
    class Meta:
        model = Stats
        fields = ('user', 'weight', 'run_distance', 'run_time')

Any help would be appreciated!

Try this:

#forms.py 
class StatUpdateForm(forms.ModelForm):
    class Meta:
        model = Stats
        fields = ('user', 'weight', 'run_distance', 'run_time')

    def __init__(self, *args, **kwargs):
        super(StatUpdateForm, self).__init__(*args, **kwargs)
        self.fields['user'].label = "New user Label"
        self.fields['weight'].label = "New weightLabel"
        self.fields['run_distance'].label = "New run_time Label

or

Solution two :

Add label attributes to fields.

#models.py

class Stats(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE, label="User Label"))
    date = models.DateField(auto_now=True, label="Date Label"))
    weight = models.DecimalField(max_digits=5, decimal_places=2)
    run_distance = models.IntegerField(default=5)
    run_time = models.TimeField()

try this it's worked with django 4.1

class ProductForm(forms.ModelForm):

    class Meta:
        model = ProductModel
        fields = ('name', 'og_price', 'discount', 'sell_price', 'dis_pice', 'info', 'status', )

        

        labels = {
            'name':'Product Name',
            'og_price':'Original Price',
            'discount':'Product Discount',
            'sell_price':'Product Selling Price',
            'dis_pice':'Product Discounted Price',
            'info':'Product Information',
            'status':'Product Availability Status',
        }

By default in case of model forms The form field's label is set to the verbose_name of the model field, with the first character capitalized.

If you want any customizations on form labels you can pass labels in form of dictionary with keys as fiels name and values as cutomized label values in Meta class of model form.

For example:

labels = {‘name’: ‘Enter Name’, ‘password’: ‘Enter Password’, ‘email’: ‘Enter Email’ } 

class StatUpdateForm(forms.ModelForm):
    class Meta:
        model = Stats
        fields = [‘name’, ‘password’, ‘email’]
        labels = {‘name’: ‘Enter Name’, ‘password’: ‘Enter Password’, ‘email’: ‘Enter Email’ }
    

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM