Django simple Post request is not working - django

I am new to Django and trying to build a simple web page. I am trying for post request but there no values getting inserted into the database.I hope the problem should be in views.py forms.is_valid() Since no logs are recorded after this line.Please assist
model.py
from django.db import models
from django.contrib.auth.models import User
from django.db.models import Q
from django.forms import ModelForm
from django import forms
# Create your models here.
class aws_cred(models.Model):
aws_access_user_id = models.ForeignKey(User,null=False,related_name="aws_acc_user")
access_key = models.CharField(max_length=300)
secret_key = models.CharField(max_length=300)
class aws(ModelForm):
class Meta:
model = aws_cred
fields = ['access_key','secret_key','aws_access_user_id']
views.py
from django.shortcuts import render_to_response,HttpResponseRedirect,render,redirect,reverse
from django.contrib.auth.decorators import login_required
from django.template import RequestContext
from s3comp.models import aws_cred,aws
import logging
#login_required
def fileinput(req):
logging.basicConfig(filename='log_filename.txt',level=logging.DEBUG, format='%(asctime)s - %(levelname)s - %(message)s')
if req.method == 'POST':
form = aws(req.POST)
logging.debug(form)
try:
logging.debug('step 4')
if form.is_valid():
logging.debug('step 5')
access_key_val = req.POST.get('access key','')
secret_key_val = req.POST.get('secret key','')
aws_access_user_id_val = req.POST.get('aws access user id', '')
logging.debug(access_key_val+" " +secret_key_val+" " +aws_access_user_id_val)
cred_obj = aws(access_key = access_key_val,secret_key =secret_key_val,aws_access_user_id = aws_access_user_id_val)
cred_obj.save()
return HttpResponseRedirect(reverse('s3comp:fileinput'))
except Exception as e:
logging.debug(e)
else:
form = aws()
return render(req,'s3comp/fileinput.html',{'form':form})
html file
<form action="{% url 'fileinput_home' %}" method="post">
{% csrf_token %}
<p><label for="Aws access user id">User:</label><input type="text" name="Aws access user id" value={{ user.get_username }}/></p>
<p><label for="Access Key">Access Key:</label><input type="text" name="Access Key"/></p>
<p><label for="Secret Key">Secret Key:</label><input type="text" name="Secret Key"/></p>
<input type="submit" value="Submit">
</form>

You are using wrong name attribute value in template and views, So update according to below code
<form action="{% url 'fileinput_home' %}" method="post">
{% csrf_token %}
<p><label for="Aws access user id">User:</label><input type="text" name="aws_access_user_id" value={{ user.get_username }}/></p>
<p><label for="Access Key">Access Key:</label><input type="text" name="access_key"/></p>
<p><label for="Secret Key">Secret Key:</label><input type="text" name="secret_key"/></p>
<input type="submit" value="Submit">
</form>
Views.py
access_key_val = req.POST.get('access_key','')
secret_key_val = req.POST.get('secret_key','')
aws_access_user_id_val = req.POST.get('aws_access_user_id', '')

Related

How to use Django-simple-captcha on the admin login page?

