'<' not supported between instances of 'Applicant' and 'Applicant' - django

I have a model that I want to use for predictions which I have loaded using pickle and I have a form created in using django. But when a user submits the form I want it to be in store it in a csv format in a variable so I can perform Xgboost prediction on every form the user fills and after it outputs the prediction. COuld it be its not getting any input. New to this
from django.db import models
from django import forms
from django.core.validators import MaxValueValidator, MinValueValidator
# Create your models here.
type_loan=(("Cash loan","Cash loan"),
("Revolving loan","Revolving Loan"))
Gender=(("Male","Male"),
("Female","Female"))
Yes_NO=(("YES","YES"),("NO","NO"))
status=(("Single","Single"),
("Married","Married"),
("Widow","Widow"),
("Seprated","Divorce"))
Highest_Education=(("Secondary","Secondary"),
("Incomplete Higher","Incomplete Higher"),
("Lower Secondary","Lower Secondary"),
("Academic Degree","Academic Degree"))
Income_type=(("Working","Working Class"),
("State Servant","Civil Servant"),
("Commercial Associate","Commercial Associate"),
("Pensioner","Pensioner"),
("Student","Student"),
("Businessman","Business Owner"))
class Applicant(models.Model):
name=models.CharField(default="Jon Samuel",max_length=50,null="True")
Birth_date=models.DateField(default="2018-03-12",blank=False, null=True)
Status=models.CharField(choices=status,max_length=50)
Children=models.IntegerField(default=0,validators=[MinValueValidator(0),MaxValueValidator(17)])
Highest_Education=models.CharField(choices=Highest_Education,max_length=50)
Gender=models.CharField(choices=Gender, max_length=50)
loan_type=models.CharField(choices=type_loan, max_length=50)
own_a_car=models.CharField(choices=Yes_NO,max_length=50)
own_a_house=models.CharField(choices=Yes_NO,max_length=50)
def __str__(self):
return self.name
views.py
from django.shortcuts import render
from .models import Applicant
from .forms import Applicant_form
from django.views.generic import ListView, CreateView, UpdateView
from django.core.cache import cache
import xgboost as xgb
import pickle
from sklearn.preprocessing import LabelEncoder
class CreateMyModelView(CreateView):
model = Applicant
form_class = Applicant_form
template_name = 'loan/index.html'
success_url = '/loan/results'
context_object_name = 'name'
class MyModelListView(ListView):
template_name = 'loan/result.html'
context_object_name = 'Results'
def get_queryset(self):
queryset=Applicant.objects.all()
with open('model/newloan_model','rb') as f:
clf=pickle.load(f)
le=LabelEncoder()
le.fit(queryset)
queryset=le.transform(queryset)
d_test = xgb.DMatrix(queryset)
predict=clf.predict(d_test)
return (predict)

One way to accomplish this is to use a Django package called django-import-export. This way you can export every object inside a model to a csv file.
https://django-import-export.readthedocs.io/en/latest/

Related

Make Django 3 REST render HTML template

I am trying to build a Django (version 3.05) REST API call that will render to a chosen HTML template.
I am, however, receiving a number of errors that I haven't found a solution to on StackOverflow (And yes, I've looked far and wide).
Since my errors are many and varying depending on what I attempt, let me rather ask how to do it correctly to begin with.
In my view set up (below), what do I need to add (or change) in order to render the queryset to an HTML template?
models.py:
from django.db import models
class Hero(models.Model):
name = models.CharField(max_length=60)
alias = models.CharField(max_length=60)
def __str__(self):
return self.name
serializers.py:
from rest_framework import serializers
from .models import Hero
class HeroSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Hero
fields = ('name', 'alias')
views.py:
from rest_framework import viewsets
from .serializers import HeroSerializer
from .models import Hero
class HeroViewSet(viewsets.ModelViewSet):
queryset = Hero.objects.all().order_by('name')
serializer_class = HeroSerializer
# over here - how do I render the queryset /to/my/template.html
myapi/urls.py:
from django.urls import include, path
from rest_framework import routers
from . import views
router = routers.DefaultRouter()
router.register(r'heroes', views.HeroViewSet)
you should change your view from ModelViewSet to APIView.
with API view you can include renderer_classes and template_name.
check here for more information

