django_apscheduler.models.DoesNotExist: DjangoJob matching query does not exist - django

hi I am trying to implement a job scheduler using djangorestframework , django-apscheduler and requests libraries but when I try to post a request for scheduling a job following error appear although job is scheduled but response is code Internal server error (500) with following error
Traceback (most recent call last):
File "/Users/gauravyadav/Python/env4/lib/python3.6/site-packages/django/core/handlers/exception.py", line 35, in inner
response = get_response(request)
File "/Users/gauravyadav/Python/env4/lib/python3.6/site-packages/django/core/handlers/base.py", line 128, in _get_response
response = self.process_exception_by_middleware(e, request)
File "/Users/gauravyadav/Python/env4/lib/python3.6/site-packages/django/core/handlers/base.py", line 126, in _get_response
response = wrapped_callback(request, *callback_args,
**callback_kwargs)
File "/Users/gauravyadav/Python/env4/lib/python3.6/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view
return view_func(*args, **kwargs)
File "/Users/gauravyadav/Python/env4/lib/python3.6/site-packages/django/views/generic/base.py", line 69, in view
return self.dispatch(request, *args, **kwargs)
File "/Users/gauravyadav/Python/env4/lib/python3.6/site-packages/rest_framework/views.py", line 483, in dispatch
response = self.handle_exception(exc)
File "/Users/gauravyadav/Python/env4/lib/python3.6/site-packages/rest_framework/views.py", line 443, in handle_exception
self.raise_uncaught_exception(exc)
File "/Users/gauravyadav/Python/env4/lib/python3.6/site-packages/rest_framework/views.py", line 480, in dispatch
response = handler(request, *args, **kwargs)
File "/Users/gauravyadav/Python/env4/Scheduler3/distribute_jobs/views.py", line 298, in post
scheduler.start()
File "/Users/gauravyadav/Python/env4/lib/python3.6/site-packages/apscheduler/schedulers/blocking.py", line 19, in start
self._main_loop()
File "/Users/gauravyadav/Python/env4/lib/python3.6/site-packages/apscheduler/schedulers/blocking.py", line 30, in _main_loop
wait_seconds = self._process_jobs()
File "/Users/gauravyadav/Python/env4/lib/python3.6/site-packages/apscheduler/schedulers/base.py", line 987, in _process_jobs
jobstore_next_run_time = jobstore.get_next_run_time()
File "/Users/gauravyadav/Python/env4/lib/python3.6/site-packages/django_apscheduler/jobstores.py", line 29, in inner
return func(*a, **k)
File "/Users/gauravyadav/Python/env4/lib/python3.6/site-packages/django_apscheduler/jobstores.py", line 79, in get_next_run_time
return
//not able to ident this code deserialize_dt(DjangoJob.objects.filter(next_run_time__isnull=False).earlie s .t('next_run_time').next_run_time)///
File "/Users/gauravyadav/Python/env4/lib/python3.6/site-packages/django/db/models/query.py", line 597, in earliest
return self._earliest_or_latest(*fields, field_name=field_name)
File "/Users/gauravyadav/Python/env4/lib/python3.6/site-packages/django/db/models/query.py", line 594, in _earliest_or_latest
return obj.get()
File "/Users/gauravyadav/Python/env4/lib/python3.6/site-packages/django/db/models/query.py", line 403, in get
self.model._meta.object_name
django_apscheduler.models.DoesNotExist: DjangoJob matching query does not exist.
[04/Jul/2018 12:19:05] "POST /jobs/ HTTP/1.1" 500 120459
-
Heading
models.py
class Jobs(models.Model, ListCharField, ListTextField):
title = models.CharField(max_length=20, blank=False, default='')
tenantId = models.TextField(max_length=50, null=True, default='')
studentid = models.CharField(max_length=20, blank=False, default=None,
null=True, db_index=False)
contentId = models.IntegerField(blank=False, null=False, db_index=False)
version = models.IntegerField(null=True)
appVersion = models.CharField(max_length=50, null=True)
devicePlatformName = models.TextField(max_length=50, null=True)
deviceIdentity = models.TextField(max_length=200, null=True)
deviceToken = models.TextField(max_length=200, null=True)
fcmToken = models.TextField(max_length=200, null=True)
fbTokenId = models.TextField(max_length=200, null=True)
userRole = models.TextField(max_length=50, null=True)
users = ListCharField(base_field=models.CharField(max_length=50,
null=True), null=True, size=100, max_length=20000)
# # users = models.CharField(max_length=600, null=True, default='')
allUsers = models.BooleanField(default=False)
groupIdList = ListTextField(base_field=models.IntegerField(null=True),
null=True)
sendSMS = models.BooleanField(default=False)
sendEmail = models.BooleanField(default=False)
distributeDateTime = models.CharField(max_length=200, null=True)
contentType = models.CharField(max_length=200, null=True)
distributeOn = models.CharField(max_length=200, null=True)
orgId = models.CharField(max_length=200, null=False, default=None)
run_immediate = models.BooleanField(default=False)
class Meta:
ordering = ('title',)
#######serializers.py########
class JobsSerializers(serializers.ModelSerializer):
users=serializers.ListField(child=serializers.CharField(max_length=200))
groupIdList = serializers.ListField(child=serializers.IntegerField())
class Meta:
model = Jobs
fields = (
'title',
'tenantId',
'studentid',
'contentId',
'version',
'appVersion',
'devicePlatformName',
'deviceIdentity',
'deviceToken',
'fcmToken',
'fbTokenId',
'userRole',
'groupIdList',
'allUsers',
'users',
'sendSMS',
'sendEmail',
'distributeDateTime',
'contentType',
'distributeOn',
'orgId',
'run_immediate',
# 'deviceInfoData'
)
def create(self, validated_data):
"""
Create and return a new `Jobs` instance, given the validated data.
"""
return Jobs.objects.create(**validated_data)
#########views.py
from rest_framework import mixins
from rest_framework import generics
from Scheduler3 import settings
from .models import Jobs
from .serializers import JobsSerializers
import requests
import json
from apscheduler.schedulers.blocking import BlockingScheduler
from apscheduler.jobstores.sqlalchemy import SQLAlchemyJobStore
from django_apscheduler.jobstores import DjangoJobStore
scheduler = BlockingScheduler()
url = 'mysql+mysqldb://' + settings.DATABASES['default']['USER'] + ':'
\
+ settings.DATABASES['default']['PASSWORD'] + '#' +
settings.DATABASES['default']['HOST'] + '/' + \
settings.DATABASES['default']['NAME']
# jobstores = dict(default=SQLAlchemyJobStore(url=url))
# scheduler.configure(jobstores=jobstores)
scheduler.add_jobstore(DjangoJobStore(), "default")
def date_time_converter(distributeOn):
splited_run_date = '{}.000000'.format(distributeOn)
return splited_run_date
def schedule_job(users, contentId, orgId, allUsers, contentType,
tenantId, studentid, version, appVersion,
deviceInfoData, devicePlatformName, deviceIdentity,
deviceToken, fcmToken, fbTokenId, userRole,
groupIdList, sendSMS, sendEmail):
payload = {
"tenantId": "{}".format(tenantId),
"studentid": "{}".format(studentid),
"version": '{}'.format(version),
"appVersion": "{}".format(appVersion),
"devicePlatformName": "{}".format(devicePlatformName),
"deviceIdentity": "{}".format(deviceIdentity),
"deviceToken": "{}".format(deviceToken),
"fcmToken": "{}".format(fcmToken),
"fbTokenId": "{}".format(fbTokenId),
"userRole": "{}".format(userRole),
"users": users,
"allUsers": '{}'.format(allUsers) if 1 else 0,
"groupIdList": groupIdList,
"sendSMS": '{}'.format(sendSMS) if 1 else 0,
"sendEmail": '{}'.format(sendEmail) if 1 else 0,
"orgId": "{}".format(orgId),
"deviceInfoData": deviceInfoData
}
print("Payload")
print(payload)
url = 'http//:designated/url/distribute
r = requests.put(url, data=json.dumps(payload), headers=headers)
print(r.status_code, users)
print(r.reason)
print(r.text)
class JobList(mixins.ListModelMixin,
mixins.CreateModelMixin,
generics.GenericAPIView):
"""
List all jobs, or create a new job.
"""
queryset = Jobs.objects.all()
serializer_class = JobsSerializers
def get(self, request, *args, **kwargs):
return self.list(request, *args, **kwargs)
def post(self, request):
# print('c')
# scheduler.start()
# print('d')
print(request.data)
"""Serialzer data """
"""Fetching Request Data """
distributeOn = request.data.get('distributeOn')
jobTitle = request.data.get('title')
users = request.data.get('users')
contentId = request.data.get('contentId')
orgId = request.data.get('orgId')
contentType = request.data.get('contentType')
tenantId = request.data.get('tenantId')
studentid = request.data.get('studentid')
version = request.data.get('version')
appVersion = request.data.get('appVersion')
deviceInfoData = request.data.get('deviceInfoData')
devicePlatformName = request.data.get('devicePlatformName')
deviceIdentity = request.data.get('deviceIdentity')
deviceToken = request.data.get('deviceToken')
fcmToken = request.data.get('fcmToken')
fbTokenId = request.data.get('fbTokenId')
userRole = request.data.get('userRole')
groupIdList = request.data.get('groupIdList')
sendSMS = request.data.get('sendSMS')
sendEmail = request.data.get('sendEmail')
allUsers = request.data.get('allUsers')
"""Calling Time Formatter Function to provided time for Job Trigger"""
splited_datetime = date_time_converter(distributeOn)
"""Instantiating Scheduler and Scheduling Jobs"""
job1 = scheduler.add_job(schedule_job, 'date',
run_date='{}'.format(splited_datetime),
misfire_grace_time=200, args=[users,
contentId, orgId, allUsers, contentType,
tenantId,
studentid, version, appVersion,
deviceInfoData, devicePlatformName,
deviceIdentity,
deviceToken,
fcmToken, fbTokenId, userRole,
groupIdList,
sendSMS, sendEmail],
max_instances=20,
replace_existing=True)
if not scheduler.running == True:
print('c')
scheduler.start()
print('d')
print("after add job method called")
print(job1.id)
return self.create(request)
##########urls.py######
from django.conf.urls import url, include
from django.contrib import admin
from django.urls import path
urlpatterns = [
url('admin/', admin.site.urls),
url(r'^', include('distribute_jobs.urls')),
]
###distribute_jobs/url.py
from django.conf.urls import url
from rest_framework.urlpatterns import format_suffix_patterns
from distribute_jobs import views
urlpatterns = [
url(r'^jobs/$', views.JobList.as_view()),
url(r'^jobs/(?P<pk>[0-9]+)/$', views.JobDetail.as_view()),
]
urlpatterns = format_suffix_patterns(urlpatterns)