I would like to add captcha on my django login form using Django Simple Captcha found here: http://code.google.com/p/django-simple-captcha/
This works great if you create a new form but I'm using the django.contrib.auth.forms the one that comes with django. Any idea how I might be able to implement captcha with the existing django auth views or any ways? Thank you!
Please do not suggest using Google reCaptcha.
My urls.py
from django.contrib.auth import views as auth_views
urlpatterns = [
path('login/', auth_views.LoginView.as_view(template_name='login.html'), name='login')
,...
]
My login.html
<form class="fadeIn second" method="post">
{% csrf_token %}
{{ form.as_p }}
<button type="submit" class="btn btn-primary"> Login </button>
</form>
My Forms.py
from captcha.fields import CaptchaField
class MyFormCaptcha(forms.Form):
captcha = CaptchaField()
This video and this GitHub project solved my problem. You can customize the project code according to your needs. For me it is as follows.
My urls.py
urlpatterns = [
...
path('captcha/',include('captcha.urls')),
path('submit',submit,name='submit')
]
My forms.py
from captcha.fields import CaptchaField
class MyForm(forms.Form):
captcha=CaptchaField()
My login.html
<form action="/submit" method="post">
{% csrf_token %}
<div>
<label for="fullname">Full Name</label>
<input type="text" id="fullname" name="fullname">
</div>
<br>
<div>
<label for="email">Email</label>
<input type="text" id="email" name="email">
</div> <br>
{{form.captcha}}
<button type="submit">Submit</button>
</form>
My views.py How to log a user in?
from django.contrib.auth import authenticate, login
def test(request):
form=MyForm()
return render(request,'captcha/home.html',{'form':form})
def submit(request):
if request.method == 'POST':
form=MyForm(request.POST)
if form.is_valid():
name=request.POST['fullname']
email=request.POST['email']
print('success')
print(name)
print(email)
user = authenticate(request,username=username,password=password)
if user is not None:
login(request, user)
return redirect('/homepage') # Redirect to a success page.
else:
# Return an 'invalid login' error message.
print('fail')
messages.success( request,f 'login failed! username or passwoed is wrong!'
return redirect('login')

Uploading image through an upload form to Django User profile

I am trying to create a student register page that allows the student to upload a profile photo. I am using Django User model and a StudentProfile model that has a OneToOne relation with User. Here are my codes:
student\models.py:
from django.db import models
from django.contrib.auth.models import User
class StudentProfile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE,)
avatar = models.ImageField(upload_to='student_profile/', null=True, blank=True)
def __str__(self):
return self.user.username
students/form.py:
from django import forms
class ImageUploadForm(forms.Form):
profile_photo = forms.ImageField()
eLearning/views.py:
from django.contrib.auth import authenticate, login, get_user_model
from django.http import HttpResponse
from django.shortcuts import render, redirect
from .forms import LoginForm, RegisterForm
from students.forms import ImageUploadForm
from students.models import StudentProfile
User = get_user_model()
def register_page(request):
register_form = RegisterForm(request.POST or None)
photo_upload_form = ImageUploadForm(request.POST, request.FILES)
context = {
"register_form": register_form,
"photo_upload form": photo_upload_form
}
if register_form.is_valid():
# print(register_form.cleaned_data)
username = register_form.cleaned_data.get("username")
first_name = register_form.cleaned_data.get("first_name")
last_name = register_form.cleaned_data.get("last_name")
email = register_form.cleaned_data.get("email")
password = register_form.cleaned_data.get("password")
new_user = User.objects.create_user(
username, email, password,
first_name=first_name,
last_name=last_name,
)
if photo_upload_form.is_valid():
user = username
avatar = photo_upload_form.cleaned_data.get("profile_photo")
new_user_profile = StudentProfile.objects.create(user, avatar)
print(new_user)
return render(request, "auth/register.html", context)
auth/register.html:
{% extends "base.html" %}
{% load static %}
{% block content %}
{% load crispy_forms_tags %}
<div class="container">
<div class="row my-4">
<div class="col-5">
<form action="" method="post" class="form-control">
{% csrf_token %}
{{ register_form|crispy }}
<input type="submit" class="btn btn-default" value="Submit">
</form>
</div>
<div class="col-5">
<form method="post" enctype="multipart/form-data" class="form-control">
{% csrf_token %}
<input id="id_image" type="file" class="my-2" name="image">
{{ photo_upload_form|crispy }}
</form>
</div>
</div>
</div>
{% endblock %}
I am facing 2 problems:
1) The ImageUploadForm is not rendering on to register.html
2) A StudentProfile is not being created. User is being created fine.
I also tried replacing form with ModelForm for ImageUploadForm but I get a NULL constraint for student_user since Django doesn't what user for StudentProfile is.
I have been looking through Stack Overflow. All solutions are about how to upload a user image to Django admin but I haven't found anything that shows how to associate the uploaded image to User model during registration. Forgive me if this is a repeated question. Thanks.
In your eLearning/views.py:
the context you are passing to the html page the _ is missing
context = {
"register_form": register_form,
"photo_upload form": photo_upload_form
}
This will be the reason for the ImageUploadForm is not rendering on to register.html
It's should be like
context = {
"register_form": register_form,
"photo_upload_form": photo_upload_form
}
So I figured it out. The real issue was with the register.html code. The submit button only worked for the register_form so the photo upload form was not validating, hence student profile entry was not being created. Here's the updated code:
eLearning/views.py:
from students.forms import ImageUploadForm
from students.views import upload_pic
def register_page(request):
register_form = RegisterForm(request.POST or None)
photo_upload_form = ImageUploadForm(request.POST, request.FILES)
context = {
"register_form": register_form,
"photo_upload_form": photo_upload_form
}
if register_form.is_valid():
username = register_form.cleaned_data.get("username")
first_name = register_form.cleaned_data.get("first_name")
last_name = register_form.cleaned_data.get("last_name")
email = register_form.cleaned_data.get("email")
password = register_form.cleaned_data.get("password")
new_user = User.objects.create_user(
username, email, password,
first_name=first_name,
last_name=last_name,
)
upload_pic(request, photo_upload_form, username=username)
return render(request, "auth/register.html", context)
students/views.py:
from django.contrib.auth import get_user_model
from django.http import HttpResponseRedirect
from django.shortcuts import render, redirect, HttpResponse
from .models import StudentProfile
from .forms import ImageUploadForm
def upload_pic(request, form, username):
if request.method == 'POST':
if form.is_valid():
User = get_user_model()
user = User.objects.get(username=username)
avatar = form.cleaned_data.get('profile_photo')
new_user_profile = StudentProfile.objects.create(user=user, avatar=avatar)
new_user_profile.save()
register.html:
{% extends "base.html" %}
{% load static %}
{% block content %}
{% load crispy_forms_tags %}
<div class="container">
<div class="row my-4">
<div class="col-5">
<form action="" method="post" enctype="multipart/form-data" class="form-control">
{% csrf_token %}
{{ register_form|crispy }}
{{ photo_upload_form|crispy }}
<input type="submit" class="btn btn-default" value="Submit">
</form>
</div>
</div>
</div>
{% endblock %}
You have to make sure enctype="multipart/form-data" is inside your tags or the image upload form will not get validated. I would also recommend adding an image validation method to your form.py. Something Sachin pointed out earlier: image form and validation. Hope this helps.

