1

I have following snippets,

# models.py
class Test(models.Model):
    username = models.CharField(max_length=100)
    email = models.EmailField()


# forms.py
class TestForm(forms.ModelForm):
    username = forms.CharField()
    email = forms.EmailField()

    class Meta:
        model = Test
        fields = ('username', 'email')


# views.py
def test(request):
    email = "example@example.com"
    """
    How to pass and show the 'email' in django form/template?
    """
    if request.method == 'POST':
        form = TestForm(request.POST)
        if form.is_valid():
            form.save()
            return redirect('home')
    else:
        form = TestForm()
    return render(request, 'test.html', {"form": form})

How can I show and re-use the value of email variable (ie,example@example.com) in Django form/template as a read-only field?

JPG
  • 82,442
  • 19
  • 127
  • 206
  • Maybe not a duplicate, but closely related: https://stackoverflow.com/questions/324477/in-a-django-form-how-do-i-make-a-field-readonly-or-disabled-so-that-it-cannot – Brian H. Oct 15 '18 at 13:24
  • Also very related, almost a dupe of the former question i commented: https://stackoverflow.com/questions/41271979/read-only-field-in-django-form/41272908 – Brian H. Oct 15 '18 at 13:28
  • @BrianH. `disabled=True` doing the job ***partially***. It's not showing the value of `email` field – JPG Oct 15 '18 at 13:38
  • yeah, that's why i said it's not an exact duplicate. – Brian H. Oct 15 '18 at 13:42
  • @BrianH. Anyway I got the answer after little digging :) – JPG Oct 16 '18 at 02:51

1 Answers1

0

try to do this way:

class TestForm(forms.ModelForm):
    .....
    email = forms.EmailField(initial='{{ context.email }}', disabled=True)
    .....

context, passed from view, should have 'email'

apet
  • 958
  • 14
  • 16