post django form data via iframe - django

I have a django form that I want to display on another website via iframe. The form displays ok but whenever I try to submit the form that is displayed in the iframe, I get a "server refused to connect" error message.
Is it possible to make a django form work with iframe or is there a better way to do it?
The views code for the form:
from django.views.decorators.clickjacking import xframe_options_exempt
#xframe_options_exempt
def booking_create_view(request):
form=BookingForm
submitted = False
if request.method=='POST':
form = BookingForm(request.POST)
if form.is_valid():
form.save()
return HttpResponseRedirect('/?submitted=True')
else:
form = BookingForm
if 'submitted' in request.GET:
submitted = True
return render(request, "booking_form.html",{'form':form, 'submitted': submitted})
HTML for the form:
<form class="" action="" method= POST>
<div class="form-group">
{% csrf_token %}
{{ form.as_p }}
<input type="Submit" value="Submit" class = "btn btn-secondary">
</form>
{% endif %}
The iframe:
<h1>The iframe element</h1>
<iframe src="http://127.0.0.1:8000/" title="test">
</iframe>
Note: I have also tried using a live server (pythonanywhere) that had the same result

Related

Overriding django-allauth views to use with modals

I am trying to handle login/registration functionality in a modal. I got successful login/registration working by importing the LoginForm and RegistrationForm into my modal view and then posting to the appropriate allauth URLs. The desired behavior is to have forms with errors rendered asynchronously in the modal.
I have not been able to get forms with errors (email doesn't exist when trying to login, passwords don't match when registering etc.) to render as an html partial in a modal with the errors. I'm not too sure where to start when trying to add this functionality into my own view/how to piggyback on the allauth views and change their functionality.
Adding the below to my views.py and url.py I've managed to get the allauth default template to load when the form is invalid (e.g. email field does not contain a valid email) but have not been able to get my template to load.
From views.py:
class LoginViewSnippet(LoginView):
success_url = reverse_lazy('home')
template_name = 'user_app/partials/loginmodal.html'
def get_context_data(self, **kwargs):
print('here1')
context = super(LoginView,self).get_context_data(**kwargs)
return context
def form_invalid(self, form):
print('here')
error_msg = 'error'
return HttpResponse(error_msg, status=400)
login = LoginViewSnippet.as_view()
From urls.py:
path('accounts/login',user_app_views.login, name='account_login'),
From user_app/partials/loginmodal.html:
...
<div class="modal-body">
<form id="loginform" method="POST" action="{% url 'account_login' %}" autocomplete="off">
{% csrf_token %}
{% for field in loginform %}
<div class="form-group mb-3">
{{ field.errors }}
{{ field | as_crispy_field }}
</div>
{% endfor %}
</form>
</div>
<div class="mx-auto">
<button form="loginform"type="submit" class="btn btn-success" hx-post="{% url 'account_login' %}" hx-target="#modals-here">Login</button>
<button type="button" class="btn btn-secondary" onclick="closeModal()">Close</button>
</div>
...

How do you render form from views in template without model?

