I am a bit puzzled with the Django object models. I have models like this:
# Create your models here.
class Item(models.Model):
code = models.CharField(max_length=200, unique=True)
barcode = models.CharField(max_length=300)
desc = models.CharField('Description',max_length=500)
reg_date = models.DateField('registered date')
registrar = models.CharField(max_length=100)
def __unicode__(self):
return self.code + ' : ' + self.desc
class ItemInfo(models.Model):
item = models.OneToOneField(Item, primary_key=True)
supplier = models.ForeignKey(Supplier)
stock_on_hand = models.IntegerField()
stock_on_order = models.IntegerField()
cost = models.IntegerField()
price = models.IntegerField()
unit = models.CharField(max_length=100)
lead_time = models.IntegerField()
But when I tried to retrieve the Item and ItemInfo into modelforms, I got this error:
'ModelFormOptions' object has no attribute 'many_to_many'. I suspected there is something wrong with this line supplier = models.ForeignKey(Supplier). Can someone explained me when to use ForeignKeyor the relationships fields (OneToOneFields, ManyToManyFields, ManyToOneFields)
Edit: ModelForm:
class ItemForm(ModelForm):
class Meta:
model = Item
widgets = {
'registrar' : TextInput(attrs={'ReadOnly' : 'True'})
}
class ItemInfoForm(ModelForm):
class Meta:
model = ItemInfo
exclude = ('item')
This is how I generate the form with populated value from the models:
def details(request, code):
csrf_context = RequestContext(request)
current_user = User
if request.user.is_authenticated():
item = Item.objects.get(pk=code)
item_info = ItemInfo.objects.get(pk=item.pk)
item_form = ItemForm(instance=item)
item_info_form = ItemInfoForm(instance=item_form)
return render_to_response('item/details.html',
{'item_form' : item_form, 'item_info_form' : item_info_form},
csrf_context)
else:
return render_to_response('error/requires_login.html', csrf_context)
Traceback:
Traceback:
File "C:\Python27\lib\site-packages\django\core\handlers\base.py" in get_response
111. response = callback(request, *callback_args, **callback_kwargs)
File "G:\tulip\stock\item\views.py" in details
131. item_info_form = ItemInfoForm(instance=item_form)
File "C:\Python27\lib\site-packages\django\forms\models.py" in __init__
237. object_data = model_to_dict(instance, opts.fields, opts.exclude)
File "C:\Python27\lib\site-packages\django\forms\models.py" in model_to_dict
112. for f in opts.fields + opts.many_to_many:
Exception Type: AttributeError at /item/details/1/
Exception Value: 'ModelFormOptions' object has no attribute 'many_to_many'
You are instantiating ItemInfoForm with ItemForm instance. While instance should be ItemInfo instance, not form
Correct line:
item_info_form = ItemInfoForm(instance=item_info)
Related
I noticed this error in my application, "'NoneType' object has no attribute 'day'". What I have noticed about it is that. I have a model named course_schedule, the course schedule has an option of Monday to Sunday. If the course schedule is partially populated, that is I populate only some days, like 3 days out of the complete 7 days in a week, I get the error but whenever I populate the course schedule populate course schedule model completely, I don't have the error and everything works well.
error log:
Traceback (most recent call last):
File "C:\Users\Habib\Documents\django\FIVERR\Ayyub_SMS\venv\lib\site-packages\django\core\handlers\exception.py", line 47, in inner
response = get_response(request)
File "C:\Users\Habib\Documents\django\FIVERR\Ayyub_SMS\venv\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\Habib\Documents\django\FIVERR\Ayyub_SMS\sms\schoolapp\views.py", line 1754, in sir_course
get_all = getall(2021, sch.day)
Exception Type: AttributeError at /en/sir_course
Exception Value: 'NoneType' object has no attribute 'day'
models.py
class Assign_teacher_to_courses(models.Model):
Course_Name = models.ForeignKey(add_courses, on_delete=models.CASCADE)
Teacher_Name = models.ForeignKey(add_teacher_by_manager, on_delete=models.CASCADE)
def __str__(self):
return self.Course_Name.Course_Name+" - "+self.Teacher_Name.teacher_ID+" - "+self.Teacher_Name.teacher_name
class course_schedule(models.Model):
days_choices = (
("Mon", 'Monday'),
("Tue", 'Tuesday'),
('Wed', "Wednessday"),
('Thurs', "Thursday"),
('Fri', "Friday"),
('Sat', "Saturday"),
("Sun", "Sunday"),
)
day = models.CharField(max_length=60, default="Sun")
time_session = models.CharField(max_length=150, default='8:00am')
end_session = models.CharField(max_length=150, default='10:00am')
def __str__(self):
return self.day
views.py
def sir_course(request):
if request.method == "POST":
get_course_name_th = Assign_teacher_to_courses.objects.filter(Teacher_Name=get_id_teach)
# print(get_course_name_th)
store_email_teacher_dtta = store_email_teach_new.objects.filter(Teacher_ID=teach_course_id)
days = {}
for course in get_course_name_th:
# print(course.Course_Name.syllabus)
sch = course_schedule.objects.get(id=course.Course_Name.pk)
get_all = getall(2021, sch.day)
lists = {}
for n in get_all:
date = n.strftime("%d/%m/%Y")
try:
if days[str(date)]:
days[str(date)].append(str(course.Course_Name.Course_Name)+" "+str(course.Course_Name.course_code))
except KeyError:
days[str(date)] = [str(course.Course_Name.Course_Name)+" "+str(course.Course_Name.course_code),]
# print(days)
context1 = {'get_course_name_t_cours':get_course_name_th, "days": days}
return render(request, 'teacher_page.html', context1)
else:
return redirect('/')
Looks like maybe sch is None.
You should always put your object get in a try...except block or you can use the inbuilt get_object_or_404
Following a previous question snippet of your add_courses model.
class add_courses(models.Model):
Course_Name = models.CharField(max_length=200, blank=True)
Manager_Name = models.ForeignKey(Manager_login_information, on_delete=models.CASCADE, blank=True)
description = models.TextField(default='', blank=True)
syllabus = models.TextField(default='', blank=True)
student = models.ManyToManyField(add_students_by_manager, blank=True)
schedule = models.ForeignKey(course_schedule, on_delete=models.CASCADE, blank=True)
def __str__(self):
return self.Course_Name
You have the following relationship path from Assign_teacher_to_courses to course_schedule:
Assign_teacher_to_courses -> add_courses -> course_schedule
Therefore to get the schedule of each course in get_course_name_th you should change sch = course_schedule.objects.get(id=course.Course_Name.pk) to sch = course.Course_Name.schedule.
I have 2 models: Categories and CategoryAdditionalAttributes that has foreign key to Categories.
Also, I'm creating an inline form set for CategoryAdditionalAttributes, but I meet this error in the testing phase:
models.py
class Categories(models.Model):
category_breadcrumb = models.CharField(max_length=512, unique=True)
class Meta:
app_label = 'assortment'
def __str__(self):
return self.category_breadcrumb
class CategoryAdditionalAttribute(models.Model):
category = models.ForeignKey(
Categories, on_delete=models.CASCADE, related_name='additional_attributes')
attribute_key = models.CharField(max_length=500)
attribute_value = models.CharField(max_length=1000)
class Meta:
app_label = 'assortment'
def __str__(self):
return "{}: {}".format(str(self.attribute_key), self.attribute_value)
def __unicode__(self):
return "{}: {}".format(str(self.attribute_key), self.attribute_value)
admin.py
class CategoryAdditionalAttributeInlineFormSet(BaseInlineFormSet):
class Meta:
model = CategoryAdditionalAttribute
fields = ['attribute_key', 'attribute_value']
def save_new_objects(self, commit=True):
saved_attributes = super(
CategoryAdditionalAttributeInlineFormSet, self).save_new_objects(commit)
if commit:
CategoryAdditionalAttributeService()
.insert_additional_attributes(saved_attributes, self.deleted_forms)
return saved_attributes
def save_existing_objects(self, commit=True):
saved_attributes = super(
CategoryAdditionalAttributeInlineFormSet, self).save_existing_objects(commit)
if commit:
CategoryAdditionalAttributeService()
.insert_additional_attributes(saved_attributes, self.deleted_forms)
return saved_attributes
class CategoryAttributeInline(admin.TabularInline):
model = CategoryAdditionalAttribute
formset = CategoryAdditionalAttributeInlineFormSet
extra = 1
class CategoriesAdmin(admin.ModelAdmin):
form = CategoriesForm
search_fields = ['category_breadcrumb']
inlines = [CategoryAttributeInline]
test
class CategoryAdditionalAttributesTest(TestCase):
....
def test_insert_additional_attribute_success(self):
AttributeFormSet = inlineformset_factory(
Categories, CategoryAdditionalAttribute, form=CategoryAdditionalAttributeInlineFormSet)
data = {
'form-TOTAL_FORMS': '1',
'form-INITIAL_FORMS': '0',
'form-MAX_NUM_FORMS': '',
'form-0-category': self.test_category,
'form-0-attribute_key': 'a_room',
'form-0-attribute_value': 'Kamar Mandi'
}
test_attribute_formset = AttributeFormSet(data)
self.assertEqual(test_attribute_formset.is_valid(), True)
Results
Traceback (most recent call last):
File "/home/varian/.local/share/virtualenvs/f1-thanos- aRnD22rB/local/lib/python2.7/site-packages/mock/mock.py", line 1305, in patched
return func(*args, **keywargs)
File "/home/varian/Desktop/dekoruma/f1- thanos/thanos/apps/assortment/tests/test_admin.py", line 134, in test_insert_additional_attribute_success
test_attribute_formset = AttributeFormSet(data)
File "/home/varian/.local/share/virtualenvs/f1-thanos-aRnD22rB/local/lib/python2.7/site-packages/django/forms/models.py", line 885, in __init__
if self.form._meta.fields and self.fk.name not in self.form._meta.fields:
AttributeError: type object 'CategoryAdditionalAttributeForm' has no attribute '_meta'
Any help will be appreciated.
I'm a beginner with Python and Django and I'm stuck with my view. I get the following error when I try to render a request : Django error: AttributeError at / 'GalleryListViewIndex' object has no attribute 'META'.
I don't know why I get this, i searched for some answers and tried some manipulations but everything I did wasn't working.
I'm using photologue to build a little portfolio application and I'm trying to get the first picture of a gallery to display it on an index page.
Here is the model for Gallery and Photo classes :
photologue.models.Gallery :
class Gallery(models.Model):
date_added = models.DateTimeField(_('date published'),
default=now)
title = models.CharField(_('title'),
max_length=250,
unique=True)
slug = models.SlugField(_('title slug'),
unique=True,
max_length=250,
help_text=_('A "slug" is a unique URL-friendly title for an object.'))
description = models.TextField(_('description'),
blank=True)
is_public = models.BooleanField(_('is public'),
default=True,
help_text=_('Public galleries will be displayed '
'in the default views.'))
photos = SortedManyToManyField('Photo',
related_name='galleries',
verbose_name=_('photos'),
blank=True)
sites = models.ManyToManyField(Site, verbose_name=_(u'sites'),
blank=True)
objects = GalleryQuerySet.as_manager()
class Meta:
ordering = ['-date_added']
get_latest_by = 'date_added'
verbose_name = _('gallery')
verbose_name_plural = _('galleries')
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse('photologue:pl-gallery', args=[self.slug])
def latest(self, limit=LATEST_LIMIT, public=True):
if not limit:
limit = self.photo_count()
if public:
return self.public()[:limit]
else:
return self.photos.filter(sites__id=settings.SITE_ID)[:limit]
def sample(self, count=None, public=True):
"""Return a sample of photos, ordered at random.
If the 'count' is not specified, it will return a number of photos
limited by the GALLERY_SAMPLE_SIZE setting.
"""
if not count:
count = SAMPLE_SIZE
if count > self.photo_count():
count = self.photo_count()
if public:
photo_set = self.public()
else:
photo_set = self.photos.filter(sites__id=settings.SITE_ID)
return random.sample(set(photo_set), count)
def photo_count(self, public=True):
"""Return a count of all the photos in this gallery."""
if public:
return self.public().count()
else:
return self.photos.filter(sites__id=settings.SITE_ID).count()
photo_count.short_description = _('count')
def public(self):
"""Return a queryset of all the public photos in this gallery."""
return self.photos.is_public().filter(sites__id=settings.SITE_ID)
def orphaned_photos(self):
"""
Return all photos that belong to this gallery but don't share the
gallery's site.
"""
return self.photos.filter(is_public=True)\
.exclude(sites__id__in=self.sites.all())
photologue.models.Photos :
class Photo(ImageModel):
title = models.CharField(_('title'),
max_length=250,
unique=True)
slug = models.SlugField(_('slug'),
unique=True,
max_length=250,
help_text=_('A "slug" is a unique URL-friendly title for an object.'))
caption = models.TextField(_('caption'),
blank=True)
date_added = models.DateTimeField(_('date added'),
default=now)
is_public = models.BooleanField(_('is public'),
default=True,
help_text=_('Public photographs will be displayed in the default views.'))
sites = models.ManyToManyField(Site, verbose_name=_(u'sites'),
blank=True)
objects = PhotoQuerySet.as_manager()
class Meta:
ordering = ['-date_added']
get_latest_by = 'date_added'
verbose_name = _("photo")
verbose_name_plural = _("photos")
def __str__(self):
return self.title
def save(self, *args, **kwargs):
if self.slug is None:
self.slug = slugify(self.title)
super(Photo, self).save(*args, **kwargs)
def get_absolute_url(self):
return reverse('photologue:pl-photo', args=[self.slug])
def public_galleries(self):
"""Return the public galleries to which this photo belongs."""
return self.galleries.filter(is_public=True)
def get_previous_in_gallery(self, gallery):
"""Find the neighbour of this photo in the supplied gallery.
We assume that the gallery and all its photos are on the same site.
"""
if not self.is_public:
raise ValueError('Cannot determine neighbours of a non-public photo.')
photos = gallery.photos.is_public()
if self not in photos:
raise ValueError('Photo does not belong to gallery.')
previous = None
for photo in photos:
if photo == self:
return previous
previous = photo
def get_next_in_gallery(self, gallery):
"""Find the neighbour of this photo in the supplied gallery.
We assume that the gallery and all its photos are on the same site.
"""
if not self.is_public:
raise ValueError('Cannot determine neighbours of a non-public photo.')
photos = gallery.photos.is_public()
if self not in photos:
raise ValueError('Photo does not belong to gallery.')
matched = False
for photo in photos:
if matched:
return photo
if photo == self:
matched = True
return None
My views.py for the index page :
class GalleryListViewIndex(ListView):
paginate_by = 20
def get_queryset(request):
x = []
queryset = Gallery.objects.on_site().is_public()[:4]
for g in queryset:
r = [g.photos.first()]
x += r
first_pic = x
return render(request,'index.html', context={'first_pic': first_pic})
This is where I'm picking up the first picture of 4 galleries.
And here is the traceback for the error :
Traceback:
File "/home/toasti/Bureau/projet/python3/lib/python3.4/site-packages/django/core/handlers/base.py" in get_response
149. response = self.process_exception_by_middleware(e, request)
File "/home/toasti/Bureau/projet/python3/lib/python3.4/site-packages/django/core/handlers/base.py" in get_response
147. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/toasti/Bureau/projet/python3/lib/python3.4/site-packages/django/views/generic/base.py" in view
68. return self.dispatch(request, *args, **kwargs)
File "/home/toasti/Bureau/projet/python3/lib/python3.4/site-packages/django/views/generic/base.py" in dispatch
88. return handler(request, *args, **kwargs)
File "/home/toasti/Bureau/projet/python3/lib/python3.4/site-packages/django/views/generic/list.py" in get
159. self.object_list = self.get_queryset()
File "/home/toasti/Bureau/projet/python3/lib/python3.4/site-packages/photologue/views.py" in get_queryset
35. return render(request,'index.html', context={'first_pic': first_pic})
File "/home/toasti/Bureau/projet/python3/lib/python3.4/site-packages/django/shortcuts.py" in render
67. template_name, context, request=request, using=using)
File "/home/toasti/Bureau/projet/python3/lib/python3.4/site-packages/django/template/loader.py" in render_to_string
97. return template.render(context, request)
File "/home/toasti/Bureau/projet/python3/lib/python3.4/site-packages/django/template/backends/django.py" in render
95. return self.template.render(context)
File "/home/toasti/Bureau/projet/python3/lib/python3.4/site-packages/django/template/base.py" in render
204. with context.bind_template(self):
File "/usr/lib/python3.4/contextlib.py" in __enter__
59. return next(self.gen)
File "/home/toasti/Bureau/projet/python3/lib/python3.4/site-packages/debug_toolbar/panels/templates/panel.py" in _request_context_bind_template
79. context = processor(self.request)
File "/home/toasti/Bureau/projet/python3/lib/python3.4/site-packages/django/template/context_processors.py" in debug
41. if settings.DEBUG and request.META.get('REMOTE_ADDR') in settings.INTERNAL_IPS:
Exception Type: AttributeError at /
Exception Value: 'GalleryListViewIndex' object has no attribute 'META'
I really don't understand why it raises me this error. Any help would be really appreciated...!
get_queryset has one job and one job only, that is to get a queryset (hence its name)
def get_queryset(self):
return Gallery.objects.on_site().is_public()[:4]
The rest of your logic you currently have in there probably belongs in get_context_data
def get_context_data(self, *args, **kwargs):
context = super(GalleryListViewIndex, self).get_context_data(*args, **kwargs)
x = []
for g in self.get_queryset():
r = [g.photos.first()]
x += r
first_pic = x
context['first_pic'] = first_pic
return context
The actual rendering should then be done by just setting the template_name
template_name = 'index.html'
I'm trying to map a foreign key to POST data when creating a new object through a serializer. There are two foreign keys in the object, one is serializing perfectly, the other is creating an error.
Model:
class Event(models.Model):
owner = models.ForeignKey('auth.User', related_name='owner', blank=True)
date = models.DateField('eventdate')
time = models.TimeField('eventtime', default=now)
eventtype = models.ForeignKey(EventType, related_name='eventtype', blank=True)
# duration = models.DurationField()
location = models.CharField(max_length=200, blank=True)
attenders = models.ManyToManyField(User, related_name='attenders')
invited = models.ManyToManyField(User, related_name='invitedlist')
View:
class EventMixin(RetrieveUpdateDestroyAPIView, CreateAPIView):
serializer_class = EventSerializer
def get_queryset(self):
return Event.objects.all()
def partial_update(self, request, *args, **kwargs):
request['owner'] = request.user
sname = request['eventtype']
request['eventtype'] = EventType.objects.filter(sname=sname)
json_str = json.dumps(self.request.data)
data = json.loads(json_str)
try:
invited = list(data['toInvite'])
for i in invited:
for j in User.objects.filter(username=i):
invite = EventInvite(invited=j, sender=request.user, event=self.get_object())
invite.save()
self.get_object().invited.add()
except KeyError:
pass
return super(EventMixin, self).partial_update(request, *args, **kwargs)
def create(self, request, *args, **kwargs):
new = {}
new['owner'] = request.user.__dict__
new['date'] = request.data['date']
new['time'] = request.data['time']
new['location'] = request.data['location']
sname = request.data['eventtype']
new['eventtype'] = EventType.objects.get(sname=sname).__dict__
json_str = json.dumps(self.request.data)
data = json.loads(json_str)
serializer = EventMixinSerializer(data=new)
with open('/tmp/log.txt', 'w+') as f:
f.write(str(serializer.is_valid()))
f.write(str(serializer.validated_data))
f.close()
serializer.is_valid();
serializer.save()
try:
invited = list(data['toInvite'])
for i in invited:
for j in User.objects.filter(username=i):
invite = EventInvite(invited=j, sender=request.user, event=self.get_object())
invite.save()
self.get_object().invited.add()
except KeyError:
pass
Serializer:
class EventMixinSerializer(serializers.ModelSerializer):
owner = UserSerializer(read_only=True)
eventtype = EventTypeSerializer()
attenders = FriendsListingField(read_only=True)
invited = FriendsListingField(read_only=True)
class Meta:
model = Event
fields = ('owner', 'eventtype', 'date', 'time', 'location', 'id', 'attenders', 'invited')
def create(self, validated_data):
owner = validated_data.pop('owner')
owner = owner.instance
eventtype = validated_data.pop('eventtype')
eventtype = eventtype.instance
event = Event.objects.create(owner=owner, eventtype=eventtype, **validated_data)
event.save()
return event
Error when owner field present:
False
{'owner': OrderedDict([('username', ['A user with that username already exists.'])])}
Result when UserSerializer(read_only=True) (pretty much diabling it):
True
OrderedDict([('eventtype', OrderedDict([('lname', 'Swimming'), ('sname', 'SWM'), ('category', '1')])), ('date', datetime.date(2015, 12, 22)), ('$
(Notice the event type data in the result)
Thanks!
You need to remove the validators from UserSerializer.
Assuming UserSerializer is a User ModelSerializer it'll extract the unique constraint on the User.username from the Model and your validation will fail.
To work this around you'll need to remove the UniqueValidator by overriding the validators list for the username field of the UserSerializer
Please help me out of this django REST framework issue .I am trying to create on rest api which which will populate data in two tables based on argument passed .
My models look like .
class WorkloadType(models.Model):
type = models.CharField(max_length=60)
status = models.BooleanField(default=True)
class Workload(models.Model):
workload_type = models.ForeignKey(WorkloadType)
workload_group = models.IntegerField(blank=True, null=True)
name = models.CharField(max_length = 60)
hdd_gb = models.IntegerField(blank=True, null=True)
ssd_gb = models.IntegerField(blank=True, null=True)
iops = models.CharField(max_length = 60)
vcpu = models.IntegerField(blank=True, null=True)
cpu = models.IntegerField(blank=True, null=True)
created_date = models.DateTimeField(auto_now_add=True, blank=True)
status = models.BooleanField(default=True)
class VdiWorkload(models.Model):
workload = models.ForeignKey(Workload)
provision_type = models.CharField(max_length = 60)
number_of_users = models.IntegerField()
json_data = models.CharField(max_length=255,blank = True,null = True)
status = models.BooleanField(default=True)
created_date = models.DateTimeField(auto_now_add=True, blank=True)
I have my serializer.py file which is looking like .
from django.forms import widgets
from rest_framework import serializers
from models import WorkloadType,Workload, \
VdiWorkload,DbWorkload,\
VmWorkload,ExchangeWorkload,RawWorkload
class VdiSerializer(serializers.Serializer):
class Meta:
model = VdiWorkload
class WorkloadSerializer(serializers.Serializer):
vdi = VdiSerializer(required = False)
pk = serializers.IntegerField(read_only=True)
workload_group = serializers.IntegerField(required=False)
workload_type = serializers.CharField(max_length = 10)
name = serializers.CharField(max_length = 60)
hdd_gb = serializers.IntegerField()
ssd_gb = serializers.IntegerField()
iops = serializers.CharField(max_length = 60)
vcpu = serializers.IntegerField()
cpu = serializers.IntegerField()
class Meta:
model = Workload
fields = ('vdi','workload_group','workload_type','name','hdd_gb','ssd_gb','iops','vcpu','cpu')
def create(self, validated_data):
"""
Create and return a new `Workload` instance, given the validated data.
"""
wt = WorkloadType.objects.get(type = validated_data['workload_type'])
validated_data['workload_type'] = wt
print "=-=-=-=-=-=-=-=-=-=-=-=-=------"
if not validated_data['workload_group']:
workload_group = Workload.objects.latest('workload_group')
validated_data['workload_group'] = workload_group
else:
try:
workload_group = Workload.objects.latest('workload_group')
validated_data['workload_group'] = workload_group + 1
except:validated_data['workload_group'] = 1
#try:node_exist = Workload.objects.get(name = validated_data['name'])
#except:node_exist = None
#if node_exist:
# raise serializers.ValidationError('Node name already exist.')
#else:
wl = Workload.objects.create(**validated_data)
VdiWorkload.objects.create(workload=wl, **validated_data)
return wl
Now I passing the rest body like.
{
"type": "Exchange",
"iops": "22",
"name": "another model",
"hdd_gb": "23",
"ssd_gb": "320",
"hdd_count": "123",
"ssd_count": "4",
"memory": "123",
"core": "114",
"rackspace": "6",
"vcpu":"12",
"workload_type":"VDI",
"workload_group":true,
"cpu":"1",
"vdi":[{
"provision_type":"user",
"number_of_users":"10",
"json_data":"any extra data which we want"
}]
}
But whenever I am making post request I am getting the error
Traceback
raceback:
File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py" in get_response
111. response = callback(request, *callback_args, **callback_kwargs)
File "/usr/local/lib/python2.7/dist-packages/django/views/decorators/csrf.py" in wrapped_view
77. return view_func(*args, **kwargs)
File "/home/rohit/workspace/sizer/src/sizer/Workload/views.py" in workload_list
49. serializer.save()
File "/usr/local/lib/python2.7/dist-packages/rest_framework/serializers.py" in save
164. self.instance = self.create(validated_data)
File "/home/rohit/workspace/sizer/src/sizer/Workload/WorkloadSerializer.py" in create
63. return Workload.objects.create(**validated_data)
File "/usr/local/lib/python2.7/dist-packages/django/db/models/manager.py" in create
137. return self.get_query_set().create(**kwargs)
File "/usr/local/lib/python2.7/dist-packages/django/db/models/query.py" in create
375. obj = self.model(**kwargs)
File "/usr/local/lib/python2.7/dist-packages/django/db/models/base.py" in __init__
367. raise TypeError("'%s' is an invalid keyword argument for this function" % kwargs.keys()[0])
Exception Type: TypeError at /workload/workloadlist/
Exception Value: 'vdi' is an invalid keyword argument for this functi
Please do let me know if you need any other info I am still not able to solve out this question .
I am not able to identify this issue as I am new in DRF .
Please do let me know what might I am doing wrong here .My views looklike .
#csrf_exempt
def workload_list(request):
"""
List all code users, or create a new user.
"""
print "Herer I am *****************************111111"
if request.method == 'GET':
print "Herer I am *****************************"
workloads = Workload.objects.all()
serializer = WorkloadSerializer(workloads, many=True)
return JSONResponse(serializer.data)
elif request.method == 'POST':
data = JSONParser().parse(request)
serializer = WorkloadSerializer(data=data)
print serializer
print "****************** I am in ***********views now "
if serializer.is_valid():
serializer.save()
return JSONResponse(serializer.data, status=201)
return JSONResponse(serializer.errors, status=400)
Forgive me if this is off track but it looks to me like the model doesn't know anything about the nested field (vdi). Did you try popping it off validated_data?
Here's a small (untested) example of what I have been working on using djangorestframework==3.1.3 with Django==1.7.
models.py:
class Child(models.Model):
child_data = models.CharField(max_length=255)
class Parent(models.Model):
# Set 'related_name' to the nested field name in the serializer.
child_id = models.ForeignKey(Child, related_name='child')
serializers.py:
class ChildSerializer(serializers.ModelSerializer):
class Meta:
model = Child
class ParentSerializer(serializers.ModelSerializer):
# The ForeignKey in the model is supplied with this name so that GET
# requests can populate this and the source field below makes it
# accessible in create after validation.
child = TestInfoSerializer(source='child_id')
class Meta:
model = Parent
fields = ('child', )
def create(self, validated_data):
child_data = validated_data.pop('child_id') # strip out child_id for subsequent Parent create
try:
# try to find an existing row to fulfill the foreign key
child_instance = Child.objects.filter(**child_data)[0]
except IndexError:
# create a new row
child_instance = Child.objects.create(**child_data)
return Parent.objects.create(child_id=child_instance, **validated_data)
With this I can POST nested JSON without thinking about the foreign key:
{
"child": {
"child_data": "asdf"
}
}
GET also returns the nested representation with this setup.
I hope this helps.