SharePoint Online add-in test license creation error - sharepoint

I've been struggling with creating test license for a SharePoint add-in I'm developing. I have followed below documentations provided by Microsoft to create test license tokens.
Add license checks to Office and SharePoint Add-ins
Office and SharePoint Add-in license XML schema structure
For every token I've tried, I'm getting below error.
Some license attributes are missing from the license token.
Parameter name: rawXMLEntitlementToken
These are some of different variants of token (Token 1-4) I've tried which threw same error mentioned above.
Token 1:
<r v="0">
<t aid="WA900006056"
pid="{E73E4711-181C-45D8-938E-E966C22FE761}"
oid="{8cf30d98-d6f9-4cde-8669-2d09749d8237}"
did="{42E3AD48-54AE-454D-A0EF-85F2908C68EF}"
ts="0"
et="Free"
sl="false"
ad="2018-12-18T17:30:41Z"
ed="2019-01-17T17:30:41Z"
sd="2018-12-18T17:30:41Z"
te="2018-12-20T17:30:41Z"
test="true"
ss="1" />
<d>VNNAnf36IrkyUVZlihQJNdUUZl/YFEfJOeldWBtd3IM=</d>
</r>
Token 2:
<r v="0">
<t aid="WA900006056"
pid="{E73E4711-181C-45D8-938E-E966C22FE761}"
oid="{8cf30d98-d6f9-4cde-8669-2d09749d8237}"
did="{42E3AD48-54AE-454D-A0EF-85F2908C68EF}"
ts="1"
et="Trial"
sl="false"
ad="2018-12-18T17:30:41Z"
ed="2019-01-17T17:30:41Z"
sd="2018-12-18T17:30:41Z"
te="2018-12-20T17:30:41Z"
test="true"
ss="1" />
<d>VNNAnf36IrkyUVZlihQJNdUUZl/YFEfJOeldWBtd3IM=</d>
</r>
Token 3:
<r v="0">
<t aid="WA900006056"
pid="{E73E4711-181C-45D8-938E-E966C22FE761}"
oid="{8cf30d98-d6f9-4cde-8669-2d09749d8237}"
did="{42E3AD48-54AE-454D-A0EF-85F2908C68EF}"
ts="1"
et="Paid"
sl="false"
ad="2018-12-18T17:30:41Z"
ed="2019-01-17T17:30:41Z"
sd="2018-12-18T17:30:41Z"
te="2018-12-20T17:30:41Z"
test="true"
ss="0" />
<d>VNNAnf36IrkyUVZlihQJNdUUZl/YFEfJOeldWBtd3IM=</d>
</r>
Token 4:
<r v="0">
<t aid="WA900006056"
pid="{E73E4711-181C-45D8-938E-E966C22FE761}"
oid="{8cf30d98-d6f9-4cde-8669-2d09749d8237}"
did="{42E3AD48-54AE-454D-A0EF-85F2908C68EF}"
ts="1"
et="Paid"
sl="false"
ad="2018-12-18T17:30:41Z"
ed="2019-01-17T17:30:41Z"
sd="2018-12-18T17:30:41Z"
te="2018-12-20T17:30:41Z"
test="true"
ss="1" />
<d>VNNAnf36IrkyUVZlihQJNdUUZl/YFEfJOeldWBtd3IM=</d>
</r>
Observation 1
I've tried sending empty value for cid field as well (Token 5). When I send empty value for that, I get below error.
EntitlementTokenPurchaserId field extracted from the given license token is null or empty.
Parameter name: rawXMLEntitlementToken
Token 5:
<r v="0">
<t aid="WA900006056"
pid="{E73E4711-181C-45D8-938E-E966C22FE761}"
cid=""
oid="{8cf30d98-d6f9-4cde-8669-2d09749d8237}"
did="{42E3AD48-54AE-454D-A0EF-85F2908C68EF}"
ts="1"
et="Trial"
sl="false"
ad="2018-12-20T00:55:19Z"
ed="2019-01-19T00:55:19Z"
sd="2018-12-20T00:55:19Z"
te="2018-12-22T00:55:19Z"
test="true"
ss="1" />
<d>VNNAnf36IrkyUVZlihQJNdUUZl/YFEfJOeldWBtd3IM=</d>
</r>
Observation 2
I've tried below alterations to token and it didn't change above two exceptions thrown by the API.
Token with and without v="0" attribute in root node.
Token with deployment id as empty value (did="")
Observation 3
I have verified that user who send the token has admin privileges to the site collection which I try to apply license token to.
Any help to solve this issue is highly appreciated.

