我的form.py
:
class BannerForm(forms.ModelForm):
name = forms.CharField(max_length=32)
#Affiliazione = forms.CharField(disabled = True, initial='red') #in original question
#affiliation = forms.ModelChoiceField(Affiliation.objects.all(),
#widget=forms.HiddenInput(), initial=Affiliation.objects.get(id=1)) #in original question
Affiliazione = forms.CharField(disabled = True, required=False) #added after first answer
affiliation = forms.ModelChoiceField(Affiliation.objects.all(),
widget=forms.HiddenInput()) #added after first answer
' Affiliazione'现场展示' red'但它没有被保存,因为Disabled controls cannot be successful。 '从属关系'字段实际传递数据但隐藏。它们一起提供我想要的东西(一个传递数据的禁用字段,以便用户可以看到值,但不能更改它)。
问题是我不想对这些值进行硬编码(' red'' id = 1')。我有'选项'在模特中我选择要通过的价值,但我不知道如何......我认为这是一个愚蠢的问题,对不起,有人可以帮助我吗?
我的models.py
:
class Options(models.Model):
new_affiliation = models.ForeignKey('Affiliation')
class Affiliation(models.Model):
name = models.CharField(max_length=32, unique=True)
def __str__(self):
return self.name
class Banner(models.Model):
name = models.CharField(max_length=32, unique=True)
affiliation = models.ForeignKey(Affiliation)
编辑。我的View.py
:
def add_banner(request):
# A HTTP POST?
if request.method == 'POST':
form = BannerForm(request.POST)
print('form is post') #control
# Have we been provided with a valid form?
if form.is_valid():
print('form is valid') #control
# Save the new banner to the database.
banner = form.save(commit=False)
#some irrilevant code here
form.save(commit=True)
print('form salvato') #control
# Now call the homepage() view.
# The user will be shown the homepage.
return homepage(request)
else:
# The supplied form contained errors - just print them to the terminal
print (form.errors)
else:
# If the request was not a POST, display the form to enter details
#form = BannerForm(request.POST) #in original question
#initial_value = 'red' #added after first answer
#init = Affiliation.objects.get(id=1) #added after first answer
form = BannerForm(request.POST or None, initial={
'affiliation': Campaign_Options.new_regent_affiliation}) #added after first answer
# Bad form (or form details), no form supplied...
# Render the form with error messages (if any).
print ('fine')
return render(request, 'core/add_banner.html', {'form': form})
我的add_banner.html
:
{% csrf_token %}
{% for hidden in form.hidden_fields %}
{{ hidden }}
{% endfor %}
{% for field in form.visible_fields %}
{{ field.errors }}
{{ field.label }}
{{ field }}
{{ field.help_text }}
<br />
{% endfor %}
答案 0 :(得分:1)
即使我不太了解您的表单,但为了回答您的问题,您可以在初始化表单时从您的视图中传递初始值,这将使值变得灵活:
def your_view(request):
# get the string for affilizione by applying your logic here
# initial_value = 'red'
form = BannerForm(request.POST or None, initial={'Affiliazione': initial_value})