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!
Related
Following is my code for webhook with a Django application
#csrf_exempt
def webhook(request):
webhook_secret = STRIPE_WEBHOOK_SECRET
payload = request.body.decode('utf-8')
signature = request.META["HTTP_STRIPE_SIGNATURE"]
try:
event = stripe.Webhook.construct_event(
payload=payload, sig_header=signature, secret=webhook_secret)
data = event['data']
except Exception as e:
return e
event_type = event['type']
data_object = data['object']
if event_type == 'invoice.paid':
webhook_object = data["object"]
stripe_customer_id = webhook_object["customer"]
stripe_sub = stripe.Subscription.retrieve(webhook_object["subscription"])
stripe_price_id = stripe_sub["plan"]["id"]
current_period_end = stripe_sub["current_period_end"]
current_period_end = datetime.datetime.fromtimestamp(current_period_end, tz=None)
pricing = Pricing.objects.get(stripe_price_id=stripe_price_id)
user = User.objects.get(stripe_customer_id=stripe_customer_id)
subscription = Subscription.objects.get(user=user)
subscription.status = stripe_sub["status"]
subscription.stripe_subscription_id = webhook_object["subscription"]
subscription.pricing = pricing
subscription.current_period_end = current_period_end
subscription.save()
if event_type == 'customer.subscription.deleted':
webhook_object = data["object"]
stripe_customer_id = webhook_object["customer"]
stripe_sub = stripe.Subscription.retrieve(webhook_object["id"])
user = User.objects.get(stripe_customer_id=stripe_customer_id)
subscription = Subscription.objects.get(user=user)
subscription.status = stripe_sub["status"]
subscription.save()
return HttpResponse()
and the url is
path('webhook/', webhook, name='webhook')
if I check the path https://example.com/webhook/, I am getting the error
Exception Type: KeyError at /webhook/
Exception Value: 'HTTP_STRIPE_SIGNATURE'
and in strpe account I am getting 500 error
It takes the POST request, whenever you hit the URL then it will show you this error because of the GET request.
run these commands:
$ stripe login
$ stripe listen --forward-to localhost:8000/webhook
you can follow this said by stripe itself.
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
in view.py:
#require_POST
#csrf_exempt
def ipn(request):
transactions_logger = logging.getLogger("django")
processor = Ipn(request.POST, logger=transactions_logger)
verification_success = processor.verify_ipn()
encoding = request.POST.get('ok_charset', None)
data = QueryDict(request.body, encoding=encoding)
if verification_success:
form = OkpayIpnForm(data)
if form.is_valid():
print("ALL FINE!!")
form.save()
return HttpResponse("")
In forms.py:
class OkpayIpnForm(forms.ModelForm):
class Meta:
model = OkpayIpn
exclude = []
Code for IPN Checkprocessor = Ipn(request.POST, logger=transactions_logger:
class Ipn(object):
OKPAY_VERIFICATION_URL = 'https://checkout.okpay.com/ipn-verify'
OKPAY_IPN_INVALID = b'INVALID'
OKPAY_IPN_VERIFIED = b'VERIFIED'
OKPAY_IPN_TEST = b'TEST'
OKPAY_STATUS_COMPLETED = 'completed'
__verification_result = False
def __init__(self, request_data, logger):
if 'ok_verify' in request_data:
raise Exception("ok_verify must not be present in initial request data for {}".format(
self.__class__.__name__
))
self._request_data = request_data
self.logger = logger
return
def verify_ipn(self):
self.__verification_result = False
headers = {
'Content-Type': 'application/x-www-form-urlencoded',
}
verify_request_payload = {
'ok_verify': 'true',
}
verify_request_payload.update(self._request_data)
resp = requests.post(self.OKPAY_VERIFICATION_URL, data=verify_request_payload, headers=headers)
if resp.content == self.OKPAY_IPN_VERIFIED or resp.content == self.OKPAY_IPN_TEST:
self.__verification_result = True
# if resp.content == self.OKPAY_IPN_VERIFIED: # anyway disable test on production.
# self.__verification_result = True
return self.__verification_result
All is ok, I revice IPN and validate it, then I try to validate form and save it to Database.
But form doesn't pass validation and doesn't save to database.
Thank You for help
Problem was that 1 CharField of Model for saving IPN has maxlength=20, but recieved 40 symbols.
Thx jape he advised to add in form validation else statement and print form.errors
the error of of form validation was :
<li>ok_item_1_type<ul class="errorlist"><li>Ensure this value has at most 20 characters (it has 40).</li></ul></li>
This is my Model class
class SubJobs(models.Model):
id = models.AutoField(primary_key = True)
subjob_name = models.CharField(max_length=32,help_text="Enter subjob name")
subjobtype = models.ForeignKey(SubjobType)
jobstatus = models.ForeignKey(JobStatus, default= None, null=True)
rerun = models.ForeignKey(ReRun,help_text="Rerun")
transfer_method = models.ForeignKey(TransferMethod,help_text="Select transfer method")
priority = models.ForeignKey(Priority,help_text="Select priority")
suitefiles = models.ForeignKey(SuiteFiles,help_text="Suite file",default=None,null=True)
topofiles = models.ForeignKey(TopoFiles,help_text="Topo file",default=None,null=True)
load_image = models.NullBooleanField(default = True,help_text="Load image")
description = models.TextField(help_text="Enter description",null=True) command = models.TextField(help_text="Command",null=True)
run_id = models.IntegerField(help_text="run_id",null=True)
pid_of_run = models.IntegerField(help_text="pid_of_run",null=True)
hold_time = models.IntegerField()
created = models.DateTimeField(default=timezone.now,null=True)
updated = models.DateTimeField(default=timezone.now,null=True)
finished = models.DateTimeField(null=True)
The user might want to update a entry and may choose to update only few fields among these. How do I write a generic update statement that would update only the fields that were passed?
I tried this.
def update_subjob(request):
if (request.method == 'POST'):
subjobs_subjobid = request.POST[('subjob_id')]
post_data = request.POST
if 'subjob_name' in post_data:
subjobs_subjobname = request.POST[('subjob_name')]
if 'subjob_type' in post_data:
subjobs_subjobtype = request.POST[('subjob_type')]
if 'rerun_id' in post_data:
subjobs_rerun_id = request.POST[('rerun_id')]
if 'priority_id' in post_data:
subjobs_priority_id = request.POST[('priority_id')]
if 'transfer_method' in post_data:
subjobs_transfermethod = request.POST[('transfer_method')]
if 'suitefile' in post_data:
subjob_suitefile = request.POST[('suitefile')]
if 'topofile' in post_data:
subjob_topofile = request.POST[('topofile')]
try:
subjobinstance = SubJobs.objects.filter(id=subjobs_subjobid).update(subjob_name=subjobs_subjobname,
updated=datetime.now())
except Exception as e:
print("PROBLEM UPDAING SubJob!!!!")
print(e.message)
How do I write a generic update to update only those fields which are sent in request.POST?
You'd better use Forms. But if you insist on your code it could be done like this.
Suppose you have variable field_to_update where every field that you are waiting in request is listed.
subjobs_subjobid = request.POST[('subjob_id')]
field_to_update = ('subjob_name','subjob_type', 'rerun_id', 'priority_id', 'transfer_method', 'suitefile', 'topofile')
post_data = request.POST
to_be_updated = {field: post_data.get(field) for field in field_to_update if field in post_data}
# then you need to get the object, not filter it
try:
subjobinstance = SubJobs.objects.get(id=subjobs_subjobid)
subjobinstance.update(**to_be_updated, updated=datetime.now())
except ObjectDoesNotExist: # from django.core.exceptions
print('There is no such object') # better to use logger
except Exception as e:
print("PROBLEM UPDAING SubJob!!!!")
print(e.message)
so I have this model set up with django and mongoengine.
class Product(Document):
product_id = IntField()
title = StringField(max_length=255)
sources = ListField(ReferenceField(Source, dbref = True))
class Source(Document):
source_id = IntField()
source_type = StringField(choices=settings.PARENT_TYPE_CHOICES, max_length=50)
name = StringField(max_length=255)
url = URLField(max_length=2000)
meta = {"allow_inheritance": True}
And in my scrapy pipeline I save the following data:
class SaveItemPipeline(object):
def process_item(self, item, spider):
product = item["product"]
product["sources"] = self.create_sources(product)
saved_product,created = Product.objects.get_or_create(**product)
return item
def create_sources(self,product):
temp_sources = []
for source in product["sources"]:
print source
if source["source_type"] == "user":
temp_source,created = UserSource.objects.get_or_create(**source)
elif source["source_type"] == "store":
temp_source,created = StoreSource.objects.get_or_create(**source)
elif source["source_type"] == "collection":
temp_source,created = CollectionSource.objects.get_or_create(**source)
temp_sources.append(temp_source.id)
return temp_sources
Howerver, when I run the scraper, on save it gives me this error:
raise ValidationError(message, errors=errors, field_name=field_name)
mongoengine.errors.ValidationError:
[ObjectId('55787a07516ddcf4d93cd4c6'),
ObjectId('55787b07516ddcf5aff06fa9'),
ObjectId('55787b07516ddcf5aff06faa')] is not a valid ObjectId
By the way the UserSource and StoreSource...all inherit from Source so they are just subclasses.However, am I doing anything wrong here, I don't understand why it is giving me that error when product gets created.
Thanks!
You can use this
class Source(Document):
source_id = IntField()
class Product(Document):
sources = ListField(ReferenceField(Source, dbref = True))
src, created = Source.objects.create(source_id=1)
pd, _ = Product.objects.create(sources=[src])
It works for me. I am using mongoengine 0.8.7, pymongo 2.8