Was able to resolve the error by adding value for cid. Below is the token format finally worked for me.
<r v="0">
<t aid="WA900006056"
pid="{E73E4711-181C-45D8-938E-E966C22FE761}"
cid="32F3E7FC559F4F49"
oid="{8cf30d98-d6f9-4cde-8669-2d09749d8237}"
did="{42E3AD48-54AE-454D-A0EF-85F2908C68EF}"
ts="1"
et="Trial"
sl="false"
ad="2018-12-20T00:55:19Z"
ed="2019-01-19T00:55:19Z"
sd="2018-12-20T00:55:19Z"
te="2018-12-22T00:55:19Z"
test="true"
ss="1" />
<d>VNNAnf36IrkyUVZlihQJNdUUZl/YFEfJOeldWBtd3IM=</d>
</r>

Related

How do I display error messages when I am not looping over form fields in Django templates?

My forms are not showing the error messages when I try to submit an empty form but I can see the errors while looping over the field errors in views.py. How do I overcome this problem?
the template (Updated):
{% block formcontent %}
{{form.non_field_errors}}
<div class="row">
<div class="col">
{{form.username.label_tag}} {{form.username}} {{form.username.errors|striptags}}
</div>
</div><br>
<div class="row">
<div class="col">
{{form.first_name.label_tag}} {{form.first_name}} {{form.first_name.errors|striptags}}
</div>
<div class="col">
{{form.last_name.label_tag}} {{form.last_name}} {{form.last_name.errors|striptags}}
</div>
</div><br>
<div class="row">
<div class="col">
{{form.email.label_tag}} {{form.email}} {{form.email.errors|striptags}}
</div>
</div><br>
<div class="row">
<div class="col">
{{form.location.label_tag}} {{form.location}} {{form.location.errors|striptags}}
</div>
<div class="col">
{{form.designation.label_tag}} {{form.designation}} {{form.designation.errors|striptags}}
</div>
</div><br>
<div class="row">
<div class="col">
{{form.password1.label_tag}} {{form.password1}} {{form.password1.errors|striptags}}
</div>
<div class="col">
{{form.password2.label_tag}} {{form.password2}} {{form.password2.errors|striptags}}
</div>
</div><br>
{% endblock formcontent %}
Edit 1:
(Updated)
class MyRegistrationForm(UserCreationForm):
password1=forms.CharField(label='Password', widget=forms.PasswordInput(attrs={'class':'form-control'}))
password2=forms.CharField(label='Confirm Password', widget=forms.PasswordInput(attrs={'class':'form-control'}))
class Meta:
model=MyRegistration
fields=['username', 'first_name', 'last_name', 'email', 'location', 'designation']
widgets={
'username':forms.TextInput(attrs={'class':'form-control'}),
'first_name':forms.TextInput(attrs={'class':'form-control'}),
'last_name':forms.TextInput(attrs={'class':'form-control'}),
'email':forms.EmailInput(attrs={'class':'form-control'}),
'location':forms.Select(attrs={'class':'form-select'}),
'designation':forms.TextInput(attrs={'class':'form-control'}),
}
def clean_username(self):
username = self.cleaned_data.get('username')
if not username:
raise ValidationError('Username is required!')
else:
try:
MyRegistration.objects.get(username=username)
raise ValidationError('This username already exists!', code='username_exists')
except MyRegistration.DoesNotExist:
pass
return username
def clean_email(self):
email=self.cleaned_data.get('email')
if not email:
raise ValidationError('Email is required!')
else:
try:
MyRegistration.objects.get(email=email)
raise ValidationError('This email already exists!', code='email_exists')
except MyRegistration.DoesNotExist:
pass
return email
def clean_first_name(self):
first_name=self.cleaned_data.get('first_name')
if not first_name:
raise ValidationError('First-name is required!')
return first_name
def clean_last_name(self):
last_name=self.cleaned_data.get('last_name')
if not last_name:
raise ValidationError('Last-name is required!')
return last_name
def clean_location(self):
location=self.cleaned_data.get('location')
if not location:
raise ValidationError('Location is required!')
return location
def clean_designation(self):
designation=self.cleaned_data.get('designation')
if not designation:
raise ValidationError('Designation is required!')
return designation
I really have no idea what is wrong with my codes in template. I have checked, the Django documentation suggests the same way to approach such scenarios where the forms are not looped over.
Edit 2:
models.py:
class MyRegistration(AbstractBaseUser, PermissionsMixin):
location_list=[
('Solapur', 'Solapur'),
('Dhule', 'Dhule'),
('Other', 'Other'),
]
username=models.CharField(max_length=10, unique=True)
email=models.EmailField(unique=True)
first_name=models.CharField(max_length=150)
last_name=models.CharField(max_length=150)
location=models.CharField(max_length=10, choices=location_list, default=None)
designation=models.CharField(max_length=70)
is_active=models.BooleanField()
is_staff=models.BooleanField(default=False)
start_date=models.DateTimeField(default=timezone.now)
last_login=models.DateTimeField(null=True)
USERNAME_FIELD='username'
REQUIRED_FIELDS=['email', 'first_name', 'last_name', 'location', 'designation']
objects=FirstManager()
def __str__(self):
return self.first_name
views.py:(Updated)
def signup(request):
print('1')
if request.user.is_authenticated:
print('2')
if request.method=='POST':
print('3')
if request.POST.get('password1')==request.POST.get('password2'):
print('4')
fm=MyRegistrationForm(request.POST)
for field in fm:
print("Field Error:", field.name, field.errors)
if fm.is_valid():
print('6')
fm.save()
messages.success(request, 'Registered successfully!!')
fm=MyRegistrationForm()
print('7')
cur_user=request.user
return render(request, 'account/signup.html', {'form':fm, 'cur_user':cur_user})
else:
fm=MyRegistrationForm()
cur_user=request.user
return render(request, 'account/signup.html', {'form':fm, 'cur_user':cur_user})
else:
return HttpResponseRedirect('/')
When you raise ValidationError in the clean method, these errors get added to the non_field_errors attribute on the form. This is why nothing gets rendered when using form.email.errors and other errors attributes on particular fields.
You should render the form.non_field_errors before you render your form, so you can see those errors, too.
However, to solve your issue, I would rather go with the option of splitting the validation of each field into particular methods clean_<field_name>. For example for username field:
def clean_username(self):
username = self.cleaned_data.get('username')
if not username:
raise ValidationError('Username is required!')
else:
try:
un=MyRegistration.objects.get(username=self.instance.username)
raise ValidationError('This username already exists!')
except MyRegistration.DoesNotExist:
pass
# Make sure you return the value of the data in
# the clean_<field_name> methods
return username
And so on for other fields, too. Doing just this should fix your code, but here are some other recommendations:
Use codes when raising ValidationErrors. E.g.: raise ValidationError('This username already exists', code='username_exists')
Check out the django-crispy package, it can handle the HTML rendering of forms with minimal code
You can set constraints in the models for unique fields (e.g. username) and required fields. This further prevents users who are not adding data with your form (e.g. admin) to add duplicate usernames or null values. This would also mean that a lot of your custom validation code would be unnecessary.
EDIT #1:
The use of instance to get the values from the submitted form is wrong. Since this form is used exclusively for create purposes as registration is creation of a new user, instance will always be empty. instance is only filled with data when you're updating a model instance.
You should replace the uses of instance with getting the form data from self.cleaned_data dict.
For example:
# Instead of:
username = self.instance.username
# Use:
username = self.cleaned_data.get('username')
EDIT #2:
After the author added the view code.
The issue might be in your view code. Also, there is no need to comparing password1 and password2 as the UserCreationForm already does that for your.
The core issue is that if your form is invalid, you need to re-render that same form, not create another instance. I propose the following update:
def signup(request):
print('1')
if request.user.is_authenticated:
print('2')
if request.method=='POST':
print('3')
form = MyRegistrationForm(request.POST)
if form.is_valid():
print('4')
form.save()
messages.success(request, 'Registered successfully!!')
# If you do this, you always render the empty form
# without the errors
# fm=MyRegistrationForm()
print('7')
cur_user=request.user
return render(
request, 'account/signup.html',
{'form': form, 'cur_user':cur_user}
)
else:
form = MyRegistrationForm()
cur_user=request.user
return render(
request, 'account/signup.html',
{'form':form, 'cur_user':cur_user}
)
else:
return HttpResponseRedirect('/')
Some other recommendations:
You probably don't need to check if the user is authenticated if this is registration view. How can the new users create an account? However, if this is needed probably the #login_required decorator works better for this.
On success, you need to redirect to the success URL. Don't use render for success scenarios, only when handling the GET method or when you need to re-render the form to display validation errors.

