how to render tenjin_template in django1.6 - django-templates

Here is my view which renders my tenjin_template in Django. It gives me an error
init() takes exactly 1 argument (2 given)
Here is the code
def get(self, request):
voucher_request = Voucher.objects.all()
context = RequestContext(request, {
'voucher_request': voucher_request,
})
return self.tenjin_response("billing/voucher.html", context)

I got the answer of above question:
def get(self,*args, **kwargs):
voucher_request = Voucher.objects.all()
if voucher_request == MANAGE_RAISE:
return self.permission_exception()
context = {
'voucher_request': Voucher.objects.all(),
}
return self.tenjin_response("billing/voucher.html", context)

Related

File uploaded with Django Rest Framework shows null on database

Created an API and while testing the JSON output I'm getting is
{
"id": 34,
"file_upload": null
}
While checking the admin panel, the new id is created but there is no uploaded image in that. And hence I'm not able to save it locally too.
Here's my urls.py
urlpatterns = [
path("api/", upload_file),
path("api-class/", UploadFileView.as_view())
]
I've created two paths one with function-based views and the other with class-based views, but neither is working.
views.py
class UploadFileView(APIView):
parser_classes = [MultiPartParser, FormParser,]
def get(self, request):
file = ApiSerializer.objects.all()
serializer = ApiSerializer(file, many=True)
return Response(serializer.data)
def post(self, request, format=None):
print(request.data)
serializer = ApiSerializer(data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data, status=status.HTTP_201_CREATED)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
#api_view(['POST'])
#parser_classes((MultiPartParser,))
def upload_file(request):
if request.method == 'POST':
serializer = ApiSerializer(data=request.data)
extension = 'csv'
ext = ['csv']
if extension in ext:
if serializer.is_valid():
serializer.save()
return Response(serializer.data, status=status.HTTP_201_CREATED)
else:
report = {'message':'Serializer wasn\'t valid. Error occured'}
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
else:
resp = {'message': "Invalid Format"}
return Response(resp, status=status.HTTP_400_BAD_REQUEST)
serializer.py
class ApiSerializer(serializers.ModelSerializer):
class Meta:
model = UserInput
fields = '__all__'
models.py
def file(instance, filename):
filename = filename.replace(" ", "")
return '\{0}'.format(filename)
def validate_file_extension(value):
import os
ext = os.path.splitext(value.name)[1]
valid_extensions = ['.csv']
if not ext in valid_extensions:
raise ValidationError(u'File not supported!')
class UserInput(models.Model):
file_upload = models.FileField(null=True, blank=True, upload_to='file', validators=[validate_file_extension])

suspend function testing with spock

I have a simple function in kotlin like that :
suspend fun createTicket(#Valid request: CreateTicketRequest, authentication: Authentication): HttpResponse<Any> {
request.customerId = "customerId"
logger().info("Receive by the client $request")
return HttpResponse.created(service.create(request))
}
I've already Mock the request and the authentication.
So, I call it on Spock:
def 'It should create a ticket with success'() {
given:
def request = createRequest(
TICKET_ID,
TICKET_NAME,
TICKET_PHONE,
TICKET_CPF,
TICKET_EMAIL,
TICKET_COMMENT,
TICKET_SUBJECT,
TICKET_TAG
)
when:
response = controller.createTicket(
request,
authentication
)
then:
response != null
}
I'm getting the following error :
Suspend function 'create' should be called only from a coroutine or another suspend function.
Can anyone help me with this question ?
Best regards
Solved I created a Kotlin class code
class CallCreateTicket {
private lateinit var response: HttpResponse<Any>
private fun createTicket(
request: CreateTicketRequest,
authenticator: Authenticator,
controller: TicketController,
): HttpResponse<Any> {
runBlocking {
response = controller.createTicket(request, authenticator)
}
return response
}
}
and I called it on groovy ...
#Mockable(TicketCreateServiceImpl)
class TicketControllerTest extends Specification {
def mockUtil = new MockUtil()
def service = Mock(TicketCreateServiceImpl)
def authenticator = Mock(Authenticator)
def response = Mock(HttpResponse)
def controller = new TicketController(service)
def callCreateTicket = new CallCreateTicket()
def 'check if all instances are mocked'() {
mockUtil.isMock(authentication)
mockUtil.isMock(service)
}
def 'It should call the index function and return a valid String'() {
when:
response = controller.index()
then:
response == INDEX_RETURN
}
def 'It should call the index function and return a invalid String'() {
when:
response = controller.index()
then:
response != INVALID_INDEX_RETURN
}
def 'It should create a ticket with success'() {
given:
def request = createRequest(
TICKET_ID,
TICKET_NAME,
TICKET_PHONE,
TICKET_CPF,
TICKET_EMAIL,
TICKET_COMMENT,
TICKET_SUBJECT,
TICKET_TAG
)
when:
response = callCreateTicket.createTicket(
request,
authenticator,
controller
)
then:
response.status(HttpStatus.CREATED)
}
}

Django: How do I return JWT with custom claim after user Sign Up?

