Django ClassBasedViews without html file? - django

How to avoid producing html files with content like this:
<form action="/contact/" method="post">{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Submit" />
</form>
Can I define somehow it in views or forms, so that there is no need for creating this files in templates?

Most class-based views use the TemplateResponseMixin. You can override the render_to_response method to return a HttpResponse object (or any subclass) that doesn't render a template.
class SimpleResponseMixin(object):
def render_to_response(self, context, **kwargs):
return HttpResponse(content='<content>', content_type=kwargs.get('content_type', self.content_type))

Related

How To - render a string as a template in django

i've been wondering about how i could render a template just by passing a made-inside-view string so that i woudn't have the need to create an html file. I read the Django Docs, but i couldn't find an explanation on this, as far as seen all was about giving the template path string, (also i tried a few lines, but got nothing).
Please, have this as an example:
from django.shortcuts import render
def my_view(request):
arbitrary_string_as_template = """
<form action="" method="POST">
{% csrf_token %}
<label for="">Username</label>
<input type="text" name="username">
<label for="">Password</label>
<input type="password" name="password">
<button type="submit">
submit
</button>
</form>
"""
return render(request, arbitrary_string_as_template, {})
So if this can be done... then i think it would have in its way a good potential, since it gains in terms of versatility..and btw..
#I'm New to Django
Thanks for your attention
You can construct a Template object [Django-doc] with the template string, and then .render(…) [Django-doc] it:
from django.http import HttpResponse
from django.template import Template, RequestContext
def my_view(request):
arbitrary_string_as_template = """
<form action="" method="POST">
{% csrf_token %}
<label for="">Username</label>
<input type="text" name="username">
<label for="">Password</label>
<input type="password" name="password">
<button type="submit">
submit
</button>
</form>
"""
template = Template(arbitrary_string_as_template)
context = RequestContext(request)
return HttpResponse(template.render(context))
If however the content is static, I would advise to use a file. It makes it easier to separate concerns, and write clean files that each focus on a specific part.

How to create multiple form update(edit) view in Django

I need to create function based or class based view which can edit/update multiple forms in one page. How to create this?
You should be able to have more than one form appear on a template by passing two different form variables in the view. Something like this:
def formview(request):
if request.method == 'POST'
form1 = form.Form1()
form2 = form.Form2()
context = {'form1': form1, 'form2': form2}
Then in your template you simply need to handle each form within the form tags like so:
<form action="" method="post">
{% csrf_token %}
{{ form1.as_p }}
{{ form2.as_p }}
<input class="btn btn-primary" type="submit" value="Submit">
</form>

Declacre CSRF-Token in forms.py

I'm using Djangos CSRF-Token the way it's mostly described on the internet:
MyFormPage.html
<form method="POST">
{% csrf_token %}
{{ form.as_p }}
</form>
But I wonder - is there a way to include it somehow directly in the forms.py?
I don't know if this is a good practice or not, but you can do something like:
from django.middleware import csrf
class SomeForm(forms.Form):
csrfmiddlewaretoken = forms.CharField(widget=forms.HiddenInput(), initial=csrf._get_new_csrf_token())
The rendered input field will be:
<input type="hidden" name="csrfmiddlewaretoken" value="Hsw4uH5jbioQhaWrgAtGgEVp5GbnXIrayuvTqbbABaSxPbGJqksEIxVI4zJW8VVj" id="id_csrfmiddlewaretoken">

How to populate existing html form with django UpdateView?

I am trying to implement a simple UpdateView, but I want to use my own template. Using djangos auto_population is working, but not what I want, because I have lots of fields formatted differently.
<form method="post" action="#">
{% csrf_token %}
{{ form.as_p }}
<input type="submit">
</form>
But I want to use my own form template which looks like this:
edit_template.html
<form class="form-horizontal" role="form" method="POST" action="{% url 'update' pk=abc %}">
{% csrf_token %}
<input name='varX' id="varX" type="text" placeholder="" class="form-class">
<input name='varY' id="varY" type="text" placeholder="" class="form-class">
</form>
views.py
class ModelUpdate(UpdateView):
model = MyModel
fields = ['varX','varY']
Now I would like that form to be populated with my object data, but the form is empty.
UpdateView is also passing the data twice to the template: One as 'object' and one as 'mymodel'.
I also tried updating
get_context_data
by adding
context.update( model_to_dict(myModelData))
But that also does not change anything.
How can I populate my custom form using djangos class-based views?
Try this:
def get_initial(self):
initial = super().get_initial()
initial['my_form_field1'] = self.request.something
return initial
Have a look at django-widget-tweaks, you first need to check for any non field errors and then loopt through the fields one by one.
https://simpleisbetterthancomplex.com/article/2017/08/19/how-to-render-django-form-manually.html
This article should cover just that

CSRF token not rendered if using Context({dict}) vs just {dict}

Does anyone know why the following renders my template ok:
c= {'render_form' : form }
return render(request, 'page1.html', c)
but the following does not render the csrf token:
c= Context({'render_form' : form})
return render(request, 'page1.html', c)
The template looks like this:
<form method="post">
{% csrf_token %}
{{ render_form }}
<input type="submit" value="Submit" class='btn' id="submitbutton" name="_submit" />
</form>
I want to keep render() and I would like to avoid using locals().
Depends on your Django version, but the render method used to take two context related arguments, context and context_instance, the latter expects a Context or RequestContext object, the first a dictionary. The documentation has some specific deprecation details:
https://docs.djangoproject.com/en/1.8/topics/http/shortcuts/#optional-arguments