Delete all task related to User

I am creating a todo app. I want to delete all task related to a particular user from Tasklist table after login but i got an error ' deleteAll() missing 1 required positional argument: 'id' ". How can i delete all task. Thanks in advance.
Model.py
from django.contrib.auth.models import User
from django.db import models
class TaskList(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
task = models.CharField(max_length=100, null=False, blank=False)
complete = models.BooleanField(default=False)
taskCreate = models.DateTimeField(auto_now=True)
Views.py
def deleteAll(request, id):
TaskList.objects.filter(id=request.user.tasklist_set.filter(id)).delete()
return redirect('todolist')
Html
{% extends 'home.html' %}
{% block content %}
{%if user.is_authenticated%}
<h2>Welcome {{ user.get_username| title }}</h2>
<button type="submit">Logout</button>
<form method="post">
{% csrf_token %}
<label for="task">
<input name="task" placeholder="add today's task" id="task" required>
<button type="submit">add</button>
</label>
</form>
<form method="get" >
{% csrf_token %}
<div>
{% for todo in task %}
{% if todo.complete %}
<li class="list-group-item todo-completed"><h6>{{ todo.task|linebreaks}} </h6></li>
{% else %}
<h6 class="list">{{ todo.task|linebreaks}}</h6>
{% endif %}
{% endfor %}
<button> Delete All </button>
<button> Delete Completed </button>
</div>
</form>
{% endif %}
{% endblock %}
First Change in your template Delete All button. Because your view requires a user id.
<button type="button"> Delete All </button>
Then simplify the deleteAll functions db query. You need to filter all tasks of current user. so you can just use user__id__exact = id:
def deleteAll(request, id):
TaskList.objects.filter(user__id__exact = id).delete()
return redirect('todolist')
Alternative Solution:
You don't need to send id. because you can get the current user id in request argument.
You just need to change the filter:
# view
#login_required
def deleteAll(request):
TaskList.objects.filter(user = request.user).delete()
return redirect('todolist')
# In template use:
<button type="button"> Delete All </button>
# urlpattern
path('delete/', deleteAll, name='delete')
I hope this will help you. Thank you. Happy Coding :)
This is a very common mistake that people do. :)
You have defined a function which takes request and an argument named as id as shown here:
def deleteAll(request, id):
TaskList.objects.filter(id=request.user.tasklist_set.filter(id)).delete()
return redirect('todolist')
But you have to pass an argument into deleteAll. To do that you have to type in the argument value.
You can do so by entering the value after {% url 'delete' %} in the line
Delete All
For example:
Delete All
I hope this helped, if not, feel free to comment and clarify the query.
I suppose "id" refers to the user's id, that is request.user.pk.
There are two issues, or two solutions:
About the Error
You have specified that your view expects the argument id, therefore you would need to add it to the URL in the template.
def deleteAll(request, id): # <<<< "id" is specified as argument
Delete All <!-- no "id" is specified -->
If you have an argument in a view, you need to specify it in the urls.py (which you obviously did) and subsequently whereever you need it reversed:
Delete All
You need the request template processor to have the request in your template context.
However, you actually don't need the ID because you know it in the view already. This is the "other solution".
About the ID
def deleteAll(request, id):
TaskList.objects.filter(id=request.user.tasklist_set.filter(id)).delete()
return redirect('todolist')
can be rewritten to
from django.contrib.auth.decorators import login_required
#login_required
def deleteAll(request):
TaskList.objects.filter(id=request.user.pk).delete()
return redirect('todolist')
You need to remove the id argument in the url in your urls.py, as well.