Unable to get image data in an API along with json data for registration

I want to create a register API in which I have username,email, password input along with an image field.I am unable to receive and process the data properly.The default user class is extended to store image field.
I have this extended user model:-
from django.contrib.auth.models import User
import os
def get_upload_path(instance, filename):
fileName, fileExtension = os.path.splitext(filename)
return os.path.join("user_%s" % instance.user.username,"user_{0}.{1}" .format(instance.user.username,fileExtension))
# Create your models here.
class Userprofile(models.Model):
user=models.OneToOneField(User,on_delete=models.CASCADE)
display_picture=models.ImageField(upload_to=get_upload_path)
has_voted=models.BooleanField(default=False)
voted_item=models.CharField(max_length=200,default='none')
def __str__(self):
return self.user.username
These are the serializers:-
from django.contrib.auth.models import User
from .models import Userprofile
class UserprofileSerializer(serializers.ModelSerializer):
class Meta:
model=Userprofile
fields=['display_picture']
class UserSerializer(serializers.ModelSerializer):
class Meta:
model=User
fields=['username','email','password1','password2']
this is the path/url:-
path('register',views.FileUploadView.as_view(),name='Register'),
this is the view:-
#csrf_exempt
class FileUploadView(APIView):
parser_classes=[MultiPartParser,FormParser]
def register(self,request):
display_picture=request.FILES["display_picture"]
data=json.loads(request.data["data"])
#saving data using serializers
return JsonResponse({'message': "Registered Successfully!"},status=200)
I am getting this issue which says:-
path('register',views.FileUploadView.as_view(),name='Register'),
AttributeError: 'function' object has no attribute 'as_view'
You are decorating a class like a function,thats why your code is breaking.
In order to use a decorator on a class, you can do either of the two approaches:
1) Decorating the class:
from django.utils.decorators import method_decorator
from django.views.decorators.csrf import csrf_exempt
#method_decorator(csrf_exempt,name='dispatch')
class FileUploadView(APIView):
parser_classes=[MultiPartParser,FormParser]
def register(self,request):
display_picture=request.FILES["display_picture"]
data=json.loads(request.data["data"])
#saving data using serializers
return JsonResponse({'message': "Registered Successfully!"},status=200)
2) Decorating in URL only:
from django.views.decorators.csrf import csrf_exempt
path('register',csrf_exempt(view.FileUploadView.as_view()))
You can read in detail here.

Django: Model Queryset to Pandas to Django Rest Framework

I am trying to accomplish the following workflow in my Django project:
Query my database
Convert the returned queryset to a pandas dataframe in order to perform some calculations & filtering
Pass the final dataframe to Django REST API Framework
if I understand correctly, I have to use django-pandas for Step 2. and Django REST Pandas for Step 3.
I installed both and read the documentaton, but I have no clue how to make it work.
What I have achieved to far is to set up my model, views, serializes and urls to have the original queryset rendered via the Django Rest Framework.
If anyone could give me a hint on how to integrate pandas in this workflow, it would be highly appreciated.
my models.py file
from django.db import models
class Fund(models.Model):
name = models.CharField(max_length=100)
commitment_size = models.IntegerField(blank=True, null=True)
commitment_date = models.DateField(blank=True, null=True)
def __str__(self):
return self.name
my views.py file
from rest_framework import generics
from rest_framework.views import APIView
from pages.models import Fund
from .serializers import FundSerializer
class FundAPIView(generics.ListAPIView):
queryset = Fund.objects.all()
serializer_class = FundSerializer
my serializers.oy file
from rest_framework import serializers
from pages.models import Fund
class FundSerializer(serializers.ModelSerializer):
class Meta:
model = Fund
fields = ('name', 'commitment_size', 'commitment_date')
So i figured it out. First, you need to install django-pandas and django rest framework (but no need to install django REST pandas)
models.py and serializers.py files stay the same as above, but the views file is different
from rest_framework.views import APIView
from rest_framework.response import Response
from django_pandas.io import read_frame # Import django_pandas.io read frame
from pages.models import Fund
from .serializers import FundSerializer
class TestData(APIView):
authentication_classes = []
permission_classes = []
def get(self, request, format=None):
data = Fund.objects.all() # Perform database query
df = read_frame(data) # Transform queryset into pandas dataframe
df['testcolumn'] = "testdata" # Perform some Pandas Operation with dataframe
return Response(df) # Return the result in JSON via Django REST Framework

