呈现表单时如何不显示“ Id:”? (与“ ParentClass ptr:”相同)

时间:2018-12-28 17:26:00

标签: python django django-models django-forms django-templates

我用modelformset_factory制作了一个表格(实际上是Formset)。 我用

显示它
  <form method="post" action="">
    {% csrf_token %}
    {{ player_formset.management_form }}
    {% for player_form in player_formset %}
      {% for field in player_form %}
          {{ field.label_tag }} {{ field }}
      {% endfor %}
        <br>
    {% endfor %}
    <input type="submit" value="Aggiungi">
  </form>

当渲染自动添加带有'Human ptr:'的字段时(因为我的模型Player是Human的子类,如果我直接使用Human,他会向我显示“ Id:” ,标题只是用来概括问题)。

如何删除此写内容? 我尝试过:

1)在HTML文件中使用标签 {%forloop.last%} ,但实际上最后一个字段是“删除:” 复选框(如果我使用 can_delete = False 可以,但是我需要)

2)更改PlayerForm(ModelForm)Meta中的标签,但似乎不适用于该字段。奇怪的是,它起作用了 widgets = {'human_ptr':Input(attrs = {})} ,但它会影响 {{field}} 而不是 {{ field.label_tag}}

如果有用,我添加涉及代码的所有部分:

forms.py

from skeleton.models import Player
from django.forms import ModelForm
from django.forms.widgets import Input


class PlayerForm(ModelForm):

    class Meta:
        model = Player
        fields = ['first_name', 'last_name', 'jersey_number']
        labels = {
            'first_name': 'Nome',
            'last_name': '',
            'jersey_number': 'Numero di maglia',
            'human_ptr': 'human_ptr', }

        # widgets = {'human_ptr': Input(attrs={})}

views.py

from django.shortcuts import render, redirect
from skeleton.models import Player
from django.contrib.auth.decorators import login_required
from .forms import PlayerForm
from django.forms import modelformset_factory
from django.http import HttpResponseNotFound


# Create your views here.
@login_required(login_url="/accounts/login/")
def team_area(request):
    if request.user.team is not None:
        PlayerFormSet = modelformset_factory(Player, form=PlayerForm, extra=1, can_delete=True,)
        if request.method == "POST":
            player_formset = PlayerFormSet(
                request.POST,
                request.FILES,
                queryset=Player.objects.all().filter(team=request.user.team),)

            for player_form in player_formset:
                if player_form.is_valid():
                    player = player_form.save(commit=False)
                    player.team = request.user.team

            if player_formset.is_valid():
                player_formset.save()
            return redirect('team_area:home')
        else:
            player_formset = PlayerFormSet(queryset=Player.objects.all().filter(team=request.user.team))
        return render(request, 'team_area/team_area.html', {'player_formset': player_formset})
    else:
        return render(request, 'team_area/empty_page.html')

models.py

class Human(models.Model):
    SHIRT_SIZES = (('XXS', 'XXS'), ('XS', 'XS'), ('S', 'S'), ('M', 'M'), ('L', 'L'), ('XL', 'XL'), ('XXL', 'XXL'))
    team = models.ForeignKey(Team, on_delete=models.CASCADE)
    first_name = models.CharField(max_length=16)
    last_name = models.CharField(max_length=16)
    jersey_size = models.CharField(max_length=4, choices=SHIRT_SIZES, blank=True)
    slug = models.SlugField(blank=True)

    def save(self, *args, **kwargs):
        self.slug = slugify(self.first_name + ' ' + self.last_name)
        super(Human, self).save(*args, **kwargs)

    def __str__(self):
        return self.first_name + ' ' + self.last_name


class Player(Human):
    year_of_birth = models.IntegerField(validators=[MinValueValidator(1900), MaxValueValidator(2100)], blank=True, null=True)
    jersey_number = models.IntegerField(validators=[MinValueValidator(0), MaxValueValidator(99)], blank=True, null=True)
    all_star_game = models.ForeignKey(AllStarGame, on_delete=models.CASCADE, blank=True, null=True)

可能我想直接修改表单( views.py ),而不是修改其显示方式( team_area.html )。

2 个答案:

答案 0 :(得分:0)

虽然不漂亮,但是可以使用

 {% for field in player_form %}
     {% if field.label_tag != id %}
         {{ field.label_tag }} {{ field }}
     {% endif %}
 {% endfor %}

答案 1 :(得分:0)

我在html文件中做到了这一点,并且工作了。我必须添加else,因为没有表单将无法正常工作

  {% for field in player_form %}
    {% if forloop.revcounter != 2 %}
      {{ field.label_tag }} {{ field }}
    {% else %}
      {{ field }}
    {% endif %}
  {% endfor %}