1
我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' 字段顯示 '紅色',但它不保存,因爲Disabled controls cannot be successful。 「隸屬關係」字段實際上傳遞了數據,但是隱藏起來。它們一起給我想要的東西(一個傳遞數據的禁用字段,以便用戶可以看到值但不能改變它)。
問題是我不喜歡硬編碼值('紅'和'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 %}
我的表格將允許用戶創建新的旗幟(還有其他irrilevant領域)。用戶應該看到聯屬價值,但不應該能夠改變它。你的觀點不會傳遞給我的形式......場地保持無效 – fabio
然後你可能還需要調整你的前端。渲染字段,如:{{field.label}}:{{field.value}}'只會給您提供值,而不是呈現窗口小部件。 –
這也行不通...它給「Nome:無」「Affiliazione:無」在兩個都沒有文本框。我已經編輯了我的第一篇文章 – fabio