Hi this issues is a bug on django-apscheduler version=0.2.11 which resolved on version=0.2.12 for more details please click here

Related

IntegrityError : null value in column of relation " violates not-null constraint

'm building a small webstore , in the product page i put the order form using FormMixin and TemplateView, when i submit the order i get a " null value in column "customer_id" of relation "products_order" violates not-null constraint
DETAIL: Failing row contains (21, null)." error :
models.py
class Product(models.Model):
name = models.CharField(max_length=255)
description = models.TextField()
nominal_price = models.PositiveIntegerField(verbose_name='prix normal',)
reduced_price = models.PositiveIntegerField(blank=True, null=True)
quantity = models.PositiveIntegerField(default=10)
category = models.ForeignKey(Category, on_delete=models.CASCADE, related_name='products')
photo = models.ImageField(upload_to="img/products/", default="img/products/user_default.png")
def __str__(self):
return self.name
class Customer(models.Model):
full_name = models.CharField(max_length=150)
address = models.CharField(max_length=1500, null=True)
phone = models.IntegerField()
city = models.CharField(max_length=100)
email = models.EmailField(null=True)
def __str__(self):
return self.full_name
class Order (models.Model):
product = models.ManyToManyField(Product, through='OrderProduct')
customer = models.ForeignKey(Customer, on_delete=models.CASCADE)
class OrderProduct(models.Model):
order = models.ForeignKey(Order, on_delete=models.CASCADE)
product = models.ForeignKey(Product, on_delete=models.CASCADE)
views.py :
class ProductDetailView(FormMixin, TemplateView):
model = Product
template_name = 'product.html'
form_class = OrderForm
def get_success_url(self):
return reverse('index')
def post(self, request, *args, **kwargs):
context = self.get_context_data()
form = OrderForm(request.POST)
if context['form'].is_valid():
product = get_object_or_404(Product, name=self.kwargs['product_name'])
customer = form.save()
instance = Order.objects.create(customer=customer)
instance.product.set(product)
return super(TemplateView, self)
def get_context_data(self, **kwargs):
context = super(ProductDetailView, self).get_context_data(**kwargs)
context['product'] = Product.objects.get(name=self.kwargs['product_name'])
context['form'] = self.get_form()
return context
urls.py
from django.urls import path
from . import views
urlpatterns = [
path('', views.ProductListView.as_view(), name='index'),
path ('<str:product_name>/', views.ProductDetailView.as_view(), name='product'),
path('categories/', views.CategoryListView.as_view(), name='categories'),
path('add_category', views.AddCategoryView.as_view(), name='add_category'),
path('add_product/', views.AddProductView.as_view(), name='add_product'),
path('categories/<str:category_name>/', views.CategoryProductsView.as_view(), name='category_products'),
]
Traceback
Traceback (most recent call last):
File "D:\Python\Django\Django projects\Store\venv\lib\site-packages\django\core\handlers\exception.py", line 47, in inner
response = get_response(request)
File "D:\Python\Django\Django projects\Store\venv\lib\site-packages\django\utils\deprecation.py", line 119, in __call__
response = self.process_response(request, response)
File "D:\Python\Django\Django projects\Store\venv\lib\site-packages\django\middleware\clickjacking.py", line 26, in process_response
if response.get('X-Frame-Options') is not None:
AttributeError: 'super' object has no attribute 'get'