Form.is_valid() returns False?

Why am I asking question despite already been asked? I read many question posted on Stack Overflow but I am not able to fix the code as I am new to Python Language.
What am I trying to do: Simply trying to take the input from user and return an HttpResponse (if successfully). Otherwise, an error HttpResponse message to return.
Problem : The MyForm.is_valid() in Forms.py is always returning False! I tried many solutions posted on previous questions and also read the documentary thrice but not able to understand, what am I doing wrong?
Views.Py
from django.http import HttpResponse
from .forms import PostForm
.
.
. <<code here>>
def register(request):
if request.method == 'POST':
Myform = PostForm(request.POST)
if Myform.is_valid():
return HttpResponse("<h1>Is_Valid is TRUE.</h1>")
else:
return HttpResponse("<h1>Is_Valid is False.</h1>")
else:
return HttpResponse("<h1> GET REQUEST>>>> </h1>")
Forms.Py
from django.forms import ModelForm
from .models import Post
class PostForm(ModelForm):
class Meta:
model= Post
fields = ['Username']
Models.Py
from django.db import models
class Post(models.Model):
Username = models.CharField(max_length = 20)
def __str__(self):
return self.name
HTML CODE
{% block body %}
<div class="container-fluid">
<form method="POST" class="post-form" action="{% url 'submit' %}">
{% csrf_token %}
<div class="form-group"> <!-- Full Name -->
<label for="Username" class="control-label">Full Name</label>
<input type="text" class="form-control" id="Username" name="full_name" placeholder="Enter the name of Patient here.">
</div>
<div class="form-group"> <!-- Submit Button -->
<button type="submit" class="btn btn-primary"> Submit!</button>
</div>
</form>
</div>
<hr/>
{% endblock %}
Urls.Py
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^/submit$', views.register , name = 'submit'),
]
The name of your input should be username:
This is how you send this value to the form.
NOTE: It's better to use the django form, that you've already done with ModelForm
<input type="text" class="form-control" id="username" name="username" placeholder="Enter the name of Patient here.">

