简体   繁体   English

以表单(django)传递数据库值

[英]Pass database value in form (django)

My form.py : 我的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

The 'Affiliazione' field display 'red' but it isn't saved because Disabled controls cannot be successful . “ Affiliazione”字段显示为“红色”,但未保存,因为Disabled控件无法成功执行 The 'affiliation' field actually pass the data but is hidden. “从属关系”字段实际上传递数据,但被隐藏。 They together give what I want (a disabled field that pass data so the user can see the value but can't change it). 它们一起提供了我想要的内容(一个禁用的字段,用于传递数据,以便用户可以看到该值但不能更改它)。

The problem is I don't like to hardcode that values ('red' and 'id=1'). 问题是我不喜欢对值(“ red”和“ id = 1”)进行硬编码。 I have the 'Options' class in models where I choose the value to pass but I don't know how... I think it's a silly question, sorry, but someone can help me? 我在模型中选择了要传递的值的“选项”类,但我不知道如何……我认为这是一个愚蠢的问题,对不起,但是有人可以帮助我吗?

My models.py : 我的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)

Edit. 编辑。 My View.py : 我的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})

My add_banner.html : 我的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 %}

Even if I don't quite get the intention of your form, but for the sake of answering your question, you could pass the initial value from your views when you initialize the form, this will make the value flexible: 即使我不太了解表单的意图,但是为了回答您的问题,您可以在初始化表单时从视图中传递初始值,这将使值变得灵活:

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})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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