I'm trying to create a form that submits a model with a foreign key but i got this error :
Traceback (most recent call last):
File "C:\Users\~\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\handlers\exception.py", line 41, in inner
response = get_response(request)
File "C:\Users\~\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\handlers\base.py", line 187, in _get_response
response = self.process_exception_by_middleware(e, request)
File "C:\Users\~\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\handlers\base.py", line 185, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\~\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\views\decorators\csrf.py", line 58, in wrapped_view
return view_func(*args, **kwargs)
File "~.py", line 21, in wrap
return function(request, *args, **kwargs)
File "~.py", line 32, in wrap
return function(request, *args, **kwargs)
File "~.py", line 428, in example
PostFormSet = inlineformset_factory(User, Post, fields=('longitude', 'latitude', 'placename', 'explanation', ))
File "C:\Users\~\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\forms\models.py", line 1038, in inlineformset_factory
fk = _get_foreign_key(parent_model, model, fk_name=fk_name)
File "C:\Users\~\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\forms\models.py", line 980, in _get_foreign_key
opts = model._meta
AttributeError: 'function' object has no attribute '_meta'
model.py
class Post(models.Model):
owner = models.ForeignKey(User,on_delete=models.CASCADE,related_name="posts",blank=False,null=False)
</other fields>...
class PostImage(models.Model):
owner = models.ForeignKey(Post,on_delete=models.CASCADE,related_name="images",blank=False,null=False)
views.py
def example(request):
context = {
'hellow we':"qfqf"
}
print(request.user)
PostFormSet = inlineformset_factory(User, Post, fields=('longitude', 'latitude', 'placename', 'explanation', ))
print("------------------------------------------------------------")
print(frm.errors)
return JsonResponse(context, encoder=JSONEncoder)
I found the problem. There was another function named Post in the views
Related
i have created this serializer to validate on the presence of a record with these column combination`
class CampaignServicesValidation(serializers.Serializer):
campaign_id = serializers.IntegerField(required=True)
service_id = serializers.IntegerField(required=True)
def validate(self, data):
try:
campaign_service = CampaignServices.objects.get(campaign_id=data['campaign_id'],
service_id=data['service_id'])
print("found"+str(campaign_service.id))
except Exception:
raise serializers.ValidationError(detail='Campaign Service does not exist')
return campaign_service
and it is called in my viewSet like this:
campaign_service = CampaignServicesValidation(data={'campaign_id': request.data['campaign_id'], 'service_id': pk})
if not campaign_service.is_valid():
return RestResponse(status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, serializer_error=campaign_service.errors)
when the combination is not found it raises an exception and works well, but when it passes validation and enters the is_valid() function in the if condition it produces this error
Traceback (most recent call last):
File "D:\RightsHero\collector-management\venv\lib\site-packages\django\core\handlers\exception.py", line 55, in inner
response = get_response(request)
File "D:\RightsHero\collector-management\venv\lib\site-packages\django\core\handlers\base.py", line 197, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "D:\RightsHero\collector-management\venv\lib\site-packages\django\views\decorators\csrf.py", line 54, in wrapped_view
return view_func(*args, **kwargs)
File "D:\RightsHero\collector-management\venv\lib\site-packages\rest_framework\viewsets.py", line 125, in view
return self.dispatch(request, *args, **kwargs)
File "D:\RightsHero\collector-management\venv\lib\site-packages\rest_framework\views.py", line 509, in dispatch
response = self.handle_exception(exc)
File "D:\RightsHero\collector-management\venv\lib\site-packages\rest_framework\views.py", line 469, in handle_exception
self.raise_uncaught_exception(exc)
File "D:\RightsHero\collector-management\venv\lib\site-packages\rest_framework\views.py", line 480, in raise_uncaught_exception
raise exc
File "D:\RightsHero\collector-management\venv\lib\site-packages\rest_framework\views.py", line 506, in dispatch
response = handler(request, *args, **kwargs)
File "D:\RightsHero\collector-management\collectors_management\views.py", line 157, in update_campaign_service_frequency
serializer.save()
File "D:\RightsHero\collector-management\venv\lib\site-packages\rest_framework\serializers.py", line 207, in save
self.instance = self.update(self.instance, validated_data)
File "D:\RightsHero\collector-management\venv\lib\site-packages\rest_framework\serializers.py", line 993, in update
info = model_meta.get_field_info(instance)
File "D:\RightsHero\collector-management\venv\lib\site-packages\rest_framework\utils\model_meta.py", line 35, in get_field_info
opts = model._meta.concrete_model._meta
AttributeError: 'CampaignServicesValidation' object has no attribute '_meta'
I have tried changing serializer.Serializer to ModelSerialzier but nothing changed
Since Serializer does not have a _meta attribute, it does not have the is_valid() method. Instead, you should check the serializer.errors attribute of the serializer after calling validate().
I am trying to grab a user's list using Django Rest Framework and an Ajax request. However, I get the following error
AttributeError: 'UserListViewSet' object has no attribute 'GET'
Not sure what I am doing wrong - I am newer to DRF than vanilla Django.
Ajax call:
const showUserLists = function(map){
let userName = "Henry";
$.ajax({
type: 'GET',
url: '/api/userlist/',
data: {
'username': userName
},
success: function (data) {
data.forEach(item => {
console.log(item.list_name)
$("#userLists").append("<li class=userlist data-name=\"" + item.list_name + "\">" + item.list_name + "</li>")
})
}
});
};
urls.py:
router = DefaultRouter()
router.register('userlist', views.UserListViewSet, basename= 'userlist')
router.register('uservenue', views.UserVenueViewSet, basename= 'uservenue')
views.py
#this shows all lists for a user
class UserListViewSet(viewsets.ModelViewSet):
serializer_class = UserListSerializer
def get_queryset(request):
name = request.GET.get('username', None)
return UserList.objects.filter(user=name)
Traceback:
Traceback (most recent call last):
File "/Users/x/Desktop/Coding/anybody/avenv/lib/python3.6/site-packages/django/core/handlers/exception.py", line 47, in inner
response = get_response(request)
File "/Users/x/Desktop/Coding/anybody/avenv/lib/python3.6/site-packages/django/core/handlers/base.py", line 179, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/Users/x/Desktop/Coding/anybody/avenv/lib/python3.6/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view
return view_func(*args, **kwargs)
File "/Users/x/Desktop/Coding/anybody/avenv/lib/python3.6/site-packages/rest_framework/viewsets.py", line 114, in view
return self.dispatch(request, *args, **kwargs)
File "/Users/x/Desktop/Coding/anybody/avenv/lib/python3.6/site-packages/rest_framework/views.py", line 505, in dispatch
response = self.handle_exception(exc)
File "/Users/x/Desktop/Coding/anybody/avenv/lib/python3.6/site-packages/rest_framework/views.py", line 465, in handle_exception
self.raise_uncaught_exception(exc)
File "/Users/x/Desktop/Coding/anybody/avenv/lib/python3.6/site-packages/rest_framework/views.py", line 476, in raise_uncaught_exception
raise exc
File "/Users/x/Desktop/Coding/anybody/avenv/lib/python3.6/site-packages/rest_framework/views.py", line 502, in dispatch
response = handler(request, *args, **kwargs)
File "/Users/x/Desktop/Coding/anybody/avenv/lib/python3.6/site-packages/rest_framework/mixins.py", line 38, in list
queryset = self.filter_queryset(self.get_queryset())
File "/Users/x/Desktop/Coding/anybody/anybody1/api/views.py", line 33, in get_queryset
name = request.GET.get('username', None)
AttributeError: 'UserListViewSet' object has no attribute 'GET'
The first parameter of get_queryset is not a request, but the UserListViewSet, so the self, you can obtain the request with self.request:
class UserListViewSet(viewsets.ModelViewSet):
serializer_class = UserListSerializer
def get_queryset(self):
name = self.request.GET.get('username', None)
return UserList.objects.filter(user=name)
I get a name error: pk is not defined although I can see that the pk is passed to the view from the url.
urls.py:
from django.conf.urls import url
from cashflow.views import cashflowView, SelectAccountView, CashflowEditView
from django.urls import path
app_name = 'cashflow'
urlpatterns = [
url(r'^select_account', SelectAccountView.as_view(), name="select_account"),
url(r'^$', cashflowView.as_view(), name="cashflow_processing"),
path('edit/<pk>/', CashflowEditView.as_view(), name="cashflow_editing"),
]
views.py:
class CashflowEditView(UpdateView):
model = ttransactions
template_name = 'cashflow/cashflow_processing.html'
form_class = CashflowForm
success_url = 'cashflow'
def get_form_kwargs(self):
kwargs = super(CashflowEditView, self).get_form_kwargs()
kwargs['request'] = self.request
return kwargs
def get_queryset(self, **kwargs):
transaction = ttransactions.objects.filter(pk=pk)
transaction_lines = transaction_lines.objects.filter(transaction=transaction.id)
return transaction, transaction_lines
I get the error on the line transaction = ttransactions.objects.filter(pk=pk)
When I run in debug I can see that pk is send to the view but when I use it on the object I get the error.
I will appreciate help to resolve the problem for me.
I added the print(kwargs) as specified and got this in the terminal:
Internal Server Error: /cashflow/edit/42/
Traceback (most recent call last):
File "C:\Users\94ber\PycharmProjects\pythonProject\dev\venv\lib\site-packages\django\core\handlers\exception.py", line 4
7, in inner
response = get_response(request)
File "C:\Users\94ber\PycharmProjects\pythonProject\dev\venv\lib\site-packages\django\core\handlers\base.py", line 179, i
n _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\94ber\PycharmProjects\pythonProject\dev\venv\lib\site-packages\django\views\generic\base.py", line 70, in
view
return self.dispatch(request, *args, **kwargs)
File "C:\Users\94ber\PycharmProjects\pythonProject\dev\venv\lib\site-packages\django\views\generic\base.py", line 98, in
dispatch
return handler(request, *args, **kwargs)
File "C:\Users\94ber\PycharmProjects\pythonProject\dev\venv\lib\site-packages\django\views\generic\edit.py", line 189, i
n get
self.object = self.get_object()
File "C:\Users\94ber\PycharmProjects\pythonProject\dev\venv\lib\site-packages\django\views\generic\detail.py", line 30,
in get_object
queryset = self.get_queryset()
File "C:\Users\94ber\PycharmProjects\pythonProject\dev\aberni\cashflow\views.py", line 274, in get_queryset
transaction = ttransactions.objects.filter(pk=pk)
NameError: name 'pk' is not defined
[06/Jan/2021 16:01:25] "GET /cashflow/edit/42/ HTTP/1.1" 500 86062
Internal Server Error: /favicon.ico/
Traceback (most recent call last):
File "C:\Users\94ber\PycharmProjects\pythonProject\dev\venv\lib\site-packages\django\db\models\fields\__init__.py", line
1774, in get_prep_value
return int(value)
ValueError: invalid literal for int() with base 10: 'favicon.ico'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\94ber\PycharmProjects\pythonProject\dev\venv\lib\site-packages\django\core\handlers\exception.py", line 4
7, in inner
response = get_response(request)
File "C:\Users\94ber\PycharmProjects\pythonProject\dev\venv\lib\site-packages\django\core\handlers\base.py", line 179, i
n _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\94ber\PycharmProjects\pythonProject\dev\venv\lib\site-packages\django\views\generic\base.py", line 70, in
view
return self.dispatch(request, *args, **kwargs)
File "C:\Users\94ber\PycharmProjects\pythonProject\dev\venv\lib\site-packages\django\views\generic\base.py", line 98, in
dispatch
return handler(request, *args, **kwargs)
File "C:\Users\94ber\PycharmProjects\pythonProject\dev\venv\lib\site-packages\django\views\generic\detail.py", line 106,
in get
self.object = self.get_object()
File "C:\Users\94ber\PycharmProjects\pythonProject\dev\venv\lib\site-packages\django\views\generic\detail.py", line 36,
in get_object
queryset = queryset.filter(pk=pk)
File "C:\Users\94ber\PycharmProjects\pythonProject\dev\venv\lib\site-packages\django\db\models\query.py", line 942, in f
ilter
return self._filter_or_exclude(False, *args, **kwargs)
File "C:\Users\94ber\PycharmProjects\pythonProject\dev\venv\lib\site-packages\django\db\models\query.py", line 962, in _
filter_or_exclude
clone._filter_or_exclude_inplace(negate, *args, **kwargs)
File "C:\Users\94ber\PycharmProjects\pythonProject\dev\venv\lib\site-packages\django\db\models\query.py", line 969, in _
filter_or_exclude_inplace
self._query.add_q(Q(*args, **kwargs))
File "C:\Users\94ber\PycharmProjects\pythonProject\dev\venv\lib\site-packages\django\db\models\sql\query.py", line 1358,
in add_q
clause, _ = self._add_q(q_object, self.used_aliases)
File "C:\Users\94ber\PycharmProjects\pythonProject\dev\venv\lib\site-packages\django\db\models\sql\query.py", line 1377,
in _add_q
child_clause, needed_inner = self.build_filter(
File "C:\Users\94ber\PycharmProjects\pythonProject\dev\venv\lib\site-packages\django\db\models\sql\query.py", line 1319,
in build_filter
condition = self.build_lookup(lookups, col, value)
File "C:\Users\94ber\PycharmProjects\pythonProject\dev\venv\lib\site-packages\django\db\models\sql\query.py", line 1165,
in build_lookup
lookup = lookup_class(lhs, rhs)
File "C:\Users\94ber\PycharmProjects\pythonProject\dev\venv\lib\site-packages\django\db\models\lookups.py", line 24, in
__init__
self.rhs = self.get_prep_lookup()
File "C:\Users\94ber\PycharmProjects\pythonProject\dev\venv\lib\site-packages\django\db\models\lookups.py", line 76, in
get_prep_lookup
return self.lhs.output_field.get_prep_value(self.rhs)
File "C:\Users\94ber\PycharmProjects\pythonProject\dev\venv\lib\site-packages\django\db\models\fields\__init__.py", line
1776, in get_prep_value
raise e.__class__(
ValueError: Field 'id' expected a number but got 'favicon.ico'.
[06/Jan/2021 16:01:26] "GET /favicon.ico/ HTTP/1.1" 500 138586
transaction = ttransactions.objects.filter(pk=pk)
Where are you getting the variable pk from? Are you expecting it to come from kwargs? If so then it should be:
transaction = ttransactions.objects.filter(pk=kwargs['pk'])
You have to fetch pk value from kwargs dictionary.
Try this:
def get_queryset(self, **kwargs):
pk = int(kwargs['pk'])
transaction = ttransactions.objects.filter(pk=pk)
transaction_lines = transaction_lines.objects.filter(transaction=transaction.id)
return transaction, transaction_lines
I'm trying to send a post request from PostMan into my Django view and I'm getting this error. "AttributeError: 'QueryDict' object has no attribute '_meta'"
From what I've gathered it has something to do with the form.save() as seen in traceba
I've searched all over to find a solution or even a better way to achieve an image post from a external web client to a Django server.
All help is very much appreciated.
Traceback
Capture.PNG
form is valid
Internal Server Error: /getimg/
Traceback (most recent call last):
File "C:\Users\Gedit\Desktop\django\virtualenv\lib\site-packages\django\core\handlers\exception.py", line 34, in inner
response = get_response(request)
File "C:\Users\Gedit\Desktop\django\virtualenv\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response
response = self.process_exception_by_middleware(e, request)
File "C:\Users\Gedit\Desktop\django\virtualenv\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\Gedit\Desktop\django\virtualenv\lib\site-packages\django\views\decorators\csrf.py", line 54, in wrapped_view
return view_func(*args, **kwargs)
File "C:\Users\Gedit\Desktop\django\virtualenv\lib\site-packages\django\views\generic\base.py", line 71, in view
return self.dispatch(request, *args, **kwargs)
File "C:\Users\Gedit\Desktop\django\virtualenv\lib\site-packages\rest_framework\views.py", line 505, in dispatch
response = self.handle_exception(exc)
File "C:\Users\Gedit\Desktop\django\virtualenv\lib\site-packages\rest_framework\views.py", line 465, in handle_exception
self.raise_uncaught_exception(exc)
File "C:\Users\Gedit\Desktop\django\virtualenv\lib\site-packages\rest_framework\views.py", line 476, in raise_uncaught_exception
raise exc
File "C:\Users\Gedit\Desktop\django\virtualenv\lib\site-packages\rest_framework\views.py", line 502, in dispatch
response = handler(request, *args, **kwargs)
File "C:\Users\Gedit\Desktop\django\virtualenv\lib\site-packages\rest_framework\decorators.py", line 50, in handler
return func(*args, **kwargs)
File "C:\Users\Gedit\Desktop\django\indivproj\getimg\api\views.py", line 21, in getimg
form.save()
File "C:\Users\Gedit\Desktop\django\virtualenv\lib\site-packages\rest_framework\serializers.py", line 207, in save
self.instance = self.update(self.instance, validated_data)
File "C:\Users\Gedit\Desktop\django\virtualenv\lib\site-packages\rest_framework\serializers.py", line 979, in update
info = model_meta.get_field_info(instance)
File "C:\Users\Gedit\Desktop\django\virtualenv\lib\site-packages\rest_framework\utils\model_meta.py", line 35, in get_field_info
opts = model._meta.concrete_model._meta
AttributeError: 'QueryDict' object has no attribute '_meta'
[24/Mar/2020 13:39:25] "POST /getimg/ HTTP/1.1" 500 20251
Views.py
#api_view(['POST',])
def getimg(request):
if request.method == 'POST':
form = ImageSerializer(request.POST, request.FILES)
logger.warning(request.FILES['img'])
if form.is_valid():
#raise_exception=True
logger.warning('form is valid')
form.save()
logger.warning()
response_dict = {'post': 'success'}
return HttpResponse(simplejson.dumps(response_dict), content_type='application/javascript')
else:
logger.warning(form.errors)
else:
form = ImageSerializer()
return render(request, 'getimg.html', {'form': form})
Serializers.py
class ImageSerializer(serializers.ModelSerializer):
class Meta:
model = Image
fields = '__all__'
Models.py
class Image(models.Model):
# name = models.CharField(default='name', max_length=30)
img = models.ImageField(upload_to='images/', max_length=1000)
Urls.py
app_name = 'getimg'
urlpatterns = [
# ex: /polls/
path('', views.getimg, name='getimg'),
path('gettext/', views.gettext, name='gettext'),
path('success', views.success, name = 'success'),
]
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Postman
so after looking around as a smart individual I realized i have not defined what save() function is... so now i do
The code that fixed the error but still not working
def save(self):
img = Image(
img =self.validated_data['img'],
)
I have a model Condition that has a field symptoms, which takes multiple different Symptoms objects. Whenever, I make a POST request to create a Condition object, I get the following error:
'Condition: epilepsy' needs to have a value for field "condition" before this many-to-many relationship can be used.
The above 'Condition: epilepsy' is nested between <>, but theres a formatting issue with posting that.
Here is my Condition model:
class Condition(models.Model):
class Treatment():
SURGERY, NON_INVASIVE, PRESCRIPTION_MEDICINE, NONE = range(4)
CHOICES = (
(SURGERY, 'Surgery'),
(NON_INVASIVE, 'Non-Invasive Treatment'),
(PRESCRIPTION_MEDICINE, 'Prescription Medicine'),
(NONE, 'None')
)
class Medicalfield(models.Model):
ONCOLOGY, CARDIOLOGY, NEPHROLOGY, PEDIATRICS, ENDOCRONOLOGY, PSYCHOLOGY = range(6)
CHOICES = (
(ONCOLOGY, 'Oncology'),
(CARDIOLOGY, 'Cardiology'),
(NEPHROLOGY, 'Nephrology'),
(PEDIATRICS, 'Pediatrics'),
(ENDOCRONOLOGY, 'Endocronology'),
(PSYCHOLOGY, 'Psychology')
)
name = models.CharField(max_length=200)
contagious = models.BooleanField()
treatable = models.BooleanField()
treatment = models.IntegerField(choices=Treatment.CHOICES, null=True)
severeity = models.IntegerField(default=0)
symptoms = models.ManyToManyField('Symptom', blank=True)
medicalfield = models.IntegerField(choices=Medicalfield.CHOICES, null=True)
new = ConditionManager()
def __unicode__(self):
return u"%s" % ( self.name )
Here is my Serializer
class ConditionSerializer(serializers.ModelSerializer):
def create(self, validated_data):
attrs = validated_data
request = self.context['request']
return Condition.new.create_condition(**attrs)
class Meta:
model = Condition
fields = ('id', 'treatment', 'name', 'contagious', 'treatable', 'treatment', 'severeity', 'symptoms', 'medicalfield')
Here is the Manager
class ConditionManager(models.Manager):
use_in_migrations = True
use_for_related_fields=True
def create_condition(self, *args, **kwargs):
condition_obj = conditions.models.Condition(name=kwargs['name'], contagious=kwargs['contagious'], treatable=kwargs['treatable'], treatment=kwargs['treatment'], severeity=kwargs['severeity'], symptoms=kwargs['symptoms'], medicalfield=kwargs['medicalfield'])
condition_obj.save()
return condition_obj
And here is the View
#api_view(['POST'])
#permission_classes((AllowAny, ))
def create_condition(request):
context = {'request': request}
symptoms = request.data['symptoms']
symptoms = Symptom.objects.filter(name__in=symptoms)
s = []
for symptom in symptoms:
s.append(symptom.pk)
request.data['symptoms'] = s
serializer = ConditionSerializer(data=request.data, context=context)
if serializer.is_valid():
serializer.save()
return response.Response(serializer.data, status=201)
return response.Response(serializer.errors, status=400)
Traceback (most recent call last):
File "/Library/Python/2.7/site-packages/django/core/handlers/exception.py", line 39, in inner
response = get_response(request)
File "/Library/Python/2.7/site-packages/django/core/handlers/base.py", line 187, in _get_response
response = self.process_exception_by_middleware(e, request)
File "/Library/Python/2.7/site-packages/django/core/handlers/base.py", line 185, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/Library/Python/2.7/site-packages/django/views/decorators/csrf.py", line 58, in wrapped_view
return view_func(*args, **kwargs)
File "/Library/Python/2.7/site-packages/django/views/generic/base.py", line 68, in view
return self.dispatch(request, *args, **kwargs)
File "/Library/Python/2.7/site-packages/rest_framework/views.py", line 477, in dispatch
response = self.handle_exception(exc)
File "/Library/Python/2.7/site-packages/rest_framework/views.py", line 437, in handle_exception
self.raise_uncaught_exception(exc)
File "/Library/Python/2.7/site-packages/rest_framework/views.py", line 474, in dispatch
response = handler(request, *args, **kwargs)
File "/Library/Python/2.7/site-packages/rest_framework/decorators.py", line 52, in handler
return func(*args, **kwargs)
File "/Users/user/medicalrecords/conditions/views.py", line 28, in create_condition
serializer.save()
File "/Library/Python/2.7/site-packages/rest_framework/serializers.py", line 214, in save
self.instance = self.create(validated_data)
File "/Users/user/medicalrecords/conditions/serializers.py", line 24, in create
return Condition.new.create_condition(**attrs)
File "/Users/user/medicalrecords/conditions/managers.py", line 17, in create_condition
condition_obj = conditions.models.Condition(name=kwargs['name'], contagious=kwargs['contagious'], treatable=kwargs['treatable'], treatment=kwargs['treatment'], severeity=kwargs['severeity'], symptoms=kwargs['symptoms'], medicalfield=kwargs['medicalfield'])
File "/Library/Python/2.7/site-packages/django/db/models/base.py", line 550, in __init__
setattr(self, prop, kwargs[prop])
File "/Library/Python/2.7/site-packages/django/db/models/fields/related_descriptors.py", line 499, in __set__
manager = self.__get__(instance)
File "/Library/Python/2.7/site-packages/django/db/models/fields/related_descriptors.py", line 476, in __get__
return self.related_manager_cls(instance)
File "/Library/Python/2.7/site-packages/django/db/models/fields/related_descriptors.py", line 783, in __init__
(instance, self.source_field_name))
ValueError: "<Condition: epilepsy>" needs to have a value for field "condition" before this many-to-many relationship can be used.
[22/Feb/2017 20:01:45] "POST /conditions/new/condition/ HTTP/1.1" 500 15799
traceback from #snakefcz 's answer
Internal Server Error: /conditions/new/condition/
Traceback (most recent call last):
File "/Library/Python/2.7/site-packages/django/core/handlers/exception.py", line 39, in inner
response = get_response(request)
File "/Library/Python/2.7/site-packages/django/core/handlers/base.py", line 187, in _get_response
response = self.process_exception_by_middleware(e, request)
File "/Library/Python/2.7/site-packages/django/core/handlers/base.py", line 185, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/Library/Python/2.7/site-packages/django/views/decorators/csrf.py", line 58, in wrapped_view
return view_func(*args, **kwargs)
File "/Library/Python/2.7/site-packages/django/views/generic/base.py", line 68, in view
return self.dispatch(request, *args, **kwargs)
File "/Library/Python/2.7/site-packages/rest_framework/views.py", line 477, in dispatch
response = self.handle_exception(exc)
File "/Library/Python/2.7/site-packages/rest_framework/views.py", line 437, in handle_exception
self.raise_uncaught_exception(exc)
File "/Library/Python/2.7/site-packages/rest_framework/views.py", line 474, in dispatch
response = handler(request, *args, **kwargs)
File "/Library/Python/2.7/site-packages/rest_framework/decorators.py", line 52, in handler
return func(*args, **kwargs)
File "/Users/user/medicalrecords/conditions/views.py", line 45, in create_condition
return response.Response(serializer.data, status=201)
File "/Library/Python/2.7/site-packages/rest_framework/serializers.py", line 527, in data
ret = super(Serializer, self).data
File "/Library/Python/2.7/site-packages/rest_framework/serializers.py", line 262, in data
self._data = self.to_representation(self.instance)
File "/Library/Python/2.7/site-packages/rest_framework/serializers.py", line 496, in to_representation
ret[field.field_name] = field.to_representation(attribute)
File "/Library/Python/2.7/site-packages/rest_framework/serializers.py", line 643, in to_representation
self.child.to_representation(item) for item in iterable
File "/Library/Python/2.7/site-packages/rest_framework/serializers.py", line 479, in to_representation
fields = self._readable_fields
File "/Library/Python/2.7/site-packages/django/utils/functional.py", line 35, in get
res = instance.dict[self.name] = self.func(instance)
File "/Library/Python/2.7/site-packages/rest_framework/serializers.py", line 373, in _readable_fields
field for field in self.fields.values()
File "/Library/Python/2.7/site-packages/rest_framework/serializers.py", line 359, in fields
for key, value in self.get_fields().items():
File "/Library/Python/2.7/site-packages/rest_framework/serializers.py", line 1010, in get_fields
fields[field_name] = field_class(**field_kwargs)
File "/Library/Python/2.7/site-packages/rest_framework/fields.py", line 733, in init
super(CharField, self).init(**kwargs)
TypeError: init() got an unexpected keyword argument 'view_name'
You'll need to create a Symptom serializer in addition to the Condition one. Your ConditionSerializer should look something like:
class ConditionSerializer(serializers.ModelSerializer):
symptoms = SymptomSerializer(read_only=True, many=True, allow_null=True)
class Meta:
model = Condition
fields = ('id', 'treatment', 'name', 'contagious', 'treatable', 'treatment', 'severeity', 'symptoms', 'medicalfield')
def create(self, validated_data):
attrs = validated_data
request = self.context['request']
return Condition.new.create_condition(**attrs)
## Try it
#api_view(['POST'])
#permission_classes((AllowAny, ))
def create_condition(request):
context = {'request': request}
serializer = ConditionSerializer(data=request.data, context=context)
if serializer.is_valid():
condition = serializer.save()
symptoms = request.data['symptoms']
for symp in symptoms:
symptom = Symptom.objects.get(id=symp) ## if it's id's you are passing
condition.symptoms.add(symptom)
return response.Response(serializer.data, status=201)
return response.Response(serializer.errors, status=400)