在我的models.py
中考虑两个模型:
class Role(models.Model):
role = models.CharField(max_length=255)
nickname = models.CharField(max_length=255)
is_hero = models.BooleanField(default=False)
def __str__(self):
return self.role
和
class Player(models.Model):
name = models.CharField(max_length=255)
role = models.ForeignKey(Role, on_delete=models.CASCADE)
nickname = models.CharField(max_length=255, default="Use the default nickname from the role you just chose but also be able to change it from within this model.")
is_hero = models.BooleanField(default="Use the default is_hero from the role you just chose but also be able to change it from within this model.")
def __str__(self):
return self.name
还要考虑我已经扮演了一个名为"Dumbo"
的角色,昵称为"Dunm"
,而is_hero为False
。
我现在继续尝试,并在设置播放器名称后尝试在新播放器中使用该角色,我选择了我的角色,但是如何使用新选择的角色在我的新播放器中的值作为昵称和is_hero的默认值并同时允许它们被覆盖吗?
谢谢
我已覆盖所有Django模板。因此,我不是在制作新表单并将其呈现在我的自定义视图中。我真的对术语不好,对不起。我希望这是有道理的。
{% load fieldcss %}
<div class="card">
<div class="card-header">
{% if fieldset.name %}<h4 class="card-title">{{ fieldset.name }}</h2>{% endif %}
{% if fieldset.description %}
<div class="description">{{ fieldset.description|safe }}</div>
{% endif %}
</div>
<div class="card-body">
{% for line in fieldset %}
<div class="row">
{% for field in line %}
{% if not line.fields|length_is:'1' and not field.is_readonly %}{{ field.errors }}{% endif %}
{% if name == "CheckboxInput" %}
{{ field.field }}{{ field.label_tag }}
{% else %}
{{ field|addlabel:field.field.label|safe }}
{% if field.is_readonly %}
<div class="readonly">{{ field.contents }}</div>
{% else %}
<div class="col-sm-10">
{% if line.fields|length_is:'1' %}{{ line.errors }}{% endif %}
<div class="form-group">
{{ field|addclass:field.field.auto_id|safe }}
{% if field.field.help_text %}
<span class="form-text">{{ field.field.help_text|safe }}</span>
{% endif %}
</div>
</div>
{% endif %}
{% endif %}
{% endfor %}
</div>
{% endfor %}
</div>
</div>
</fieldset>
答案 0 :(得分:2)
这不是您可以在模型中执行的操作,而是在创建时将值从视图传递到表单。例如:
class PlayerCreateForm(forms.ModelForm):
class Meta:
model = Player
fields = ('name', 'nickname', 'is_hero')
def create_player_from_role(request, role_id):
role = get_object_or_404(Role, role_id)
if request.method == 'POST':
form = PlayerCreateForm(request.POST)
if form.is_valid():
player = form.save(commit=False)
player.role = role
player.save()
return redirect('/')
else:
form = PlayerCreateForm(initial={'nickname': role.nickname, 'is_hero': role.is_hero})
return render(request, 'create_player.html', {'form': form})