int() argument must be a string, a bytes-like object or a number, not 'ModelBase'

I'm fairly new to Django, and coding in general so this could be a conceptual oversight, but I'm running out of ideas so any help is appreciated.
I'm trying to add logic to my form's clean() method which has nested try blocks. I'm trying to get object instances from different ForeignKey related models in each try block. The first two levels seem to work fine, but the third level throws the error below. I've printed the value and type for wine_get.wine_id and I get back 6 and 'int' respectively, so I'm not sure why this isn't considered a number.
Environment:
Request Method: POST
Request URL: http://127.0.0.1:8000/post/new/
Django Version: 2.1
Python Version: 3.6.5
Installed Applications:
['django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'debug_toolbar',
'bootstrap4',
'accounts',
'groups',
'posts']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'debug_toolbar.middleware.DebugToolbarMiddleware']
Traceback:
File "/anaconda3/lib/python3.6/site-packages/django/core/handlers/exception.py" in inner
34. response = get_response(request)
File "/anaconda3/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response
126. response = self.process_exception_by_middleware(e, request)
File "/anaconda3/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response
124. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/anaconda3/lib/python3.6/site-packages/django/views/generic/base.py" in view
68. return self.dispatch(request, *args, **kwargs)
File "/anaconda3/lib/python3.6/site-packages/django/contrib/auth/mixins.py" in dispatch
52. return super().dispatch(request, *args, **kwargs)
File "/anaconda3/lib/python3.6/site-packages/django/views/generic/base.py" in dispatch
88. return handler(request, *args, **kwargs)
File "/anaconda3/lib/python3.6/site-packages/django/views/generic/edit.py" in post
141. if form.is_valid():
File "/anaconda3/lib/python3.6/site-packages/django/forms/forms.py" in is_valid
185. return self.is_bound and not self.errors
File "/anaconda3/lib/python3.6/site-packages/django/forms/forms.py" in errors
180. self.full_clean()
File "/anaconda3/lib/python3.6/site-packages/django/forms/forms.py" in full_clean
382. self._clean_form()
File "/anaconda3/lib/python3.6/site-packages/django/forms/forms.py" in _clean_form
409. cleaned_data = self.clean()
File "/Users/evan/code/wine/wineProject/wineProject/posts/forms.py" in clean
78. wine = wine_get,
File "/anaconda3/lib/python3.6/site-packages/django/db/models/manager.py" in manager_method
82. return getattr(self.get_queryset(), name)(*args, **kwargs)
File "/anaconda3/lib/python3.6/site-packages/django/db/models/query.py" in get
390. clone = self.filter(*args, **kwargs)
File "/anaconda3/lib/python3.6/site-packages/django/db/models/query.py" in filter
841. return self._filter_or_exclude(False, *args, **kwargs)
File "/anaconda3/lib/python3.6/site-packages/django/db/models/query.py" in _filter_or_exclude
859. clone.query.add_q(Q(*args, **kwargs))
File "/anaconda3/lib/python3.6/site-packages/django/db/models/sql/query.py" in add_q
1263. clause, _ = self._add_q(q_object, self.used_aliases)
File "/anaconda3/lib/python3.6/site-packages/django/db/models/sql/query.py" in _add_q
1287. split_subq=split_subq,
File "/anaconda3/lib/python3.6/site-packages/django/db/models/sql/query.py" in build_filter
1225. condition = self.build_lookup(lookups, col, value)
File "/anaconda3/lib/python3.6/site-packages/django/db/models/sql/query.py" in build_lookup
1096. lookup = lookup_class(lhs, rhs)
File "/anaconda3/lib/python3.6/site-packages/django/db/models/lookups.py" in __init__
20. self.rhs = self.get_prep_lookup()
File "/anaconda3/lib/python3.6/site-packages/django/db/models/fields/related_lookups.py" in get_prep_lookup
115. self.rhs = target_field.get_prep_value(self.rhs)
File "/anaconda3/lib/python3.6/site-packages/django/db/models/fields/__init__.py" in get_prep_value
965. return int(value)
Exception Type: TypeError at /post/new/
Exception Value: int() argument must be a string, a bytes-like object or a number, not 'ModelBase'
Local vars from error:
Variable Value
__class__ <class 'posts.forms.WineForm'>
post_type 'opened'
quantity 2
self <WineForm bound=True, valid=True, fields=(winemaker;wine;vintage;post_type;quantity;rating;location;tasting_notes)>
vintage '1950'
wine 'Cellar 2'
wine_get <Wine: Cellar 2>
winemaker 'Cellar 2'
winemaker_get <WineMaker: Cellar 2>
Session data:
Variable Value
'_auth_user_backend' 'django.contrib.auth.backends.ModelBackend'
'_auth_user_hash' '2c72b4192e2d568f616919e66da6b281d3764e4f'
'_auth_user_id' '2'
models.py
class WineMaker(models.Model):
winemaker_id = models.AutoField(primary_key=True)
name = models.CharField(max_length=255, unique=True)
region = models.ForeignKey(
WineRegion,
db_column = 'region_id',
related_name = 'winemaker_region',
on_delete = models.CASCADE,
null = True
)
def __str__(self):
return self.name
class Meta:
db_table = 'winemakers'
class Wine(models.Model):
wine_id = models.AutoField(primary_key=True)
name = models.CharField(max_length=510)
winemaker = models.ForeignKey(
WineMaker,
db_column = 'winemaker_id',
related_name = 'wine_winemakers',
on_delete = models.CASCADE
)
vintage = models.CharField(
max_length = 10,
choices = VINTAGES,
default = 'none'
)
description = models.TextField(max_length=3000, null=True)
style = models.ForeignKey(
Style,
db_column = 'style_id',
related_name = 'wine_styles',
on_delete = models.CASCADE,
null = True
)
varietal = models.ForeignKey(
Varietal,
db_column = 'varietal_id',
related_name = 'wine_varietals',
on_delete = models.CASCADE,
null = True
)
blend = models.ForeignKey(
Blend,
db_column = 'blend_id',
related_name = 'wine_blends',
on_delete = models.CASCADE,
null = True
)
def __str__(self):
return self.name
class Meta:
db_table = 'wines'
unique_together = ('winemaker', 'name', 'vintage')
class UserCellar(models.Model):
id = models.AutoField(primary_key=True)
user = models.ForeignKey(
settings.AUTH_USER_MODEL,
related_name = 'userCellar_users',
on_delete = models.CASCADE
)
wine = models.ForeignKey(
Wine,
db_column = 'wine_id',
related_name = 'userCellar_wines',
on_delete = models.CASCADE
)
quantity = models.SmallIntegerField(default=0)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
def __int__(self):
return self.wine_id
def __str__(self):
return self.wine.name
class Meta:
db_table = 'user_cellars'
unique_together = ('user', 'wine')
...
forms.py
from django import forms
from .models import *
from django.contrib.auth import get_user_model
from .choices import VINTAGES, POST_TYPE_CHOICES
user = get_user_model()
class WineForm(forms.Form):
winemaker = forms.CharField(max_length=255)
wine = forms.CharField(max_length=510)
vintage = forms.ChoiceField(
choices = VINTAGES
)
post_type = forms.ChoiceField(
choices = POST_TYPE_CHOICES
)
quantity = forms.IntegerField(
required = False
)
rating = forms.IntegerField(
required = False
)
location = forms.CharField(
max_length = 255,
required = False
)
tasting_notes = forms.CharField(
max_length = 2000,
required = False,
widget = forms.Textarea
)
class Meta:
labels = {
'winemaker' : 'Winemaker',
'wine' : 'Wine',
'vintage' : 'Vintage',
'post_type' : 'Activity Type',
'rating' : 'Rating',
'location' : 'Location',
'tasting_notes' : 'Tasting Notes',
}
def __init__(self, *args, **kwargs):
super(WineForm, self).__init__(*args, **kwargs)
self.fields['quantity'].widget.attrs={
'id': 'quantity'
}
def clean(self):
super().clean()
winemaker = self.cleaned_data.get('winemaker')
wine = self.cleaned_data.get('wine')
vintage = self.cleaned_data.get('vintage')
post_type = self.cleaned_data.get('post_type')
quantity = self.cleaned_data.get('quantity')
if post_type and quantity:
# If both fields are valid
if post_type == 'opened':
try:
# Try to get the WineMaker instance
winemaker_get = WineMaker.objects.get(
name = winemaker,
)
try:
#Try to get the Wine instance
wine_get = Wine.objects.get(
name = wine,
winemaker = winemaker_get,
vintage = vintage,
)
try:
#Try to get the UserCellar instance
cellar_get = UserCellar.objects.get(
user = user,
wine = wine_get,
)
...
I'm afraid my original answer below is rubbish. When filtering on a foreign key, Django doesn't care if you pass an object or just a primary key:
# wm is a WineMaker object; the next 2 lines are both valid
wines1 = Wine.objects.filter(winemaker=wm)
wines2 = Wine.objects.filter(winemaker=wm.id)
===================
The stack trace is clear that the issue is with this line (though the error message is arguably less than helpful):
wine_id = wine_get.wine_id
Since wine_id is a foreign key, you need to pass a Wine instance:
wine_id = wine_get

