Home > Enterprise >  Django form not showing up in template using {{ form }} tag
Django form not showing up in template using {{ form }} tag

Time:02-15

I have made a basic todo app for my practice in which i want to create a profile page for every user. I have made a profile model, and connect it to a User signal, profile has been created but when I render it in a template, its not showing the profile form.

the form for the profile model is form.py:

class ProfileForm(ModelForm):
    class Meta:
        model = Profile
        fields = '__all__'
        exclude = ['user']

model.py --profile model:

class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE, null=True, blank=True)
    name = models.CharField(max_length=200, null=True, blank=False)
    email = models.EmailField(max_length=200, null=True)
    phone = models.CharField(max_length=40, null=True, blank=True)
    image = models.ImageField(null=True, blank=True, default='pfp.png', upload_to='images')
    date_created = models.DateField(auto_now_add=True)
    
    def __str__(self):
        return self.user.username

the view to render the profile(note: I am not creating a edit profile form, which i'll do later, that is why i used get in method):

def user_profile(request):
    profile = request.user.profile
    form = ProfileForm(instance=profile)
    
    context = {'form': form}
    return render(request, 'task/profile.html')

profile page template:

{% extends 'main.html' %}

{% load crispy_forms_tags %}
{% block content %}

<h3>Profile Page</h3>

<style>
    .profile-pic{
        max-width: 200px;
        max-height: 200px;
        margin: 0 auto;
        border-radius: 50%;
    }
    body{
        background-color: rgba(211, 211, 211, 0.527);
    }
</style>

<br>
<div >
    <div >
        <div >
            <a  href="{% url 'home' %}">Back to home page</a>
            <hr>
            <h3 style="text-align: center">Account Settings</h3>
            <hr>
            <img src="{{ user.profile.image.url }}" alt="" >
        </div>
    </div>
<form action="" method="get" enctype="multipart/form-data">
    {% csrf_token %}
    {{ form|crispy }}

    <input type="submit"  name=" Update Information">
</form>

{% endblock content %}

what am I doing wrong here

CodePudding user response:

You need to pass the context to the render engine:

def user_profile(request):
    profile = request.user.profile
    form = ProfileForm(instance=profile)
    
    context = {'form': form}
    #                              add the context            
  • Related