DJANGO - Redirect to different page with form data

Hi i want to redirect to a destination page with the from data. For example when user fills a form the data inputted in the form, i want that to be outputted on the destination page
my codes are as follows:-
source page(experiment.html), I am unsure what the action should be for the form so please help me with it
<form action="{% url 'lazer.views.about_experiment' exp.link_name %}" method="POST">
{% csrf_token %}
<label>Researcher Name(s):<input type="text" name="researcher">
<lable>Study Summary<textarea rows="10" cols="50" placeholder="here you go" maxlength="500" class="form-control" name="study"></textarea>
<br>
<input type = "submit" value="Submit" class="btn btn-primary" />
</form>
destination page (about_experiment.html)
<h3>Holding page for {{ exp.name }}.</h3>
<h2> {{ form }} </h2>
views.py
from .forms import AboutHelp
from django.shortcuts import render
from django.http import HttpResponseRedirect
def about_experiment(request):
if request.method == 'POST':
form = AboutHelp(request.POST)
if form.is_valid():
researcher = form.cleaned_data['researcher']
study = form.cleaned_data['study']
else:
form = AboutHelp()
return render(request, 'about_experiment.html', {'form': form})`
forms.py
from django import forms
class AboutHelp(forms.Form):
researcher = forms.CharField(max_length=100)
study = forms.CharField(max_length=500)
urls.py
url(r'^about/(?P<ex_link_name>\w+)', lazer.views.about_experiment, name='lazer.views.about_experiment'),

django 1.10 csrf_token not creating hidden input field

I have a form, but Django is not creating a hidden input like -
<input type="hidden" name="csrfmiddlewaretoken" value="80NGejzAPl2aCbEEuyLqIT3ppMTJLilY">
If trying send a form I have 403 mistake, CSRF token missing or incorrect.
This is my code:
html
<form class="get-info" action="{% url 'callback:send_callback' %}" method="post">{% csrf_token %} ... </form>
middleware
'django.middleware.csrf.CsrfViewMiddleware',
views.py
from django.core.mail import BadHeaderError, send_mail
from django.http import HttpResponse, HttpResponseRedirect, request
from django.shortcuts import render, render_to_response
from django.template import RequestContext
from django.template.context_processors import csrf
from django.contrib import messages
def callback(request):
phone = request.POST.get('phone', None)
lastpath = request.POST.get('lastpath', None)
if validatePhone(phone):
if sendMail(phone):
messages.success(request, 'Мы скоро перезвоним Вам')
return HttpResponseRedirect(lastpath)
else:
messages.error(request, 'Ошибка в отправке запроса. Попробуйте позже.')
return HttpResponseRedirect(lastpath)
else:
messages.error(request, "Неверный формат номера телефона. Телефон нужно вводить в формате +99999999999")
args = {}
zzz = lastpath.render(RequestContext(request, args))
return HttpResponse(zzz)
Callback url -
urlpatterns = [
url(r'^callback/', views.callback, name='send_callback'),
]
Form rendering on the main page:
<form class="get-info" action="/callback/callback/" method="post">
<input type="hidden" name="_subject" value="karpaty-perezvonite-mne">
<input id="callback" name="phone" type="tel" class="form-control" placeholder="+ 380 ___-__-__">
<input type="text" class="form-control" placeholder="" name="lastpath" value="/" style="display: none">
<button type="submit" class="btn btn-default" value="Send">Отправить</button>
</form>
I'm trying submit form to the main page - "/" and now have such mistake
UserWarning: A {% csrf_token %} was used in a template, but the context did not provide the value.
This is usually caused by not using RequestContext.
How can I fix it?