DRF Serializer fields DictField() AttributeError: 'str' object has no attribute 'items'

In django rest framework If i use DictField() in serializer its given me AttributeError at /api/v1/analytics/reports-configuration/1/
‘str’ object has no attribute ‘items’ error.please take a look.
serializers.py
import json
from rest_framework import serializers
from models import ReportConfiguration
class ReportConfigurationSerializer(serializers.ModelSerializer):
report_type = serializers.ChoiceField(choices=['query', 'activity', 'summary'])
read_only = serializers.BooleanField(required=True)
query_data = serializers.DictField(required=True)
class Meta:
model = ReportConfiguration
fields = ('id', 'title', 'query_data', 'created_by', 'last_activity_by', 'deleted',
'deleted_by', 'added_at', 'last_activity_at', 'report_type', 'read_only')
def validate(self, data):
if data['report_type'] is not 'summary' and data['read_only'] is True:
raise serializers.ValidationError("If read only true then report type should be summary")
if data['report_type'] is 'summary' and data['read_only'] is not True:
raise serializers.ValidationError("If read only not true then report type should not be summary")
return data
def create(self, validated_data):
validated_data['created_by'] = self.context['request'].user
validated_data['last_activity_by'] = self.context['request'].user
return ReportConfiguration.objects.create(**validated_data)
views.py
class ReportConfigurationViewSet(viewsets.ModelViewSet):
serializer_class = ReportConfigurationSerializer
queryset = ReportConfiguration.objects.all()
permission_classes = (permissions.IsAuthenticated,)
filter_backends = (DjangoFilterBackend,)
filter_class = ReportFilter
def list(self, request):
response = super(ReportConfigurationViewSet, self).list(request)
for data in response.data['results']:
data['query_data'] = json.loads(data['query_data'])
return response
def retrieve(self, request, pk=None):
response = super(ReportConfigurationViewSet, self).retrieve(request, pk=pk)
response.data['query_data'] = json.loads(response.data['query_data'])
return response
models.py
class ReportConfiguration(models.Model):
class ReportTypeChoice(Choice):
QueryReport = 'query'
ActivityReport = 'activity'
SummaryList = 'summary'
title = models.CharField(max_length=300, unique=True, blank=False, null=False)
query_data = JSONField(default={})
created_by = models.ForeignKey(User, null=True, blank=True, related_name='report_created_by')
last_activity_by = models.ForeignKey(User, null=True, blank=True,related_name='last_active_in_report')
deleted = models.BooleanField(default=False)
deleted_by = models.ForeignKey(User, null=True, blank=True, related_name='report_deleted_by')
added_at = models.DateTimeField(auto_now_add=True)
last_activity_at = models.DateTimeField(default=timezone.now)
report_type = models.CharField(max_length=15, choices=ReportTypeChoice)
read_only = models.BooleanField(default=False)
Error:
Starting development server at http://127.0.0.1:8000/
Quit the server with CONTROL-C.
ERROR Internal Server Error: /api/v1/analytics/reports-configuration/1/
Traceback (most recent call last):
File "/Users/ranvijay.s/.virtualenvs/my_project/lib/python2.7/site-packages/django/core/handlers/base.py", line 149, in get_response
response = self.process_exception_by_middleware(e, request)
File "/Users/ranvijay.s/.virtualenvs/my_project/lib/python2.7/site-packages/django/core/handlers/base.py", line 147, in get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/Users/ranvijay.s/.virtualenvs/my_project/lib/python2.7/site-packages/django/views/decorators/csrf.py", line 58, in wrapped_view
return view_func(*args, **kwargs)
File "/Users/ranvijay.s/.virtualenvs/my_project/lib/python2.7/site-packages/rest_framework/viewsets.py", line 83, in view
return self.dispatch(request, *args, **kwargs)
File "/Users/ranvijay.s/.virtualenvs/my_project/lib/python2.7/site-packages/rest_framework/views.py", line 477, in dispatch
response = self.handle_exception(exc)
File "/Users/ranvijay.s/.virtualenvs/my_project/lib/python2.7/site-packages/rest_framework/views.py", line 437, in handle_exception
self.raise_uncaught_exception(exc)
File "/Users/ranvijay.s/.virtualenvs/my_project/lib/python2.7/site-packages/rest_framework/views.py", line 474, in dispatch
response = handler(request, *args, **kwargs)
File "/Users/ranvijay.s/wk/project/django/dhanalytics/views.py", line 47, in retrieve
response = super(ReportConfigurationViewSet, self).retrieve(request, pk=pk)
File "/Users/ranvijay.s/.virtualenvs/my_project/lib/python2.7/site-packages/rest_framework/mixins.py", line 58, in retrieve
return Response(serializer.data)
File "/Users/ranvijay.s/.virtualenvs/my_project/lib/python2.7/site-packages/rest_framework/serializers.py", line 527, in data
ret = super(Serializer, self).data
File "/Users/ranvijay.s/.virtualenvs/my_project/lib/python2.7/site-packages/rest_framework/serializers.py", line 262, in data
self._data = self.to_representation(self.instance)
File "/Users/ranvijay.s/.virtualenvs/my_project/lib/python2.7/site-packages/rest_framework/serializers.py", line 496, in to_representation
ret[field.field_name] = field.to_representation(attribute)
File "/Users/ranvijay.s/.virtualenvs/my_project/lib/python2.7/site-packages/rest_framework/fields.py", line 1601, in to_representation
for key, val in value.items()
AttributeError: 'str' object has no attribute 'items'

