Reputation: 11
I have been working on a personal project for a bit now and have been unable to resolve an issue I have been having with a particular form. I have written successful Django forms in the past and have modeled it after those but I am still unable to get it to display.
My model looks like:
name = models.CharField(max_length=100)
director = models.CharField(max_length=50)
genre = models.TextField()
rating = models.IntegerField()
mpaa_rating = models.CharField(max_length=5)
# movie_file = models.FileField()
movie_cover = models.CharField(max_length=100)
cast_list = models.TextField()
year = models.TextField()
url = models.CharField(max_length=100, default='http://www.imdb.com/title/')
My form like:
class Meta:
model = Movie
fields = ['url', 'name', 'director', 'genre', 'rating', 'mpaa_rating', 'movie_cover', 'cast_list', 'year']
View:
context = RequestContext(request)
movie_form = MovieForm()
if request.method == 'POST':
movie_form = MovieForm(data=request.POST)
if movie_form.is_valid():
url = urlrequest.urlopen(movie_form.url)
movie = BeautifulSoup(url, 'html.parser')
movie_form.set_name(movie.find(itemprop='name'))
data = get_movie_data(url)
movie_form.data['name'] = data[0]
movie_form.data['director'] = data[4]
movie_form.data['genre'] = data[7]
movie_form.data['rating'] = data[3]
movie_form.data['mpaa_rating'] = data[2]
movie_form.data['year'] = data[1]
movie_form.data['cast_list'] = data[5]
movie_form.data['movie_cover'] = data[6]
movie_form.save()
print('movie added')
return render_to_response('add_movie.html', {movie_form: 'movie_form'}, context)
And finally Template:
<form id="movie_form" method="post" action="{% url 'add_movie' %}">
{% csrf_token %}
{{ movie_form.as_p }}
<input type="submit" value="Save" />
</form>
I have read several posts on stack overflow about how to fix the issue but none of them have fixed mine yet.
Thanks for the help
Upvotes: 1
Views: 58
Reputation: 3083
You're not sending the form to the template:
return render_to_response('add_movie.html', {movie_form: 'movie_form'},
Replace with this:
return render_to_response('add_movie.html', {'movie_form': movie_form})
UPDATE
By the way, you should use render()
instead, as it uses the RequestContext
.
If you want to use it on the template with render_to_response
you'll have to add the parameter context_instance=RequestContext(request)
, which can be a bit annoying.
Upvotes: 1