Django-models cannot import Modelform - django-models

In views.py is : from django.forms import Modelform. Still i get the Importerror. I read the other post. What am i doing wrong? And how to solve it?
models.py:
from django.db import models
from datetime import datetime
from django.forms import Modelform
from django.utils import timezone
from django.contrib.auth.models import User
from mytool.forms import Modelform
class Search(models.Model):
search = models.CharField(max_length=250)
subject = models.CharField(max_length=150)
user = models.ForeignKey(User, on_delete=models.CASCADE)
forms.py:
from django import forms
from django.forms import Modelform
from mytool.models import Search
class SearchForm(model.Modelform):
search = forms.CharField(label ='search', max_length=250, required=True)
subject = forms.CharField(label ='subject', max_length=150, required=False)
user = forms.ForeignKey(User, on_delete=forms.CASCADE)
class Meta:
model = Search
fields = ('search', 'subject', 'user',)

Related

ModuleNotFoundError: No module named 'home'

from django.conf.urls import patterns, include, url
from django.contrib import admin
from home import views
Register your models here.
admin.site.register(Contact)

Django Rest Framework authentication and user session

I'm trying to add authentication to my django-react app. At this point I am able to login/register users and it works fine but I want to get only data which is related with user logged in so posted or updated by them. Now I get all data regardless of user which is authenticated.
I assume I have to change it in my views but how to do this?
This is one of my classes
class ListView(viewsets.ModelViewSet):
serializer_class = ListSerializer
queryset = List.objects.all()
And on frontend side I get data this way:
const getList = async () => {
try {
const response = await axiosInstance.get('/list/')
if(response){
setList(response.data)
}
}catch(error){
throw error;
}
}
You can use Django Rest Framework to set the authentication scheme on a per-view or per-viewset basis. Using the APIView class-based views:
from rest_framework.authentication import SessionAuthentication, BasicAuthentication
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.views import APIView
class ExampleView(APIView):
authentication_classes = [SessionAuthentication, BasicAuthentication]
permission_classes = [IsAuthenticated]
def get(self, request, format=None):
content = {
'user': str(request.user), # `django.contrib.auth.User` instance.
'auth': str(request.auth), # None
}
return Response(content)
Remember to set it up:
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': [
'rest_framework.authentication.BasicAuthentication',
'rest_framework.authentication.SessionAuthentication',
]
}
Read more here

How to send a query from the frontend (React) to Django with Rest Framework

i want to receive a particular input from the frontend react textarea to perform a certain function in django backend. Anybody to help. i want to send a input's value from the textarea input field to my backend
Here is my React Frontend Code
import React, { Component } from 'react';
import axios from 'axios';
class QueryBuilder extends Component{
render() {
return (
<div>
<form>
<textarea cols="100" rows="20" name="text" />
<br /><br />
<button>Execute Query</button>
</form>
</div>
)
}
}
export default QueryBuilder;
Here is the views.py code
from django import db
from django.shortcuts import render, HttpResponse
from rest_framework import generics
from .models import Test
from .serializers import TestSerializer
from pymongo import MongoClient
from ast import literal_eval
from rest_framework import viewsets, permissions
# from .models import Test
# from .serializers import TestSerializer
#Test Viewset
class TestViewset(viewsets.ModelViewSet):
client = MongoClient()
db = client.test
# collect = db['state_entry'].find({})
queryset = db['queryTest_test'].find({})
permission_classes = [
permissions.AllowAny
]
serializer_class = TestSerializer
Serializer.py
from rest_framework import serializers
from queryTest.models import Test
# Test Serializers
class TestSerializer(serializers.ModelSerializer):
class Meta:
model = Test
fields = '__all__'
Update your react component code to this, i see you have imported axios but havent't used it to make api call, You should definitely checkout axios official documentation, very useful package
import React, { Component } from "react";
import axios from "axios";
class App extends Component {
constructor() {
this.state({
textAreaValue: "",
});
}
api_call = (data) =>
axios
.post(`http://127.0.0.1:8000/your-api-path`, {
value_to_send: data,
})
.then(function (response) {
console.log(response);
this.setState({textAreaValue:''});
})
.catch(function (error) {
console.log(error);
});
render() {
return (
<div>
<textarea
onChange={(e) => this.setState({textAreaValue: e.target.value})}
value={this.state.textAreaValue}
/>
<button onClick={() => this.api_call(this.state.textAreaValue)}>Click it</button>
</div>
);
}
}
export default App;
Update your viewset to this i.e. use self.request.data received in api request
from django import db
from django.shortcuts import render, HttpResponse
from rest_framework import generics
from .models import Test
from .serializers import TestSerializer
from pymongo import MongoClient
from ast import literal_eval
from rest_framework import viewsets, permissions
# from .models import Test
# from .serializers import TestSerializer
#Test Viewset
class TestViewset(viewsets.ModelViewSet):
request_data = request.data
print(request_data)
client = MongoClient()
db = client.test
# collect = db['state_entry'].find({})
queryset = db['queryTest_test'].find({})
permission_classes = [
permissions.AllowAny
]
serializer_class = TestSerializer
Have a look at django request/response docs here
Checkout this answer here for a similar requirement in backend.

