I'm getting MultiValueDictKeyError while using the POST method with Django.
this is my views.py submit function.
it seems like there is an error with the candidateId field and I don't understand why.
def submit_dept_member_application(request, application_id):
cv = request.FILES['cv']
letter = request.FILES['letter']
candidate_id = request.data['candidateId']
rank_id = request.data['requestedRankId']
application_state = {
'candidate_id': candidate_id,
'rank_id': rank_id,
'cv_filename': cv.name,
'letter_filename': letter.name,
}
creator = Profile.objects.get(user=request.user.id)
department = creator.department
applicant = Profile.objects.get(user=candidate_id)
rank = Rank.objects.get(id=rank_id)
try:
application = Application.objects.get(id=application_id)
# TODO - update application
except Application.DoesNotExist:
application = None
if application is None:
application = Application(creator=creator, applicant=applicant, desired_rank=rank,
application_state=application_state, department=department
)
application.save()
create_application_directory(application.id)
ApplicationStep.objects.update_or_create(
application=application, step_name=Step.STEP_1,
defaults={'can_update': True, 'can_cancel': True, 'currentStep': True}
)
copy_to_application_directory(cv, application.id)
copy_to_application_directory(letter, application.id)
addresee = 'devasap08#gmail.com' # TODO: change email to admin address
email_headline = 'New Application Created'
wanted_action = 'application_created'
sendEmail(addresee, email_headline, wanted_action, creator)
addresee = 'devasap08#gmail.com' # TODO: change email to creator address
email_headline = 'Application Successfully Created'
wanted_action = 'application_received'
sendEmail(addresee, email_headline, wanted_action, applicant)
return Response(application.id, status=status.HTTP_200_OK)
any suggestions on how to solve it?
Thank you!
Models.py
from datetime import datetime
from cmrapp import db,login_manager
from flask_login import UserMixin
#login_manager.user_loader
def load_user(user_id):
return Registration.query.get(int(user_id))
class Registration(db.Model,UserMixin):
id = db.Column(db.Integer(),primary_key=True)
regid = db.Column(db.String(),unique=True)
section = db.Column(db.String(),nullable= False)
username = db.Column(db.String(20),unique=True,nullable = False)
password = db.Column(db.String(60),nullable = False)
def __repr__(self):
return f"Registration('{self.username}','{self.regid}')"
class Participation(db.Model):
id = db.Column(db.Integer(),primary_key=True)
pname = db.Column(db.String(20),nullable= False)
pregid = db.Column(db.String(),unique=True)
psection = db.Column(db.String(),nullable=False)
def __repr__(self):
return f"Participation('{self.pname},'{self.pregid}','{self.psection}')"
#login_manager.user_loader
def load_user(mregid):
return Memberdb.query.get(int(mregid))
class Memberdb(db.Model,UserMixin):
id = db.Column(db.Integer(),primary_key=True)
mregid = db.Column(db.String(20),nullable = False,unique=True)
mname = db.Column(db.String(20),unique=True,nullable = False)
mpassword = db.Column(db.String(60),nullable = False)
organizers = db.relationship('Eventdb',backref='owner',lazy=True)
def __repr__(self):
return f"Memberdb('{self.mname}','{self.id}')"
****routes.py****
from flask import render_template,url_for,request,redirect,flash,request
from cmrapp import app,db,bcrypt
from cmrapp.data import fetch
from datetime import datetime,date
from cmrapp.userforms import Registerform,identityform,studentform,memberform,blockform
from cmrapp.models import Registration,Participation,Memberdb
from flask_login import login_user,current_user,logout_user,login_required
#app.route('/')
#app.route('/signup',methods=["GET","POST"])
def signuppage():
if current_user.is_authenticated:
return redirect(url_for('homepage'))
form = Registerform()
if form.validate_on_submit():
hashed_password = bcrypt.generate_password_hash(form.password.data).decode('utf-8')
user = Registration(username = form.username.data, regid = form.regno.data, password =
hashed_password,section=form.section.data )
db.session.add(user)
db.session.commit()
flash(f"Your Account has been Created! {form.username.data}",'success')
return redirect(url_for('sloginpage'))
else:
return render_template('signup.html',title="Sign Up",form=form,consent=consent,diff=diff)
#app.route('/slogin',methods=["GET","POST"])
def sloginpage():
if current_user.is_authenticated:
return redirect(url_for('homepage'))
form = studentform()
if form.validate_on_submit():
user = Registration.query.filter_by(username = form.studentname.data).first()
if user:
if user and bcrypt.check_password_hash(user.password,form.spassword.data):
login_user(user,True)
next_page = request.args.get('next')
return redirect(next_page) if next_page else redirect(url_for('homepage'))
else:
flash(f'Login Unsuccessful ! Check Name and Password.','danger')
return render_template('slogin.html',title ='Student Login',form=form)
else:
flash(f'User doesn\'t exist' ,'danger')
return render_template('slogin.html',title ='Student Login',form=form)
#app.route('/msignup',methods=["GET","POST"])
def msignuppage():
form = memberform()
if form.validate_on_submit():
hashed_password = bcrypt.generate_password_hash(form.memberpassword.data).decode('utf-8')
user = Memberdb(mname = form.membername.data, mregid = form.secureid.data, mpassword =
hashed_password )
db.session.add(user)
db.session.commit()
flash('Your Account has been Created','success')
return redirect('mlogin')
else:
return render_template('msignup.html',title="Member Account",form=form)
# user = user1
#app.route('/mlogin',methods=["GET","POST"])
def mloginpage():
form = memberform()
if form.validate_on_submit():
# if form.membername.data == "Lucky" and form.memberpassword.data == "luckyG2611#":
user = Memberdb.query.filter_by(mname = form.membername.data).first()
if user:
if user and bcrypt.check_password_hash(user.mpassword,form.memberpassword.data):
login_user(user,True)
next_page = request.args.get('next')
return redirect(next_page) if next_page else redirect(url_for('mlist'))
else:
flash(f'Login Unsuccessful ! Check Name and Password.','danger')
return render_template('mlogin.html',title ='Member Login',form=form)
else:
flash(f'User doesn\'t exist' ,'danger')
return render_template('mlogin.html',title ='Member Login',form=form)
****userform.py****
from flask_wtf import FlaskForm
from wtforms import StringField,PasswordField,validators,SubmitField,BooleanField,ValidationError,BooleanField,SelectField,DateField,TextAreaField
from wtforms.validators import DataRequired,Length,EqualTo
from cmrapp.models import Registration,Participation,Memberdb
from flask_login import current_user
class Registerform(FlaskForm):
username = StringField('Name',
validators=[DataRequired(),Length(min=2,max =20),validators.regexp('^[a-
zA-Z\s]+$',message="Name contains only string ! Try Again")])
section = SelectField(u'Section',choices=[('1yr-A', 'Ist-A'),('1yr-B', 'Ist-B'), ('1yr-C','Ist-
C'),('2yr-A', 'Sec-A'),('2yr-B', 'Sec-B'), ('2yr-C','Sec-C'),('3yr-A',
'Third-A'),('3yr-B', 'Third-B'), ('3yr-C','Third-C')],validators=
[DataRequired()],validate_choice=False,coerce=str)
regno = StringField('Registration No.',
validators=[DataRequired(), Length(min=10,max=10),validators.regexp('[19]+
[DBCAG]+\d\d\d',message="Use your Respective Regno.")])
password = PasswordField('Password',
validators=[DataRequired(),Length(min=10)])
submit = SubmitField('Sign Up')
def validate_username(self,username):
user = Registration.query.filter_by(username=username.data).all()
if user:
raise ValidationError('Username Already Exist :(')
def validate_regno(self,regno):
regid = Registration.query.filter_by(regid=regno.data).all()
if regid :
raise ValidationError('Regno. Already Exist :(')
class studentform(FlaskForm):
studentname = StringField('Name',
validators=[DataRequired(),Length(min=2,max =20)])
spassword = PasswordField('Password',
validators=[DataRequired(),Length(min=10)])
studentin = SubmitField('Log In')
class identityform(FlaskForm):
identitypswd = PasswordField(validators=[DataRequired(),Length(min=10)])
submit = SubmitField('Want to join')
def validate_regid(self,pregid):
user1 = Participation.query.filter_by(pregid = current_user.regid.data).all()
if user1 :
raise ValidationError('Already Enrolled :(')
class memberform(FlaskForm):
membername= StringField('Member Name:',
validators=[DataRequired(),Length(min=2,max=20),validators.regexp('^[a-
zA-Z\s]+$',message="Name contains only string ! Try Again")])
memberpassword = PasswordField('Password',validators=[DataRequired(),Length(min=10)])
secureid = StringField('UserId',
validators=[DataRequired(),Length(max=10),validators.regexp('[19]+
[BCA1.]+\d\d\d')])
membersubmit = SubmitField('Get In')
def validate_mname(self,mname):
user1 = Memberdb.query.filter_by(mname = mname.data).all()
if user1 is not None:
raise ValidationError('Username Already Exist :(')
def validate_mregid(self,mregid):
mregid = Memberdb.query.filter_by(mregid = mregid.data).all()
if mregid is not None:
raise ValidationError('Already Exist :(')
i have imported all the required module also but it's not working but the first login page is working . if anybody knows about this .Can anyone help me out of this.
You've coded two #login_manager.user_loaders. When you do that multiple times, the last one wins. (See here)
You'll have to choose which of Registration or Memberdb your app will use to represent a logged-in user.
I am trying to embed the link of the issue id from JIRA.
I want JIRA issue id to be an embedded link to the JIRA.
class ComplainceServer():
def __init__(self, jira_server, username, password, encoding='utf-8'):
if jira_server is None:
error('No server provided.')
#print(jira_server)
self.jira_server = jira_server
self.username = username
self.password = password
self.encoding = encoding
def checkComplaince(self, appid, toAddress):
query = "/rest/api/2/search?jql=issuetype = \"Application Security\" AND \"Prod Due Date\" < now()
request = self._createRequest()
response = request.get(query, contentType='application/json')
# Parse result
if response.status == 200 and action == "warn":
data = Json.loads(response.response)
print "#### Issues found"
issues = {}
msg = "WARNING: The below tickets are non-complaint in fortify, please fix them or raise exception.\n"
issue1 = data['issues'][0]['key']
for item in data['issues']:
issue = item['key']
issues[issue] = item['fields']['summary']
print u"* {0} - {1}".format(self._link(issue), item['fields']['summary'])
print "\n"
data = u" {0} - {1}".format(self._link(issue), item['fields']['summary'])
msg += '\n'+ data
SOCKET_TIMEOUT = 30000 # 30s
email = SimpleEmail()
email.setHostName('smtp.com')
email.setSmtpPort(25)
email.setSocketConnectionTimeout(SOCKET_TIMEOUT);
email.setSocketTimeout(SOCKET_TIMEOUT);
email.setFrom('R#group.com')
for toAddress in toAddress.split(','):
email.addTo(toAddress)
email.setSubject('complaince report')
email.addHeader('X-Priority', '1')
email.setMsg(str(msg))
email.send()
def _createRequest(self):
return HttpRequest(self.jira_server, self.username, self.password)
def _link(self, issue):
return '[{0}]({1}/browse/{0})'.format(issue, self.jira_server['url'])
This is the calling function. APPid and toAddress will be passed in from different UI.
from Complaince import ComplainceServer
jira = ComplainceServer(jiraServer, username, password)
issues = jira.checkComplaince(appid, toAddress)
I want issueid to be an embedded link.
currently the email sends as below:
MT-4353(https://check.com/login/browse/MT-4353) - Site Sc: DM isg_cq5
but i want [MT-4353] as hyperlink to the URL https://check.com/login/browse/MT-4353
I'm having the worst time with this one. In a view I created a csv file that's saved to memory. I need to get that csv file to a utils.py function and post to an external api. I for the life of me can not figure out how to do this and it's really driving me nuts.
I originally was just trying to create it in the run_test_suite_in_hatit function below and then somehow open it in the run_all_modal below but that wasn't working. What occurred below was the file (hatit_csv_filename) was now a message object. I don't want to save it to a model as its temporary and is being created purely to be sent right in a api post within HATScript() which is in a utils.py file within the same app in the my project. I'm not sure how to get the file to HATScript() which is just making me nuts.
def run_test_suite_in_hatit(request):
testrail_suite_id = int(request.GET['suite'])
print(testrail_suite_id)
testrail_instance = TestRailInstance.objects.first()
project = request.user.humanresource.project
testrail_project_id = project.testrail.project_id
testrail_project = get_testrail_project(testrail_instance, testrail_project_id)
testrail_suites = testrail_project.get_suites()
testrail_suite = [s for s in testrail_suites if s.id == testrail_suite_id][0]
testrail_cases = testrail_suite.get_cases()
hatit_csv_filename = bulk_hatit_file_generator(testrail_cases)
messages.add_message(request, messages.INFO, hatit_csv_filename)
return HttpResponseRedirect('/run_all_modal/')
def run_all_modal(request):
if request.method == 'POST':
form = TestRunnerForm(request.POST)
if form.is_valid():
data = form.cleaned_data
scripts = get_messages(request)
csvfile = ""
for script in scripts:
csvfile = script
hs = HATScript()
hs.apn = data.get('apn')
hs.holly_server = data.get('browser')
hs.basic_connection_test()
response = hs.hatit_execute()
else:
print(form.errors)
return JsonResponse({'success': True})
EDIT: SOLVED
I have been bashing my head over this and it was so obvious what I needed to do !
Updated View functions:
def run_test_suite_in_hatit(request):
testrail_suite_id = int(request.GET['suite'])
testrail_instance = TestRailInstance.objects.first()
project = request.user.humanresource.project
testrail_project_id = project.testrail.project_id
testrail_project = get_testrail_project(testrail_instance, testrail_project_id)
testrail_suites = testrail_project.get_suites()
testrail_suite = [s for s in testrail_suites if s.id == testrail_suite_id][0]
testrail_cases = testrail_suite.get_cases()
hatit_csv_filename = bulk_hatit_file_generator(testrail_cases)
**HATScript.csvfile = hatit_csv_filename**
return 'runner/run_all_modal.html'
def run_all_modal(request):
if request.method == 'POST':
form = TestRunnerForm(request.POST)
if form.is_valid():
data = form.cleaned_data
hs = HATScript()
**hs.csvfile = HATScript.csvfile**
hs.apn = data.get('apn')
hs.holly_server = data.get('browser')
response = hs.hatit_execute()
print(response.status_code)
else:
print(form.errors)
return redirect('runner:dashboard')
I was trying to send to a function within a class and populate the variables with the appropriate data but because the data was coming from 2 different Views I was beside myself on how to achieve this. I have tried so many ridiculous things. I removed any proprietary bits.
class HATScript(AutomationScript):
def __init__(self, apn='', body='', dialed_number='',
holly_server='', sonus_server='',
hatit_server='',
remote_server=' ', remote_user='', remote_password=''):
self.csvfile = ''
self.hatit_server = hatit_server
self.apn = apn
self.dialed_number = dialed_number
self.body = body
self.filename = ''
self.holly_server = holly_server
self.sonus_server = sonus_server
self.remote_server = remote_server
self.remote_user = remote_user
self.remote_password = remote_password
def hatit_execute(self):
"""Uses Frank's HAT User Interface to initate a HAT test"""
browser = requests.session()
stuff = browser.get('http://{0}/hatit'.format(self.remote_server))
print(stuff.status_code)
data = {'apn': self.apn,
'browser': self.holly_server,
'port': '5060'}
response = browser.post("http://{0}/".format(self.hatit_server), data=data, files={'csvfile': open(self.csvfile)})
print(response.text)
browser.close()
return response
Essentially I was able to assign the variable the file in the run_test_suite_in_hatit(request) function and had to this SO question helped me understand working with Class variables and assigning to them etc. Which helped me solve the issue I've been having for so long that I came into work on it more on a Saturday night.
I've come a ways, but have trouble pulling data from my form. Below is my form and its post() method. validation is working ok, but how to get 'cleaned' data in app engine's version of django?
def get_type():
return [(str(type.key()), type.name) for type in GreType.all()]
class LatField(forms.Field):
def clean(self,value):
x = None
try:
x = float(value)
if x > 90.0 or x < -90.0:
x = None
except:
x = None
if x is None:
raise forms.ValidationError("Latitude should be a number between 90.00 and -90.00")
class LonField(forms.Field):
def clean(self,value):
x = None
try:
x = float(value)
if x > 180.0 or x < -180.0:
x = None
except:
x = None
if x is None:
raise forms.ValidationError("Longitude should be a number between 180.00 and -180.00")
class LocationForm(forms.Form):
type = forms.ChoiceField(choices=get_type())
name = forms.CharField(max_length=100)
desc = forms.CharField(widget=forms.Textarea(), required=False)
lat = LatField()
lon = LonField()
class LocationHandler(webapp.RequestHandler):
def get(self):
template_data = { 'form' : LocationForm() }
template_path = os.path.join(os.path.dirname(__file__), '../template/location.html')
self.response.headers['Content-Type'] = 'text/html'
self.response.out.write(template.render(template_path, template_data))
def post(self):
data = LocationForm(data=self.request.POST)
if data.is_valid():
# what to do here?
self.redirect('/locations')
my validation routines probably have some redundancy, but i'm not clear about python scope
I passed on a model based form (earlier question) to get separate lat and lon fields.)
Cleaned data available in self.cleaned_data. This example worked correctly:
class BlogCreateForm(forms.ModelForm):
class Meta:
model = Blog
exclude = ('author',)
def clean_slug(self):
'''Prevent duplicate blogs with equal key names'''
# blog with given url address already exists
if self.Meta.model.get_by_key_name(self.cleaned_data['slug']):
raise forms.ValidationError("Blog with url '%s' already exists" %
self.cleaned_data['slug'])
return self.cleaned_data['slug']
Replace return self.cleaned_data['slug'] to return self.clean_data['slug'] if you have used builtin version of Django.
Try to use http://gaeframework.com - Python web framework designed for Google App Engine