I know how to create custom claims with simplejwt. Now I want to return custom claim in the tokens containing email after user signs up. How do I do this?
My serializer:
class CreateUserSerializer(serializers.ModelSerializer):
password = serializers.CharField(min_length=8, required=True, write_only=True)
password2 = serializers.CharField(min_length=8, write_only=True, required=True)
tokens = serializers.SerializerMethodField()
def get_tokens(self, user):
refresh = RefreshToken.for_user(user)
return {
'refresh': str(refresh),
'access': str(refresh.access_token),
}
def validate(self, data):
if data['password'] != data['password2']:
raise serializers.ValidationError({"password": "Password fields didn't match."})
return data
def create(self, validated_data):
password = validated_data.pop('password', None)
password2 = validated_data.pop('password2', None)
instance = self.Meta.model(**validated_data)
if password is not None:
instance.set_password(password)
instance.save()
return instance
class Meta:
model = CustomUser
fields = ('id', 'email', 'password', 'password2', 'tokens')
extra_kwargs = {'password': {'write_only': True}}
It returns the default JWT access and refresh tokens. I want to return custom claim in the token here.
The view:
class CreateUserView(generics.CreateAPIView):
permission_classes = [permissions.AllowAny]
def create(self, request, *args, **kwargs):
serializer = CreateUserSerializer(data = request.data)
if serializer.is_valid(raise_exception=True):
serializer.save()
return Response(serializer.data, status=status.HTTP_201_CREATED)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
you can create a custom function to get new refresh and access tokens with adding some extra info (your custom claim):
from rest_framework_simplejwt.tokens import RefreshToken
def get_tokens_for_user(user):
refresh = RefreshToken.for_user(user)
refresh['user_name'] = user.username
refresh['first_name'] = user.first_name
refresh['last_name'] = user.last_name
refresh['full_name'] = user.get_full_name()
return {
'refresh': str(refresh),
'access': str(refresh.access_token),
}
and then you can use this function wherever you want.
and also for CBV (TokenObtainPairView) if you like , you can use a custom Serializer as the following to get the same result :
from rest_framework_simplejwt.serializers import TokenObtainPairSerializer
from rest_framework_simplejwt.views import TokenObtainPairView
class MyTokenObtainPairSerializer(TokenObtainPairSerializer):
#classmethod
def get_token(cls, user):
token = super().get_token(user)
token['user_name'] = user.username
token['first_name'] = user.first_name
token['last_name'] = user.last_name
token['full_name'] = user.get_full_name()
return token
class MyTokenObtainPairView(TokenObtainPairView):
serializer_class = MyTokenObtainPairSerializer
and the url path will be as the following in urls.py
path('token/', MyTokenObtainPairView.as_view(), name='token_obtain_pair'),
this is just example , and change it based on your case/requirements .
i hope this helpful for you .
I figured it out. I just had to made this change in the existing get_tokens() function of my serializer:
def get_tokens(self, user):
refresh = RefreshToken.for_user(user)
refresh['email'] = user.email
return {
'refresh': str(refresh),
'access': str(refresh.access_token),
}
Here email is my added claim.

when the android gradle plugin update to 3.1.0 from 3.0.1,error happened,gradle code is for fixed resources id

previous code is(this is the public-xml.gradle that for public.xml fixed resources id)
afterEvaluate {
for (variant in android.applicationVariants) {
def scope = variant.getVariantData().getScope()
String mergeTaskName = scope.getMergeResourcesTask().name
def mergeTask = tasks.getByName(mergeTaskName)
mergeTask.doLast {
copy {
int i=0
from(android.sourceSets.main.res.srcDirs) {
include 'values/public.xml'
rename 'public.xml', (i++ == 0? "public.xml": "public_${i}.xml")
}
into(mergeTask.outputDir)
}
}
}
}
now the error is
No signature of method: com.android.build.gradle.internal.scope.VariantScopeImpl.getMergeResourcesTask()is applicable for argument types: () values: []
Possible solutions: getMergeJavaResourcesTask()
I check the code for VariantScopeImp.java,find that in 3.0.1 the code is
#Nullable private AndroidTask<MergeResources> mergeResourcesTask;
in 3.1.0 the code is
#Nullable private MergeResources mergeResourcesTask;
when I chage the public-xml.gradle code to
def scope = variant.getVariantData().getScope()
def mergeTask = scope.mergeResourcesTask
the new error is
Cannot invoke method doLast() on null object
What should I do for it? thanks
try:
def mergeTask = variant.getMergeResources()
work for 3.1.4

how to access session in integration test in grails?

In my project, i set session.loggedInUser in login controller. But during integration test , we dont use login controller. So i have set value for session.loggedInUser. But i couldn't use session in that place. How can i use session in integration Test. Give some solution for this. thank you in advance
class MaritalStatusIntegrationTests {
#Test
void testCategoryAudit() {
RequestContextHolder.currentRequestAttributes().session.loggedInUser="Anantha"
def category = new Category(name:"Single")
category.save(flush:true)
assert CategoryAudit.count() == 1
category.name="Married"
category.save(flush:true)
assert CategoryAudit.count() == 2
}
}
Category.groovy:
class Category {
static constraints = {
name blank:false
}
String name
//Auditing
static auditable = false
def onSave = {
new CategoryAudit(this,'Insert').save(failOnError:true)
}
}
CategoryAudit.groovy:
import org.springframework.web.context.request.RequestContextHolder
class CategoryAudit {
String name
String operation
String doneBy
Date txnDate
def CategoryAudit(){}
def CategoryAudit(Category category , String operation) {
this.name = category.name
this.operation = operation
this.doneBy = RequestContextHolder.currentRequestAttributes().session.loggedInUser
this.txnDate = new Date()
}
}
No such property: RequestContextHolder for class:
com.vasco.gs.MaritalStatusIntegrationTest.
Just to clean up, according to the OP, it was missing the import for RequestContextHolder.