My label keeps on getting into my django form field, how do I fix it?

Image of problem
I have been following up on a django tutorial based around building an e-commerce site. I am currently working on the checkout page for the e-commerce website; I am making use of django forms but the label I attach to my form field keeps getting into the field and when you type into form field it creates this murky text that is very unpleasant. I can't just fix it and it is driving mad, please can someone help me check it out ? Sorry if my presentation is a bit off, I am not used to stackoverflow.
checkout.html
<div class="md-form mb-5">
{{ form.street_address }}
<label for= "address" class =""><b>Address</b></label>
<!-- <label for="address" class="">Address</label>-->
</div>
<!--address-2-->
<div class="md-form mb-5">
<!-- <input type="text" id="address-2" class="form-control" placeholder="Apartment or suite">-->
{{ form.apartment_address }}
<label for = "address2" class =''><b>Address 2</b></la
from django import forms
from django_countries.fields import CountryField
from django_countries.widgets import CountrySelectWidget
PAYMENT_OPTIONS = (
('S', 'Stripe'),
('P', 'PayPal'),
)
class CheckoutForm(forms.Form):
street_address = forms.CharField(widget=forms.TextInput(attrs={
'placeholder': '1234 main st.',
'class': 'form-control',
'id': 'address',
'name': 'address'
}
))
apartment_address = forms.CharField(widget=forms.TextInput(attrs={
'placeholder': 'Apartment or Suite',
'class': 'form-control',
'id': 'address2',
'name': 'address2'
}
), required=False)
country = CountryField(blank_label='(select country)').formfield(widget=CountrySelectWidget(attrs= {
'class': 'custom-select d-block w-100'
}))
zip = forms.CharField(widget=forms.TextInput(attrs={
'class': 'form-control'
}))
same_billing_address = forms.BooleanField(widget=forms.CheckboxInput)
save_info = forms.BooleanField(widget=forms.CheckboxInput)
payment_option = forms.ChoiceField(widget=forms.RadioSelect, choices=PAYMENT_OPTIONS)
You have overlapping text here. Remove either
<label for= "address" class =""><b>Address</b></label>
or
placeholder': '1234 main st.'
and it should look better.

