martinav7
martinav7

Reputation: 33

Django form not rendering input fields in template

When creating a form bounded to a model in django, it does not render at all.

I have the following model:

class Recipe(models.Model):
    title = models.CharField(max_length=200)
    text = models.TextField()
    created_date = models.DateTimeField(
        default=timezone.now)
    url = models.TextField(validators=[URLValidator()], blank = True)
    photo = models.ImageField(upload_to='photos', blank = True)

    def publish(self):
        self.created_date = timezone.now()
        self.save()

def __str__(self):
    return self.title

The form:

class RecipeForm(forms.ModelForm):

    class Meta:
        model = Recipe
        fields = ['title', 'text']

The view:

def recipe_new(request):
    form = RecipeForm()
    return render(request, 'recipe_edit.html', {'form:': form})

The template:

{% extends 'base.html' %}

{% block content %}
  <h1>New recipe</h1>
  <form method="post" class="recipe-form">{% csrf_token %}
    {{ form.as_p }}
    <button type="submit" class="save btn btn-default">Save</button>
  </form>
{% endblock %}

But only the title "New recipe" and "Save" button is rendered. If I try to print the form variable in my terminal, it prints out correctly. However, the response to the request always comes without the input fields (whether I use form.as_p or just form). Am I passing the form to the template incorrectly or is the form itself wrong?

Upvotes: 2

Views: 1159

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 477749

You wrote:

{'form:': form}

notice the colon (:) in boldface in the key (you write the colon twice, once in the key, and once as a key-value separator). As a result you pass a variable with a name that has a colon in it. Changing the template might help, but I would strongly advice against it, since such characters have typically a specific meaning for template filters, etc. I would therefore advice to only use valid Python identifiers.

Since the name of the variable was form:, using form in the template did not make any sense, since - according to the Django render engine - that variable does not exists, so it resolves it with the string_if_invalid setting of the render engine (by default the empty string).

It should be:

def recipe_new(request):
    form = RecipeForm()
    return render(request, 'recipe_edit.html', {'form': form})

Upvotes: 0

Related Questions