django default context variable2019 Community Moderator ElectionAre static class variables possible?Using global variables in a functionDoes Django scale?How do I pass a variable by reference?“Least Astonishment” and the Mutable Default ArgumentHow to access environment variable values?differentiate null=True, blank=True in djangoDjango: How to unit test Update Views/FormsDjango Mixin to add context variablesDjango context variable names for the templates
Should I tell my boss the work he did was worthless
PTIJ: How can I halachically kill a vampire?
Are babies of evil humanoid species inherently evil?
Space in array system equations
Fourth person (in Slavey language)
Why is Beresheet doing a only a one-way trip?
What are some noteworthy "mic-drop" moments in math?
The bar has been raised
Could you please stop shuffling the deck and play already?
What is the likely impact of grounding an entire aircraft series?
How much attack damage does the AC boost from a shield prevent on average?
What to do when during a meeting client people start to fight (even physically) with each others?
How do I express some one as a black person?
Single word request: Harming the benefactor
Low budget alien movie about the Earth being cooked
Can't find the Shader/UVs tab
Can you reject a postdoc offer after the PI has paid a large sum for flights/accommodation for your visit?
Why would a jet engine that runs at temps excess of 2000°C burn when it crashes?
Am I not good enough for you?
Accountant/ lawyer will not return my call
What is the chance of making a successful appeal to dismissal decision from a PhD program after failing the qualifying exam in the 2nd attempt?
Why does Deadpool say "You're welcome, Canada," after shooting Ryan Reynolds in the end credits?
Do I really need to have a scientific explanation for my premise?
Does splitting a potentially monolithic application into several smaller ones help prevent bugs?
django default context variable
2019 Community Moderator ElectionAre static class variables possible?Using global variables in a functionDoes Django scale?How do I pass a variable by reference?“Least Astonishment” and the Mutable Default ArgumentHow to access environment variable values?differentiate null=True, blank=True in djangoDjango: How to unit test Update Views/FormsDjango Mixin to add context variablesDjango context variable names for the templates
I'm new to Django web dev, managed to setup a toy project following this tutorial.
However I found the Django official documentation as well as this tutorial are quite confusing, hard for me to follow, especially the template context variables.
For example, in xxapp/views.py
we defined a few views as follows,
from django.views.generic.edit import CreateView, UpdateView, DeleteView
from django.urls import reverse_lazy
from catalog.models import Author
class AuthorCreate(CreateView):
model = Author
fields = '__all__'
initial = 'date_of_death': '05/01/2018'
class AuthorUpdate(UpdateView):
model = Author
fields = ['first_name', 'last_name', 'date_of_birth', 'date_of_death']
class AuthorDelete(DeleteView):
model = Author
success_url = reverse_lazy('authors')
Then in templates, we have this
% extends "base_generic.html" %
% block content %
<form action="" method="post">
% csrf_token %
<table>
form.as_table <!-- WHERE IS THIS "FORM" FROM? -->
</table>
<input type="submit" value="Submit">
</form>
% endblock %
I understand this template file, except for one thing, where is the form.as_table
from, and what is it??
I'm aware that, if we use some built-in class views or models, we might have some context data for free, but where do I lookup them, I searched on Django but found nothing.
python django django-templates
add a comment |
I'm new to Django web dev, managed to setup a toy project following this tutorial.
However I found the Django official documentation as well as this tutorial are quite confusing, hard for me to follow, especially the template context variables.
For example, in xxapp/views.py
we defined a few views as follows,
from django.views.generic.edit import CreateView, UpdateView, DeleteView
from django.urls import reverse_lazy
from catalog.models import Author
class AuthorCreate(CreateView):
model = Author
fields = '__all__'
initial = 'date_of_death': '05/01/2018'
class AuthorUpdate(UpdateView):
model = Author
fields = ['first_name', 'last_name', 'date_of_birth', 'date_of_death']
class AuthorDelete(DeleteView):
model = Author
success_url = reverse_lazy('authors')
Then in templates, we have this
% extends "base_generic.html" %
% block content %
<form action="" method="post">
% csrf_token %
<table>
form.as_table <!-- WHERE IS THIS "FORM" FROM? -->
</table>
<input type="submit" value="Submit">
</form>
% endblock %
I understand this template file, except for one thing, where is the form.as_table
from, and what is it??
I'm aware that, if we use some built-in class views or models, we might have some context data for free, but where do I lookup them, I searched on Django but found nothing.
python django django-templates
add a comment |
I'm new to Django web dev, managed to setup a toy project following this tutorial.
However I found the Django official documentation as well as this tutorial are quite confusing, hard for me to follow, especially the template context variables.
For example, in xxapp/views.py
we defined a few views as follows,
from django.views.generic.edit import CreateView, UpdateView, DeleteView
from django.urls import reverse_lazy
from catalog.models import Author
class AuthorCreate(CreateView):
model = Author
fields = '__all__'
initial = 'date_of_death': '05/01/2018'
class AuthorUpdate(UpdateView):
model = Author
fields = ['first_name', 'last_name', 'date_of_birth', 'date_of_death']
class AuthorDelete(DeleteView):
model = Author
success_url = reverse_lazy('authors')
Then in templates, we have this
% extends "base_generic.html" %
% block content %
<form action="" method="post">
% csrf_token %
<table>
form.as_table <!-- WHERE IS THIS "FORM" FROM? -->
</table>
<input type="submit" value="Submit">
</form>
% endblock %
I understand this template file, except for one thing, where is the form.as_table
from, and what is it??
I'm aware that, if we use some built-in class views or models, we might have some context data for free, but where do I lookup them, I searched on Django but found nothing.
python django django-templates
I'm new to Django web dev, managed to setup a toy project following this tutorial.
However I found the Django official documentation as well as this tutorial are quite confusing, hard for me to follow, especially the template context variables.
For example, in xxapp/views.py
we defined a few views as follows,
from django.views.generic.edit import CreateView, UpdateView, DeleteView
from django.urls import reverse_lazy
from catalog.models import Author
class AuthorCreate(CreateView):
model = Author
fields = '__all__'
initial = 'date_of_death': '05/01/2018'
class AuthorUpdate(UpdateView):
model = Author
fields = ['first_name', 'last_name', 'date_of_birth', 'date_of_death']
class AuthorDelete(DeleteView):
model = Author
success_url = reverse_lazy('authors')
Then in templates, we have this
% extends "base_generic.html" %
% block content %
<form action="" method="post">
% csrf_token %
<table>
form.as_table <!-- WHERE IS THIS "FORM" FROM? -->
</table>
<input type="submit" value="Submit">
</form>
% endblock %
I understand this template file, except for one thing, where is the form.as_table
from, and what is it??
I'm aware that, if we use some built-in class views or models, we might have some context data for free, but where do I lookup them, I searched on Django but found nothing.
python django django-templates
python django django-templates
asked Mar 6 at 16:28
avocadoavocado
4691716
4691716
add a comment |
add a comment |
2 Answers
2
active
oldest
votes
You're using generic class-based views, which come with a lot of functionality baked in. The best source to look them up is this one.
If you look at the CreateView
for example (Edit -> CreateView), you'll see that the get()
method, which is the first method called when you just fetch the page using GET, just calls render_to_response()
with context data fetched from get_context_data()
.
And inside get_context_data()
, we add a form
context variable to the context, which is assigned to get_form()
. etc...
Same with the post()
method, where first the form
is fetched, checked for validity and if not valid, the form_invalid()
method renders the template with the form
in its context.
You can follow the same with UpdateView
and DeleteView
, they are very similar. Most of the form handling code actually comes from the FormMixin
class.
When creating your own views, subclassing Django's generic views, you'll find that sometimes you can't use a view, but you can use the mixins (e.g. FormMixin
or ModelFormMixin
).
So form
in your template is the ModelForm
for the Author
model you specified in your generic views. The view is auto-generating that form from the model using a modelform_factory
, with the fields you specified with fields
. Since it's added as 'form'
key to the context used to render the template, you can access it with form
. form.as_table
will render the HTML for this form in a <table>
, as described here.
If you don't like how the form looks like and want to customise some of the fields (and can't do that by just changing the template), you would need to create your own form, tell your view about it by setting the form_class
attribute and removing the fields
attribute (the fields would be specified in your form), as described by @drew in his response.
add a comment |
"form" is a variable you need to pass from your view to your template.
You should create a forms.py file to set up all of your forms.
In this file you would create a simple form like so:
from django import forms
class NameForm(forms.Form):
your_name = forms.CharField(label='Your name', max_length=100)
And then in your view you should import the form and then set the "form" variable as such:
form = NameForm()
Or if you have posted data:
form = NameForm(request.POST)
So once you have passed this variable to the template, you can either call the entire form as you have using "form.as_table"
Or you can call individual form fields, such as:
form.your_name.label
form.your_name
form.your_name.errors
See this help doc on the Django site for more information: https://docs.djangoproject.com/en/2.1/topics/forms/#the-form-class
add a comment |
Your Answer
StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");
StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);
else
createEditor();
);
function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);
);
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55027876%2fdjango-default-context-variable%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
2 Answers
2
active
oldest
votes
2 Answers
2
active
oldest
votes
active
oldest
votes
active
oldest
votes
You're using generic class-based views, which come with a lot of functionality baked in. The best source to look them up is this one.
If you look at the CreateView
for example (Edit -> CreateView), you'll see that the get()
method, which is the first method called when you just fetch the page using GET, just calls render_to_response()
with context data fetched from get_context_data()
.
And inside get_context_data()
, we add a form
context variable to the context, which is assigned to get_form()
. etc...
Same with the post()
method, where first the form
is fetched, checked for validity and if not valid, the form_invalid()
method renders the template with the form
in its context.
You can follow the same with UpdateView
and DeleteView
, they are very similar. Most of the form handling code actually comes from the FormMixin
class.
When creating your own views, subclassing Django's generic views, you'll find that sometimes you can't use a view, but you can use the mixins (e.g. FormMixin
or ModelFormMixin
).
So form
in your template is the ModelForm
for the Author
model you specified in your generic views. The view is auto-generating that form from the model using a modelform_factory
, with the fields you specified with fields
. Since it's added as 'form'
key to the context used to render the template, you can access it with form
. form.as_table
will render the HTML for this form in a <table>
, as described here.
If you don't like how the form looks like and want to customise some of the fields (and can't do that by just changing the template), you would need to create your own form, tell your view about it by setting the form_class
attribute and removing the fields
attribute (the fields would be specified in your form), as described by @drew in his response.
add a comment |
You're using generic class-based views, which come with a lot of functionality baked in. The best source to look them up is this one.
If you look at the CreateView
for example (Edit -> CreateView), you'll see that the get()
method, which is the first method called when you just fetch the page using GET, just calls render_to_response()
with context data fetched from get_context_data()
.
And inside get_context_data()
, we add a form
context variable to the context, which is assigned to get_form()
. etc...
Same with the post()
method, where first the form
is fetched, checked for validity and if not valid, the form_invalid()
method renders the template with the form
in its context.
You can follow the same with UpdateView
and DeleteView
, they are very similar. Most of the form handling code actually comes from the FormMixin
class.
When creating your own views, subclassing Django's generic views, you'll find that sometimes you can't use a view, but you can use the mixins (e.g. FormMixin
or ModelFormMixin
).
So form
in your template is the ModelForm
for the Author
model you specified in your generic views. The view is auto-generating that form from the model using a modelform_factory
, with the fields you specified with fields
. Since it's added as 'form'
key to the context used to render the template, you can access it with form
. form.as_table
will render the HTML for this form in a <table>
, as described here.
If you don't like how the form looks like and want to customise some of the fields (and can't do that by just changing the template), you would need to create your own form, tell your view about it by setting the form_class
attribute and removing the fields
attribute (the fields would be specified in your form), as described by @drew in his response.
add a comment |
You're using generic class-based views, which come with a lot of functionality baked in. The best source to look them up is this one.
If you look at the CreateView
for example (Edit -> CreateView), you'll see that the get()
method, which is the first method called when you just fetch the page using GET, just calls render_to_response()
with context data fetched from get_context_data()
.
And inside get_context_data()
, we add a form
context variable to the context, which is assigned to get_form()
. etc...
Same with the post()
method, where first the form
is fetched, checked for validity and if not valid, the form_invalid()
method renders the template with the form
in its context.
You can follow the same with UpdateView
and DeleteView
, they are very similar. Most of the form handling code actually comes from the FormMixin
class.
When creating your own views, subclassing Django's generic views, you'll find that sometimes you can't use a view, but you can use the mixins (e.g. FormMixin
or ModelFormMixin
).
So form
in your template is the ModelForm
for the Author
model you specified in your generic views. The view is auto-generating that form from the model using a modelform_factory
, with the fields you specified with fields
. Since it's added as 'form'
key to the context used to render the template, you can access it with form
. form.as_table
will render the HTML for this form in a <table>
, as described here.
If you don't like how the form looks like and want to customise some of the fields (and can't do that by just changing the template), you would need to create your own form, tell your view about it by setting the form_class
attribute and removing the fields
attribute (the fields would be specified in your form), as described by @drew in his response.
You're using generic class-based views, which come with a lot of functionality baked in. The best source to look them up is this one.
If you look at the CreateView
for example (Edit -> CreateView), you'll see that the get()
method, which is the first method called when you just fetch the page using GET, just calls render_to_response()
with context data fetched from get_context_data()
.
And inside get_context_data()
, we add a form
context variable to the context, which is assigned to get_form()
. etc...
Same with the post()
method, where first the form
is fetched, checked for validity and if not valid, the form_invalid()
method renders the template with the form
in its context.
You can follow the same with UpdateView
and DeleteView
, they are very similar. Most of the form handling code actually comes from the FormMixin
class.
When creating your own views, subclassing Django's generic views, you'll find that sometimes you can't use a view, but you can use the mixins (e.g. FormMixin
or ModelFormMixin
).
So form
in your template is the ModelForm
for the Author
model you specified in your generic views. The view is auto-generating that form from the model using a modelform_factory
, with the fields you specified with fields
. Since it's added as 'form'
key to the context used to render the template, you can access it with form
. form.as_table
will render the HTML for this form in a <table>
, as described here.
If you don't like how the form looks like and want to customise some of the fields (and can't do that by just changing the template), you would need to create your own form, tell your view about it by setting the form_class
attribute and removing the fields
attribute (the fields would be specified in your form), as described by @drew in his response.
edited Mar 6 at 18:54
answered Mar 6 at 18:43
dirkgrotendirkgroten
5,53111324
5,53111324
add a comment |
add a comment |
"form" is a variable you need to pass from your view to your template.
You should create a forms.py file to set up all of your forms.
In this file you would create a simple form like so:
from django import forms
class NameForm(forms.Form):
your_name = forms.CharField(label='Your name', max_length=100)
And then in your view you should import the form and then set the "form" variable as such:
form = NameForm()
Or if you have posted data:
form = NameForm(request.POST)
So once you have passed this variable to the template, you can either call the entire form as you have using "form.as_table"
Or you can call individual form fields, such as:
form.your_name.label
form.your_name
form.your_name.errors
See this help doc on the Django site for more information: https://docs.djangoproject.com/en/2.1/topics/forms/#the-form-class
add a comment |
"form" is a variable you need to pass from your view to your template.
You should create a forms.py file to set up all of your forms.
In this file you would create a simple form like so:
from django import forms
class NameForm(forms.Form):
your_name = forms.CharField(label='Your name', max_length=100)
And then in your view you should import the form and then set the "form" variable as such:
form = NameForm()
Or if you have posted data:
form = NameForm(request.POST)
So once you have passed this variable to the template, you can either call the entire form as you have using "form.as_table"
Or you can call individual form fields, such as:
form.your_name.label
form.your_name
form.your_name.errors
See this help doc on the Django site for more information: https://docs.djangoproject.com/en/2.1/topics/forms/#the-form-class
add a comment |
"form" is a variable you need to pass from your view to your template.
You should create a forms.py file to set up all of your forms.
In this file you would create a simple form like so:
from django import forms
class NameForm(forms.Form):
your_name = forms.CharField(label='Your name', max_length=100)
And then in your view you should import the form and then set the "form" variable as such:
form = NameForm()
Or if you have posted data:
form = NameForm(request.POST)
So once you have passed this variable to the template, you can either call the entire form as you have using "form.as_table"
Or you can call individual form fields, such as:
form.your_name.label
form.your_name
form.your_name.errors
See this help doc on the Django site for more information: https://docs.djangoproject.com/en/2.1/topics/forms/#the-form-class
"form" is a variable you need to pass from your view to your template.
You should create a forms.py file to set up all of your forms.
In this file you would create a simple form like so:
from django import forms
class NameForm(forms.Form):
your_name = forms.CharField(label='Your name', max_length=100)
And then in your view you should import the form and then set the "form" variable as such:
form = NameForm()
Or if you have posted data:
form = NameForm(request.POST)
So once you have passed this variable to the template, you can either call the entire form as you have using "form.as_table"
Or you can call individual form fields, such as:
form.your_name.label
form.your_name
form.your_name.errors
See this help doc on the Django site for more information: https://docs.djangoproject.com/en/2.1/topics/forms/#the-form-class
answered Mar 6 at 17:00
drewdrew
584210
584210
add a comment |
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55027876%2fdjango-default-context-variable%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown