Nice programing

숨겨진 입력을 갖는 Django ModelForm

nicepro 2020. 11. 6. 20:02
반응형

숨겨진 입력을 갖는 Django ModelForm


그래서 내 TagStatus 모델이 있습니다. 나는 그것을 위해 ModelForm을 만들려고합니다. 그러나 내 양식에서는 숨겨진 입력을 {{tag.name}}로 채워야합니다. 문서를 살펴 보았는데 태그 필드를 숨겨진 입력으로 만드는 방법을 모르겠습니다. 아마도 ModelForm이 갈 길이 아닙니까?

models.py :

class TagStatus(models.Model):
    user = models.ForeignKey(User, null=True, unique=True)
    status = models.CharField(max_length=2, choices=tag_statuses)
    tag = models.ForeignKey(Tag, null=True, blank=True)

    def __unicode__(self):
        return self.status

    def save(self, *args, **kwargs):
        super(TagStatus, self).save(*args, **kwargs)

class TagStatusForm(modelForm):
    class Meta:
        model = TagStatus
        fields = ('status','tag') 
        widgets = {
             'select': Select,
             'tag': ???
        }

django views.py :

@login_required
def tags(request):
    all_tags = Tag.objects.all()
    context = base_context(request)
    if request.method == 'POST':
        if 'status_check' in request.POST:
            status_form = TagStatusForm(request.POST)
            #if request.is_ajax():
            if status_form.is_valid():
                status_form.save()
                response = simplejson.dumps({"status": "Successfully changed status"})
            else:
                response = simplejson.dumps({"status": "Error"})
                return HttpResponse (response, mimetype='application/json')
    status_form = TagStatusForm()
    context['status_form'] = status_form
    context['all_tags'] = all_tags
    return render_to_response('tags/tags.html', context, context_instance=RequestContext(request))

주형:

{% for tag in all_tags %}
....
<form class="nice" id="status-form" method="POST" action="">
     {% csrf_token %}
      <input type="hidden" name="status_check" />
      <input type='hidden' name="tag" value="{{ tag.name }}" />
     {{ status_form.status }}
</form>
...
{% endfor %}

django ModelForm을 통해 숨겨진 입력을 만든 다음 템플릿을 통해 채우는 방법은 무엇입니까?


ModelField의 필드를 숨겨진 필드로 만들려면 HiddenInput 위젯을 사용하십시오. ModelForm은 모든 필드에 대해 합리적인 기본 위젯을 사용하므로 개체가 생성 될 때 재정의하면됩니다.

class TagStatusForm(forms.ModelForm):
    class Meta:
        model = TagStatus
        widgets = {'tag': forms.HiddenInput()}

Django에서 숨겨진 필드를 렌더링하는 3 가지 방법 (AFAIK)이 있습니다.

1. You could declare a field normally in forms.py but in your templates html file use {{ form.field.as_hidden }}

2. in forms.py directly use hidden input widget.

class MyForm(forms.Form):
    hidden_field = forms.CharField(widget=forms.HiddenInput())

Once you make the field a hidden input, you could populate the value of the field in templates. Now your hidden field is ready for rendering.

3. Regular form equivalent (thanks to @Modelesq for sharing this nugget). Here no Django is involved. Changes are done at HTML template level. <input type="hidden" name="tag" value="{{ tag.name }}" />


I was looking for a way to HIDE ALL INPUTS :

class TagStatusForm(forms.ModelForm):
    class Meta:
        model = TagStatus

    def __init__(self, *args, **kwargs):
        super(TagStatusForm, self).__init__(*args, **kwargs)
        for field in self.fields:
            self.fields[field].widget = forms.HiddenInput()

I posted a way to do it with generic class-based views here:

from django.forms import HiddenInput

from django.forms.models import modelform_factory

_patient_create_form = modelform_factory(
    models.Patient,
    fields=['name', 'caregiver_name', 'sex', 'birth_date',
            'residence', 'country'],
    widgets={'country': HiddenInput()})

class PatientCreate(LoginRequiredMixin, UserOrgRequiredMixin, CreateView):
    form_class = _patient_create_form
    template_name = 'healthdbapp/patient_form.html'

참고URL : https://stackoverflow.com/questions/15795869/django-modelform-to-have-a-hidden-input

반응형