Django admin field choices render as multiple checkbox

I'm trying to customise my Django admin page. I want a single model field to render all the choices passed to it as a CheckboxSelectMultiple, but can't get it to work.
Here is the relevant part of my models.py:
from django.db import models
from django.contrib.auth.models import User
from django.contrib import admin
class Event(models.Model):
GROUP_OWNER_CHOICES = (
('vcoe', "VCOE"),
('cssi', 'CSSI'),
('essc', "ESSC"),
('tmscc', "TMSCC"),
('inmc', "INMC"),
('ccs7', "CCS7"),
('ias', "IAS"),
)
group_owner = models.BooleanField(choices=GROUP_OWNER_CHOICES, blank=True, default=False)
I can't use the Django formfield_overrides(https://docs.djangoproject.com/en/dev/ref/contrib/admin/#django.contrib.admin.ModelAdmin.form) because I have more than 1 BooleanField and would like to keep the other BooleanField's intact.
Here is what I found from other questions
from django.contrib import admin
from .models import Event
from django import forms
class EventGroupOwnerAdminForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(EventGroupOwnerAdminForm, self).__init__(*args,**kwargs)
self.fields["group_owner"].widget = forms.widgets.CheckboxSelectMultiple()
class EventAdmin(admin.ModelAdmin):
form = EventGroupOwnerAdminForm
admin.site.register(Event , EventAdmin)
But the field simply doesnt render anything. Any help?

django FieldError at /search/ Cannot resolve keyword 'searchkeyword'

I am working thru the Practical Django Projects book and am stumped. The book is for an earlier version of Django. I am using v1.3.
The problem is in the view, at 'search_keyword_keyword__in...'
from django.contrib.flatpages.models import FlatPage
from django.shortcuts import render_to_response
def search(request):
query = request.GET.get('q', '')
keyword_results = results = []
if query:
keyword_results = FlatPage.objects.filter(searchkeyword__keyword__in=query.split()).distinct()
results = FlatPage.objects.filter(content__icontains=query)
return render_to_response('search/search.html',
{'query' : query,
'keyword_results': keyword_results,
'results' : results })
The models.py is
from django.contrib.flatpages.models import FlatPage
from django.db import models
class SearchKeyword(models.Model):
keyword = models.CharField(max_length=50)
page = models.ForeignKey(FlatPage)
def __unicode__(self):
return self.keyword
The full error is:
Cannot resolve keyword 'searchkeyword' into field. Choices are: content, enable_comments, id, registration_required, sites, template_name, title, url
Which I think are the options for FlatPages. It doesn't seem like the foreign key relationship is being found.
Any ideas what could be wrong or how to correctly do the lookup? Thanks.
Here is the admin.py in case it has some bearing:
from django.contrib.flatpages.admin import FlatPageAdmin
from django.contrib import admin
from cms.search.models import SearchKeyword
from django.contrib.flatpages.models import FlatPage
# Define an inline admin descriptor for SearchKeywords model
class SearchKeywordInline(admin.TabularInline):
model = SearchKeyword
# Define a FlatPageAdmin class
class ExtendedFlatPageAdmin(FlatPageAdmin):
inlines = [
SearchKeywordInline,
]
# Re-register FlatPageAdmin
admin.site.unregister(FlatPage)
admin.site.register(FlatPage, ExtendedFlatPageAdmin)
The reverse relationship for your ForeignKey would be named searchkeyword_set (see https://docs.djangoproject.com/en/dev/topics/db/queries/#backwards-related-objects), so your queryset should have searchkeyword_set__keyword__in as a a parameter (or you can use related_name.
If that didn't work, you should check that you have done manage.py syncdb ?
It seems the problem was:
from django.contrib.flatpages.models import FlatPage
from django.db import models
The models needs to come first, like:
from django.db import models
from django.contrib.flatpages.models import FlatPage
I think what was happening is the FlatPage instance was being created before the ForeignKey was created, therefore the SearchKeyword attribute was not available to FlatPage.