Python return status 200, but no response data

I'm trying to acccess URL https://launchpad.support.sap.com/#/notes/2711030 via urllib3. When doing I'am getting
http = urllib3.PoolManager()
url = 'https://launchpad.support.sap.com/#/notes/2711030'
headers = urllib3.make_headers(basic_auth='abc:xyz')
r = http.request('GET', url, headers=headers)
When I run above I get outpout as :
r = http.request('GET', url, headers=headers)
C:\Users\AppData\Local\Continuum\anaconda3\lib\site-packages\urllib3\connectionpool.py:847: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings
InsecureRequestWarning)
r.status
Out[38]: 200
r.read()
Out[39]: b''
r.data
Out[40]: b'<html><head><meta http-equiv="cache-control" content="no-cache" /><meta http-equiv="pragma" content="no-cache" /></head><body style="background-color:#FFFFFF" onload="var url=window.location.hash;if(url&&0!==url.length){document.cookie=\'oucrsnpdmeytwvuuiyfukjxfe_anchor="\'+encodeURIComponent(url) + \'"\';}document.forms[0].submit()"><p><script language="javascript">document.write("Please wait ...");</script></p><noscript><p>Note: Your browser does not support JavaScript or it is turned off. Press the button to proceed.</p></noscript><form method="post" action="https://authn.hana.ondemand.com/saml2/sp/mds"><input type="hidden" name="tenantId" value="NzkwZmJmMjgtMjMxMC00M2E5LWI1NzEtN2MwYzliODg2ZTll"/><input type="hidden" name="idpName" value="aHR0cHM6Ly9hY2NvdW50cy5zYXAuY29t"/><input type="hidden" name="requestUrl" value="aHR0cHM6Ly9sYXVuY2hwYWQuc3VwcG9ydC5zYXAuY29tLw=="/><input type="hidden" name="requestId" value="UzZlMmU1YjU3LTY0NmEtNDI0My1iMzk0LWMzYzNlZGRjOGU2Ni1pZXdCS2R6ZE5sR252RHVuVVlCTGlZd3lWZUNwazNsMmhJcXl6Z2VRNzgw"/><input type="hidden" name="relayState" value="b3VjcnNucGRtZXl0d3Z1dWl5ZnVranhmZQ=="/><input type="hidden" name="action" value="sso"/><input type="hidden" name="signature" value="SAZ4BbOwt1i/tJpwFLn6vV1cVUYT3AVv8BGaq+yAHXbCOd5E7swH9BnR8kxZu4mc5eLiclbZe94bN0X/b2EkS06QQIWQqsjL6UoDjTH0DA3y+qzrkIPyhYzM4mwZZlFx1NGJpmuWAn+2r063QI7Yuj7ebS2XhflW6k7qDKIZpPb8ctBsa6cJSUQFoqwHV6Km7spZYlGHwQ4ktER62ZSMvpmoFRAduOQfiJ1ckLl+iVxIsrTawZZz4+87MwmqjW2ym0qrxBLbZDHMdTvG+wggTweBpI2i043jAgy7blBLk5Yh92K8QLn3zsZ3NY+gTpgz1a+CYTr2vl35H8k5Kek4cg=="/><noscript><input type="submit" value="Continue"/></noscript></form></body></html>'
I want to read the page so that I can scrape data from it, what type of authentication do I need as I provided my login credential via which I access the page but then also no result.
What else do I need to provide or is there anything that I'm doing wrong ?