Django Stripe PaymentIntent

I am trying to setup the paymentIntent API from Stripe but I can't seem to figure out the error I am getting. I followed along from this video: https://www.youtube.com/watch?v=w1oLdAPyuok&t=1414s
I have a react frontend which makes a request to my Django view:
try {
const { data: clientSecret } = await axios.post("http://127.0.0.1:8000/paymentIntent/", {
amount: price * 100
});
My view:
from django.shortcuts import render
from django.http import HttpResponse
from django.views.generic import View
from django.views.decorators.csrf import csrf_exempt
import logging
from rest_framework.views import APIView
from rest_framework import status, generics
from rest_framework.response import Response
from rest_framework.decorators import api_view
from django.conf import settings
import stripe
stripe.api_key = "pk_test_51HWMwZB5hTmoPZOBJd00GjCvDYUg"
#api_view(['POST'])
def payment(request):
try:
amount = request.body
paymentIntent = stripe.PaymentIntent.create(
amount = amount,
currency = "usd",
# payment_method_types=['card'],
# capture_method='manual',
metadata={'integration_check': 'accept_a_payment'},
)
data = paymentIntent.client_secret
return Response(data,status=status.HTTP_200_OK)
except :
return Response(status=status.HTTP_400_BAD_REQUEST)
When I make the request it just says 400 Bad Request with no response data
I don't see the actual error message you're getting, your server should log out the error in your try-catch block, as shown here: https://stripe.com/docs/api/errors/handling?lang=python allowing you to better debug and troubleshoot as you build your integration.
Most likely, it is that you have set your publishable key as your stripe-python API key. Instead you need to initialize stripe with your secret key: https://stripe.com/docs/api/authentication?lang=python

Katalon iOS mobile automation, is it possible to make a custom keyword that will long press and move element(drag and drop)

Currently I'm having some problem using Drag and Drop keyword in katalon, since the object that I need to drag should be tapped (for like 1 sec) before it pop-out and be moveable but since the "drag and drop" keyword works instantly without any timeout on the first action (drag). Now has anyone tried using a custom keyword for this kind of issue?
Thank you so much in advance.
Currently this is the only code that I am trying to convert in mobile since it was originally created for web, I'm not very sure if I am doing it right.
package aCustomDragmDrop
import static com.kms.katalon.core.checkpoint.CheckpointFactory.findCheckpoint
import static com.kms.katalon.core.testcase.TestCaseFactory.findTestCase
import static com.kms.katalon.core.testdata.TestDataFactory.findTestData
import static com.kms.katalon.core.testobject.ObjectRepository.findTestObject
import com.kms.katalon.core.annotation.Keyword
import com.kms.katalon.core.checkpoint.Checkpoint
import com.kms.katalon.core.checkpoint.CheckpointFactory
import com.kms.katalon.core.mobile.keyword.MobileBuiltInKeywords
import com.kms.katalon.core.model.FailureHandling
import com.kms.katalon.core.testcase.TestCase
import com.kms.katalon.core.testcase.TestCaseFactory
import com.kms.katalon.core.testdata.TestData
import com.kms.katalon.core.testdata.TestDataFactory
import com.kms.katalon.core.testobject.ObjectRepository
import com.kms.katalon.core.testobject.TestObject
import com.kms.katalon.core.webservice.keyword.WSBuiltInKeywords
import com.kms.katalon.core.webui.keyword.WebUiBuiltInKeywords
import internal.GlobalVariable
import MobileBuiltInKeywords as Mobile
import WSBuiltInKeywords as WS
import WebUiBuiltInKeywords as WebUI
import org.openqa.selenium.WebElement
import org.openqa.selenium.WebDriver
import org.openqa.selenium.By
import com.kms.katalon.core.mobile.keyword.internal.MobileDriverFactory
import com.kms.katalon.core.webui.driver.DriverFactory
import com.kms.katalon.core.testobject.RequestObject
import com.kms.katalon.core.testobject.ResponseObject
import com.kms.katalon.core.testobject.ConditionType
import com.kms.katalon.core.testobject.TestObjectProperty
import com.kms.katalon.core.mobile.helper.MobileElementCommonHelper
import com.kms.katalon.core.util.KeywordUtil
import com.kms.katalon.core.webui.exception.WebElementNotFoundException
import io.appium.java_client.AppiumDriver
import io.appium.java_client.MobileElement
import io.appium.java_client.TouchAction
public class DragDrop {
#Keyword
def dragdrop(TestObject to,TestObject destination,Integer intX,Integer intY) {
def Eleto = MobileElementCommonHelper.findElement(to, timout)
def eledest = MobileElementCommonHelper.findElement(destination, timeout)
TouchAction touchAction = new TouchAction(driver)
touchAction.moveToElement(eleto)
touchAction.waitAction(WaitOptions.waitOptions(Duration.ofMillis(2000)))
touchAction.perform()
touchAction.moveToElement(eledest,intX, intY)
touchAction.release()
touchAction.perform();
}
}

Resources