Exception Type: ValidationError at /home Exception Value: [u"'1a3288b3-7588-483f-8e85-1affa952dbbf' value must be an integer."]

I have created registration page , model for it and when user gets registered he gets redirected to home page. When i click on register user is getting inserted in database but when it redirects to home page i am getting this error:
Traceback:
File "C:\Python27\lib\site-packages\django\core\handlers\exception.py" in inner
39. response = get_response(request)
File "C:\Python27\lib\site-packages\django\core\handlers\base.py" in _get_response
187. response = self.process_exception_by_middleware(e, request)
File "C:\Python27\lib\site-packages\django\core\handlers\base.py" in _get_response
185. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\KR\Desktop\projects\project2\welcome\homeview.py" in home
14. if request.user.is_authenticated():
File "C:\Python27\lib\site-packages\django\utils\functional.py" in inner
234. self._setup()
File "C:\Python27\lib\site-packages\django\utils\functional.py" in _setup
380. self._wrapped = self._setupfunc()
File "C:\Python27\lib\site-packages\django\contrib\auth\middleware.py" in
24. request.user = SimpleLazyObject(lambda: get_user(request))
File "C:\Python27\lib\site-packages\django\contrib\auth\middleware.py" in get_user
12. request._cached_user = auth.get_user(request)
File "C:\Python27\lib\site-packages\django\contrib\auth__init__.py" in get_user
180. user_id = _get_user_session_key(request)
File "C:\Python27\lib\site-packages\django\contrib\auth__init__.py" in _get_user_session_key
59. return get_user_model()._meta.pk.to_python(request.session[SESSION_KEY])
File "C:\Python27\lib\site-packages\django\db\models\fields__init__.py" in to_python
927. params={'value': value},
Exception Type: ValidationError at /home
Exception Value: [u"'1a3288b3-7588-483f-8e85-1affa952dbbf' value must be an integer."]
This is the model:
class user_model(AbstractBaseUser):
user_id = models.CharField(max_length=50, primary_key=True)
username = models.CharField(max_length=50, unique=True)
first_name = models.CharField(max_length=50, default="None")
last_name = models.CharField(max_length=50, default="None")
email = models.EmailField(default="None")
password = models.CharField(max_length=150, default="abc123")
'''Custom user information fields. '''
myself = models.CharField(max_length=300, default="None")
address = models.CharField(max_length=300, default="None")
mobilePh = models.CharField(max_length=20, default="None")
workPh = models.CharField(max_length=20, default="None")
workEmail = models.EmailField(default="None")
last_login = models.CharField(max_length=50, default="None")
profile_pic = models.ImageField(width_field=None, height_field=None,
blank=True, default="None",
upload_to=upload_profile_pic)
banner_pic = models.ImageField(width_field=None, height_field=None,
blank=True, default="None",
upload_to=upload_banner_pic)
USERNAME_FIELD = 'username'
REQUIRED_FIELDS = ['user_id']
class Meta:
db_table = 'user_model'
app_label = 'welcome'
This is the register view
def register(request):
if request.method == 'POST':
if validate_registration_attributes(request.POST):
user_uuid = uuid.uuid4()
try:
user = User.objects.create(user_id=str(user_uuid), last_login=str(datetime.datetime.now()),
username=request.POST['username'],
first_name=request.POST['first_name'],
last_name=request.POST['last_name'],
email=request.POST['email'],
profile_pic="blank_image.png",
banner_pic="blank_image.png",
password='',
)
user.set_password(request.POST['passwd_1'])
user.save()
login(request, user)
return HttpResponseRedirect('/home')
except Exception as err:
user.delete()
print "Something happened"
raise Exception("""EXCEPTION at register-user.objects.create in
userObject:%s""" % (err))
global exceptmsg
return HttpResponseRedirect('/welcome')
else:
print "New account registration form validation failed"
context = {'RegisterResponse': exceptmsg}
return render(request, 'welcome.html', context)
This is the home view:
def home(request):
if request.user.is_authenticated():
return HttpResponseRedirect('/home')
else:
return HttpResponseRedirect('/welcome')
Is it the problem with the model or anything else. Please help.
I had forgot to override the default user model in settings.py. I changed the value of AUTH_USER_MODEL to myappname.user_model. Now it works fine.