I have a problem with my Django Code.I'm trying to render a form from views to template and i'm just seeing the submit button. I noticed that we can use forms dynamically by introducing it like this {{ form }}, but when I use it, I just see the "submit" button on the page(Sorry I don't know how to upload a local image here). I join my four files: views.py, home.html, forms.py and urls.py
Thank you in advance
home.html
<form method="POST" novalidate action="/config">
{% csrf_token %}
<fieldset>
<legend class="border-bottom mb-4">Home</legend>
{{ form.as_p }}
</fieldset>
<div class="form-group">
<button class="btn btn-outline-info" type="submit">Sign Up</button>
</div>
</form>
views.py
def inputHome(request):
form = InputHomeForm()
if request.method == 'POST':
form = InputHomeForm(request.POST)
if form.is_valid():
mk = form.cleaned_data['mk']
return HttpResponseRedirect('blog-config')
else:
form = InputHomeForm()
return render(request, 'blog/home.html', {'form': form})
forms.py
class InputHomeForm(forms.Form):
mk = forms.CharField(widget=forms.TextInput(attrs={'class': 'special'}))
urls.py
urlpatterns = [
path('home/', blog_views.home, name='blog-home'),
]
I don't have an error message so i don't have an idea of the problem.
You are missing form tag in html.
HTML should be,
<form method='post'>
{% csrf_token %}
<fieldset>
<legend class="border-bottom mb-4">Home</legend>
{{ form.as_p }}
</fieldset>
<div class="form-group">
<button class="btn btn-outline-info" type="submit">Sign Up</button>
</div>
</form>
Slightly unrelated (cf Nishant's answer for the main issue), but here:
if request.method == 'POST':
form = InputHomeForm(request.POST)
if form.is_valid():
mk = form.cleaned_data['mk']
return HttpResponseRedirect('blog-config')
else:
form = InputHomeForm()
In the else clause, you're replacing the bound invalid form (which carries the validation errors) with an unbound form, so you'll never get the error messages. Just remove the whole else clause.

Multiple POST request is not working after submit

I am trying to use 2 post method in a single page one is for login and other one is for contact us
login is working fine but after submitting contact us the content of login and contact us page is gone
I tried to pass various type of dictionary but still, it's not working
app/views.py
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render
from homePage.forms import SignInForm,DropUsaMessage
# Create your views here.
def homePage(request):
if request.method == 'POST' and 'SignIn' in request.POST:
sign_in_detail = SignInForm(request.POST)
if sign_in_detail.is_valid():
return render(request, "index2.html",{})
elif request.method == 'POST' and 'SendMessage' in request.POST:
message_detail = DropUsaMessage(request.POST)
if message_detail.is_valid():
return render(request, "index.html",{})
else:
sign_in_detail = SignInForm()
message_detail = DropUsaMessage()
context={
"form":sign_in_detail,
"forms":message_detail
}
return render(request, "index.html",context)
index.html
<div class="container contact-form">
<form method="post">
<h3>Drop Us a Message</h3>
{% csrf_token %}
{{ forms }}<br><br>
<div class="form-group">
<input type="submit" name="SendMessage" class="btnContact" value="Send Message" />
</div>
</form>
</div>
<div class="container-fluid">
<div class="row">
<div class="col-md-8">
<img src="{% static 'img/sampleImage.jpg' %}" width="100%" height="100%" class="d-inline-block align-top" alt="">
</div>
<div class="col-md-4">
<form method="POST">
{% csrf_token %}
{{ form }}
<div class="form-check">
<span class="fpswd">Forgot password?</span>
</div>
<button type="submit" class="btn btn-primary" name="SignIn">Submit</button>
</form>
</div>
</div>
</div>
app/forms.py
from django import forms
from django.core import validators
class SignInForm(forms.Form):
email=forms.EmailField(widget=forms.EmailInput(attrs={"class": 'form-control',"placeholder":'Enter E-mail',"id": 'exampleInputEmail1'}))
password=forms.CharField(widget=forms.PasswordInput(attrs={"class":'form-control',"placeholder":'Enter Password',"id":'exampleInputPassword1'}))
class DropUsaMessage(forms.Form):
name = forms.CharField(widget=forms.TextInput(attrs={"class":'form-control',"placeholder":'Your Name'}))
email = forms.EmailField(widget=forms.EmailInput(attrs={"class": 'form-control',"placeholder":'Your E-mail',"id": 'exampleInputEmail1'}))
phone = forms.IntegerField(widget=forms.NumberInput(attrs={"class":'form-control',"placeholder":'Your Phone Number'}))
message = forms.CharField(widget=forms.Textarea(attrs={"class":'form-control',"placeholder":'Type Your Message',"style":'width:100%; height: 150px'}))
Expected Result:
After filling up the contact us form the field will be there.
Actual result:
there is no field in Contact us(except Send Message button) and no field in SignInForm(no e-mail and no password).
Just follow the code flow and you'll notice that in the case of a POST request and "SignIn" in the post, you return the rendered "index2.html" template without any context (form and forms will be undefined in your template). Idem for the other case:
return render(request, "index2.html", {}) # empty context
Worse, if the form posted is not valid, you'll notice you only define one for the forms and not the other one, so when the code execution reaches the line context = {"form": ..., "forms": ...}, one of them will be undefined and your view will "crash", return a 500 error.
context = {'form': sign_in_detail, # sign_in_detail never defined for second "if"
'forms': message_detail} # message_detail never define for first "if"
In general, when a POST is successful, you should always redirect to another view (or the same view). That's the internet convention, in order to avoid page reload issues that would resubmit the same data. Do this:
return redirect('home') # or whatever your homepage url pattern is called
Also, it would make more sense to post your forms to different views (change the action attribute of each of your <form> tags) so you can process them in separate views which is cleaner code:
<form action="{% url 'create_message' %}" method="post">

Django forms - rendering form and redirecting

I am trying to create an 'add user' feature which will simply add the user you've selected from a dropdown as your connection. I am using ModelChoiceField from Django Forms so that I may get the existing users from my User model in the dropdown.
forms.py
from django import forms
from django.contrib.auth.models import User
class NetworkForm(forms.Form):
user_id = forms.ModelChoiceField(queryset=User.objects.all(), label='',
widget=forms.Select(attrs={'class': 'all_users'}))
views.py
#login_required
def index(request):
user_list = User.objects.exclude(username=request.user)
return render(request, 'chat/index.html', {'user_list': user_list})
For now I am just printing the form to see output
#login_required
def add_user(request):
form = NetworkForm()
if request.method == 'POST':
form = NetworkForm(request.POST)
if form.is_valid():
print form
return redirect(request.META['HTTP_REFERER'])
errors = form.errors or None
return render(request, 'chat/index.html', {
'form': form,
'errors': errors,
})
index.html
<div class="row">
<form action="{% url 'chat:add_user' %}" method="post">
{% csrf_token %}
{{ form.as_p }}
<button class="btn btn-warning" value="{{ user_id }}" style="float: left;">Submit</button>
</form>
</div>
urls.py
urlpatterns = [
url(r'^$', views.index, name='index'),
url(r'^add_user/$', views.add_user, name='add_user'),]
The way it is being rendered currently is: I have my main index page where I don't see any dropdown, i.e.,
When I click on the submit button, it moves me to index/add_user, where I get a dropdown with user (with a warning "this field is required) and a submit button again.
Finally, when I choose a user in this new page and hit submit, finally the form is printed, which I want ultimately.
What I would want it, have the complete form with dropdown in the index page itself and remain there when I submit the form. I will then hook that to show user the users they have added beneath that form itself ('print' is just for debugging purpose - not a good way I've heard though).
I understand the post request will have to go to add_user page and I can redirect back from that. I have tried various alternatives for the past 6 hours, nothing works yet. Apologies for a long one, giving out information as much as possible. Thanks very much guys. You are awesome.
Edit
Have been now rendering the form in index page (suggestion from #fazil-zaid ), but the issue remains as in only 'submit' button appears on index initially, unless when I hit submit after which the dropdown and submit appears. Again, on clicking the second time, the form is submitted.
Edit-2
I am thinking that:
<form action="{% url 'chat:index' %}" method="post">{% csrf_token %}
{{ form.as_p }}
<button class="btn btn-warning" value="{{ user_id }}" style="float: left;">Submit</button>
</form>
this might be where the problem is, as per current logic unless user takes form's action, i.e., clicks the button {{ form.as_p }} will not appear. Then I tried:
{{ form.as_p }}
<form action="{% url 'chat:index' %}" method="post">{% csrf_token %}
<button class="btn btn-warning" value="{{ user_id }}" style="float: left;">Submit</button>
</form>
Doesn't work still. POST request doesn't send any data (understandably so).
If you want the form to be in the index page, then you could include it in the index view itself.
def index(request):
if request.method == 'POST':
form = NetworkForm(request.POST)
if form.is_valid():
#do what you wanna do
#with the form data.
else:
form = NetworkForm()
render(request, 'chat/index.html', { 'form': form})
In the template,
<div class="row">
<form action="" method="post">
{% csrf_token %}
{{ form.as_p }}
<button class="btn btn-warning" value="{{ user_id }}" style="float: left;">Submit</button>
</form>
</div>
You are not rendering another template, but the same 'index.html'. Then, multiple view for that is just redundant. Index page could contain the form and render itself. From what I understand, there's no need of redirections.
There's no need of add_user view if you're showing the form in the index page itself.
For your issue, try changing the "class" attribute of the form fields, maybe something like this,
class NetworkForm(forms.Form):
user_id = forms.ModelChoiceField(queryset=User.objects.all(), widget=forms.Select(attrs={'class': 'form-control'}))
Solution:
When the page is called in the first instance using GET, the form is not valid as it seeks a POST method. Hence, all the method need to be changed to POST in the view, i.e.,
#login_required
def index(request):
user_list = User.objects.exclude(username=request.user)
form = NetworkForm()
if request.method == 'POST':
form = NetworkForm(request.POST)
if form.is_valid():
print form.data
return redirect(request.META['HTTP_REFERER'])
return render(request, 'chat/index.html', {
'user_list': user_list,
'form': form,
})
Earlier, index was using a GET to render data to index page, and using a POST to use the form. Now, everything works fine.
Special shout-out to #fazil-zaid for the heads-up since you mentioned to include everything in the index view itself, rather than making a separate view for form. Your code pointed that out in a way in addition to Stack here.

Upload html in Django

Code in template:
<form action="/html/" method="post" enctype="multipart/form-data">
{% csrf_token %}
<input type="file" id="html_file" name="html_file" />
<input type="submit" value="Upload" />
</form>
and in view
def add_html(request):
if request.POST:
#do something with html
return redirect('/')
else:
return render_to_response('add_html.html')
I need to html-file is loaded and read its contents, not upload to the server.
But I get an error:
csrf token missing or incorrect
How fix?
My guess is that the {% csrf_token %} is empty when your template is rendered.
Per the CSRF documentation you should use the render function instead of the render_to_response function to ensure the RequestContext, which includes the csrf_token, is properly loaded into your template.
You can achieve what you want with the following code:
forms.py:
from django import forms
class ReadFileForm(forms.Form):
file = forms.FileField()
views.py:
from .forms import ReadFileForm
def read_file(request):
form = ReadFileForm()
if request.method == 'POST':
form = ReadFileForm(request.POST, request.FILES)
if form.is_valid():
content = request.FILES['file'].read()
# Do something with content
return render(request, 'read_file.html', locals())
templates/read_file.html:
<html>
<head></head>
<body>
<h3>Read File Content</h3>
<form enctype="multipart/form-data" action="" method="post">
{% csrf_token %}
{{ form }}
<input type="submit" value="Save">
</form>
</body>
</html>