I am building my own projects based on the instructions from 'Django by Example' book.
However I got stuck on how does django initialize input form fields using URL parameters?
#models.py
class Image(models.Model):
title = models.CharField(max_length=200)
description = models.TextField(blank=True)
url = models.URLField()
(...)
#views.py
def image_create(request):
if request.method == 'POST':
form = ImageCreateForm(data=request.POST)
(...)
else:
form = ImageCreateForm(data=request.GET)
return render(request,
'create.html',
{'form': form})
#forms.py
class ImageCreateForm(forms.ModelForm):
class Meta:
model = Image
fields = ('title', 'url', 'description')
widgets = {
'url': forms.HiddenInput,
}
#create.html
{% extends "base.html" %}
{% block content %}
<h1>Bookmark an image</h1>
<img src="{{ request.GET.url }}" class="image-preview">
<form action="." method="post">
{{ form.as_p }}
{% csrf_token %}
<input type="submit" value="Bookmark it!">
</form>
{% endblock content %}
I could not find any specific line of code which would explicitly tell to get request.GET parameters and assign each of them to corresponding input field.
I assume that all of this has to do with the form initialization on line: form = ImageCreateForm(data=request.GET) in views.py
Questions:
- Can someone please explain me how does django use request.GET parameters to initialize input fields values(assigns them URL parameters' values)? Does it simply match, for every request.GET key, the corresponding input field 'name' attribute, and then assigns to that particular input field the value corresponding to the key in request.GET?
- Also can someone confirm if there is a relationship between the model/form(which one?) field names to the URL parameters?
What is the difference between these two(as both of them seems to work the same way, except the latter returns list in the input field values):
form = ImageCreateForm(data=request.GET)form = ImageCreateForm(initial=request.GET)