django imagekit: set ProcessedImageField from image url

I have got an image url and I want to set a ProcessedImageField attribute from it during object saving. So far I have got this:
class Video(Media):
url = models.URLField('url', max_length=256, default='')
embed_url = models.URLField('embed url', max_length=256, default='')
thumbnail = ProcessedImageField(upload_to='uploads',
processors=[ResizeToFit(width=1024, height=1024, upscale=False)],
format='JPEG',
options={'quality': 75})
def save(self, *args, **kwargs):
from django.core.files.temp import NamedTemporaryFile
import shutil
import requests
import re
params = {
'url': self.url,
'autoplay': 1,
'format': 'json',
}
try:
data = requests.get('http://www.youtube.com/oembed', params=params).json()
embed_url = re.search('src=[\'"]([^\'"]*)[\'"]', data['html']).group(1)
thumbnail_url = data['thumbnail_url']
except:
pass
response = requests.get(thumbnail_url, stream=True)
img_temp = NamedTemporaryFile(delete=True)
shutil.copyfileobj(response.raw, img_temp)
# now image data are in img_temp, how to pass that to ProcessedImageField?
super(Video, self).save(*args, **kwargs)
You should be able to save directly to that property at that point.
self.thumbnail.save("filename.ext", img_temp)
This is the resulting code (without error handling) of mine. In the end, I did in in a simpler manner by avoiding a temporary file and using ContentFile instead.
class Video(Media):
url = models.URLField('url', max_length=256, default='')
embed_url = models.URLField('embed url', max_length=256, default='')
author = models.CharField('author', max_length=64, default='', blank=True)
thumbnail = ProcessedImageField(upload_to='uploads',
processors=[ResizeToFit(width=1024, height=1024, upscale=False)],
format='JPEG',
options={'quality': 75})
def save(self, *args, **kwargs):
from django.core.files.base import ContentFile
import requests
import re
params = {
'url': self.url,
'format': 'json',
}
data = requests.get('http://www.youtube.com/oembed', params=params).json()
embed_url = re.search('src=[\'"]([^\'"]*)[\'"]', data['html']).group(1)
thumbnail_url = data['thumbnail_url']
author = data['author_name']
title = data['title']
image_data = requests.get(thumbnail_url, stream=True).raw.data
self.thumbnail.save(title, ContentFile(image_data), save=False)
self.embed_url = embed_url
self.author = author
self.title = title
super(Video, self).save(*args, **kwargs)
Ok, i've ended with this code for Python 3 :)
it has built-in retries with timeouts between them and support for downloading large files
def save_image_from_url(self, image_url):
s = requests.Session()
retries = Retry(total=5,
backoff_factor=0.1,
status_forcelist=[500, 502, 503, 504])
s.mount('https://', HTTPAdapter(max_retries=retries))
response = s.get(image_url, stream=True, timeout=9)
# here just use whatever name you want, I've just retrieve the path from my custom field
folder_name = Artist.image.field.upload_to.sub_path
random_name = uuid.uuid4().hex + ".png"
# creating folder if it doen't exist
try:
os.makedirs(os.path.join(settings.MEDIA_ROOT, folder_name))
except OSError as e:
if e.errno != errno.EEXIST:
raise
# loading image to tmp location and saving it, it's for large files because we can't handle them in memory
tmp = tempfile.NamedTemporaryFile(delete=True)
try:
tmp.write(response.raw.read())
with open(tmp.name, 'rb') as f:
self.image.save(random_name, f)
finally:
tmp.close()
Where self.image is ProcessedImageField