How to hard-code pass a variable from template B coming "from template A to Template B" to a route function?

I'm building a web application that shows a list of books, the user clicks on a book, and he is directed to a book contains another list of the information of that book.
Books.html redirects the user to review.html, the problem is url_for function in books.html file doesn't work as intended.
books.html file is a bootstrap 4 predefined list, I've just the link
to href="{{url_for('review', book_id=book.id)}}"
#app.route("/books")
def books():
''' show books in a list. '''
# Select book info based on first characters.
books = db.execute("SELECT * FROM books WHERE isbn LIKE :isbn", {"isbn":"0"+"%"})
if books is None:
raise RuntimeError("Error # books route, Didn't fetch rows from books table.")
return render_template("books.html",books=books)
#app.route("/books/<int:book_id>")
def review(book_id):
''' Show book information inner and API '''
# Get book information from books table using book_id got from books.html
bookInfo = db.execute("SELECT * FROM books WHERE id=:book_id", {"book_id": book_id}).fetchone()
# Error handling.
if bookInfo is None:
raise RuntimeError("Error # route: review, didn't fetch book information from books table.")
return render_template("review.html", bookInfo=bookInfo)
<!-- books.html -->
{% extends "base.html" %}
{%block body%}
<!-- book list <books.html> -->
<!-- this will have a template for loop over elements in database -->
<div class="container list-group">
{% for book in books %}
<a href="{{url_for('review', book_id=book.id)}}" class="list-group-item list-group-item-action flex-column align-items-start">
<div class="d-flex w-100 justify-content-between">
<h5 class="mb-1">{{book.title}}</h5>
<small><h6>ISBN: {{book.isbn}}</h6></small>
</div>
<p class="mb-1"><h6>author: {{book.author_name}}</h6></p>
<small>publication year: {{book.publish_year}}</small>
</a>
{%endfor%}
</div>
{%endblock%}
<!-- review.html -->
{% extends "base.html" %}
{%block body%}]
<!-- Book details, and user's review -->
<div class="container">
<dl class="row">
<dt class="col-sm-3">Book title</dt>
<dd class="col-sm-9">{{bookInfo.title}}</dd>
<dt class="col-sm-3">Book author</dt>
<dd class="col-sm-9">{{bookInfo.author_name}}</dd>
<dt class="col-sm-3">ISBN</dt>
<dd class="col-sm-9">{{bookInfo.isbn}}</dd>
<dt class="col-sm-3">Publication year</dt>
<dd class="col-sm-9">{{bookInfo.publish_year}}</dd>
</div>
{%endblock%}
I expect to have a list of information about the book the user picked, but instead, I get this error:
TypeError: The view function did not return a valid response. The function either returned None or ended without a return statement.

Resources