Django UUIDField issue - python

I am trying to get the UUIDField to work in python django using the following model:
class Ticket(models.Model):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
name = models.CharField(max_length=50)
However when I try adding an instance of the model to the database it returns the following error:
TypeError at /tickets/
coercing to Unicode: need string or buffer, UUID found
The documentation of UUIDField is really short and doesn't really help me.
edit: I did import uuid and here is the full traceback:
Environment:
Request Method: GET
Request URL: http://127.0.0.1:8000/tickets/
Django Version: 1.8.5
Python Version: 2.7.9
Installed Applications:
('django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'events',
'rest_framework')
Installed Middleware:
('django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'django.middleware.security.SecurityMiddleware')
Traceback:
File "/Users/daviddejong/.virtualenvs/restDemo/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response
132. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/Users/daviddejong/.virtualenvs/restDemo/lib/python2.7/site-packages/django/views/decorators/csrf.py" in wrapped_view
58. return view_func(*args, **kwargs)
File "/Users/daviddejong/.virtualenvs/restDemo/lib/python2.7/site-packages/rest_framework/viewsets.py" in view
87. return self.dispatch(request, *args, **kwargs)
File "/Users/daviddejong/.virtualenvs/restDemo/lib/python2.7/site-packages/rest_framework/views.py" in dispatch
466. response = self.handle_exception(exc)
File "/Users/daviddejong/.virtualenvs/restDemo/lib/python2.7/site-packages/rest_framework/views.py" in dispatch
463. response = handler(request, *args, **kwargs)
File "/Users/daviddejong/.virtualenvs/restDemo/lib/python2.7/site-packages/rest_framework/mixins.py" in list
48. return Response(serializer.data)
File "/Users/daviddejong/.virtualenvs/restDemo/lib/python2.7/site-packages/rest_framework/serializers.py" in data
663. ret = super(ListSerializer, self).data
File "/Users/daviddejong/.virtualenvs/restDemo/lib/python2.7/site-packages/rest_framework/serializers.py" in data
228. self._data = self.to_representation(self.instance)
File "/Users/daviddejong/.virtualenvs/restDemo/lib/python2.7/site-packages/rest_framework/serializers.py" in to_representation
603. self.child.to_representation(item) for item in iterable
File "/Users/daviddejong/.virtualenvs/restDemo/lib/python2.7/site-packages/rest_framework/serializers.py" in to_representation
461. ret[field.field_name] = field.to_representation(attribute)
File "/Users/daviddejong/.virtualenvs/restDemo/lib/python2.7/site-packages/rest_framework/relations.py" in to_representation
356. name = self.get_name(value)
File "/Users/daviddejong/.virtualenvs/restDemo/lib/python2.7/site-packages/rest_framework/relations.py" in get_name
276. return six.text_type(obj)
Exception Type: TypeError at /tickets/
Exception Value: coercing to Unicode: need string or buffer, UUID found
Edit 2: My serializer looks like this:
class TicketSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Ticket
fields = ('url', 'id', 'name')
Edit 3:
I found the error. I made a mistake in my model. My unicode looked like this:
def __unicode__(self):
return self.id
And of course this does not work.

Probably you should use something like this:
def __unicode__(self):
return str(self.id)

Related

Django: writing text from uploaded file to text field

I have the following model:
class Clean(models.Model):
name = models.CharField(max_length=100)
cv = models.TextField(max_length=10000)
cvfile = models.FileField()
I am trying to write the contents of cvfile to cv when the user submits the name and file from the form. I'm sure this can be done as the file and text field will be in the same object. The file will always be .txt so I assume a simple .read() can be performed.
Should I have a function that the form calls to perform this? If so how can this be done?
def writeCV(self):
get_text = cvfile.open().read()
#write to cv field somehow
return self.cv
I am using django 1.9
Traceback from Messaoud's answer:
Environment:
Request Method: POST
Request URL: http://127.0.0.1:8000/cleaner/clean/add/
Django Version: 1.9
Python Version: 3.6.4
Installed Applications:
['cleaner.apps.CleanerConfig',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles']
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.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware']
Traceback:
File "C:\Python\Python36-32\lib\site-packages\django\core\handlers\base.py" in get_response
149. response = self.process_exception_by_middleware(e, request)
File "C:\Python\Python36-32\lib\site-packages\django\core\handlers\base.py" in get_response
147. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Python\Python36-32\lib\site-packages\django\views\generic\base.py" in view
68. return self.dispatch(request, *args, **kwargs)
File "C:\Python\Python36-32\lib\site-packages\django\views\generic\base.py" in dispatch
88. return handler(request, *args, **kwargs)
File "C:\Python\Python36-32\lib\site-packages\django\views\generic\edit.py" in post
255. return super(BaseCreateView, self).post(request, *args, **kwargs)
File "C:\Python\Python36-32\lib\site-packages\django\views\generic\edit.py" in post
221. return self.form_valid(form)
File "C:\Python\Python36-32\lib\site-packages\django\views\generic\edit.py" in form_valid
200. self.object = form.save()
File "C:\Python\Python36-32\lib\site-packages\django\forms\models.py" in save
451. self.instance.save()
File "C:\Users\barry\Desktop\College\Year 4\Semester 2\cvCleaner\cvcleaner\cleaner\models.py" in save
11. get_text = self.cvfile.open().read()
Exception Type: AttributeError at /cleaner/clean/add/
Exception Value: 'NoneType' object has no attribute 'read'
You can do this by overriding save method in your Model
class Clean(models.Model):
name = models.CharField(max_length=100)
cv = models.TextField(max_length=10000, blank = True, null = True)
cvfile = models.FileField()
def save(self, *args, **kwargs):
get_text = self.cvfile.open().read()
self.cv = get_text
super(Clean, self).save(*args, **kwargs) # Call the "real" save() method.
Or by Using post_save signal
def writeCV(sender, instance, **kwargs):
get_text = instance.cvfile.open().read()
instance.cv = get_text
instance.save()
post_save.connect(writeCV, sender=Clean)

Error while serializing queryset object in Django Rest Framework

I am trying to serialize my queryset object and getting error as below,
Exception Type: AttributeError
Exception Value:
Got AttributeError when attempting to get a value for field `fullName` on serializer `UserSerializer`.
The serializer field might be named incorrectly and not match any attribute or key on the `QuerySet` instance.
Original exception text was: 'QuerySet' object has no attribute 'fullName'.
Traceback
Environment:
Request Method: POST
Request URL: http://127.0.0.1:8000/user/crud/
Django Version: 1.9
Python Version: 2.7.10
Installed Applications:
['rest_framework',
'background_task',
'userApp',
'imageUpload',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles']
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.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware']
Traceback:
File "C:\Users\JpG\Desktop\herokuEnv\lib\site-packages\django\core\handlers\base.py" in get_response
149. response = self.process_exception_by_middleware(e, request)
File "C:\Users\JpG\Desktop\herokuEnv\lib\site-packages\django\core\handlers\base.py" in get_response
147. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\JpG\Desktop\herokuEnv\lib\site-packages\django\views\decorators\csrf.py" in wrapped_view
58. return view_func(*args, **kwargs)
File "C:\Users\JpG\Desktop\herokuEnv\lib\site-packages\rest_framework\viewsets.py" in view
87. return self.dispatch(request, *args, **kwargs)
File "C:\Users\JpG\Desktop\herokuEnv\lib\site-packages\rest_framework\views.py" in dispatch
466. response = self.handle_exception(exc)
File "C:\Users\JpG\Desktop\herokuEnv\lib\site-packages\rest_framework\views.py" in dispatch
463. response = handler(request, *args, **kwargs)
File "C:\Users\JpG\Desktop\CYC_Heroku\userApp\views.py" in create
24. return Response(data=serializer.data) # {"detail": "Mobile Number already exist"})
File "C:\Users\JpG\Desktop\herokuEnv\lib\site-packages\rest_framework\serializers.py" in data
503. ret = super(Serializer, self).data
File "C:\Users\JpG\Desktop\herokuEnv\lib\site-packages\rest_framework\serializers.py" in data
239. self._data = self.to_representation(self.instance)
File "C:\Users\JpG\Desktop\herokuEnv\lib\site-packages\rest_framework\serializers.py" in to_representation
463. attribute = field.get_attribute(instance)
File "C:\Users\JpG\Desktop\herokuEnv\lib\site-packages\rest_framework\fields.py" in get_attribute
422. raise type(exc)(msg)
Exception Type: AttributeError at /user/crud/
Exception Value: Got AttributeError when attempting to get a value for field `fullName` on serializer `UserSerializer`.
The serializer field might be named incorrectly and not match any attribute or key on the `QuerySet` instance.
Original exception text was: 'QuerySet' object has no attribute 'fullName'.
I'm including some code snippet here .
views.py
class UserView(viewsets.ModelViewSet):
queryset = UserModel.objects.all()
serializer_class = UserSerializer
def create(self, request, *args, **kwargs):
mobNum = request.data.get('mobileNum')
if UserModel.objects.filter(mobileNum=mobNum).exists():
serializer=UserSerializer(UserModel.objects.filter(mobileNum=mobNum))
return Response(data=serializer.data)
serializer.py
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = UserModel
fields = '__all__'
models.py
class UserModel(models.Model):
fullName = models.CharField(max_length=100)
mobileNum = models.CharField(max_length=12)
isAuthority = models.BooleanField(default=False)
My sample Input
Actually, I am expecting an output similar to the output of below code
class UserView(viewsets.ModelViewSet):
queryset = UserModel.objects.all()
serializer_class = UserSerializer
def create(self, request, *args, **kwargs):
serializer = self.get_serializer(data=request.data)
if serializer.is_valid():
serializer.save()
return Response(data=serializer.data)
try get() instead of filter()
That is, serializer=UserSerializer(UserModel.objects.get(mobileNum=mobNum))
Full views.py
class UserView(viewsets.ModelViewSet):
queryset = UserModel.objects.all()
serializer_class = UserSerializer
def create(self, request, *args, **kwargs):
mobNum = request.data.get('mobileNum')
if UserModel.objects.filter(mobileNum=mobNum).exists():
serializer=UserSerializer(UserModel.objects.get(mobileNum=mobNum))
return Response(data=serializer.data)

ValueError with Django form initial

I'm building a reservation app with Django and I want to allow users to use one reservation as template for another. My idea is that I add ?prefill=<reservation_id> to url and then prefill empty form with data from reservation in prefill id.
My CreateView looks like this:
class ReservationCreateView(LoginRequiredMixin, CreateUpdateMixin, CreateView):
model = Reservation
form_class = ReservationForm
success_url = '/'
def get_context_data(self, **kwargs):
ctx = super(ReservationCreateView, self).get_context_data()
r = Reservation.objects.filter(pk=self.request.GET.get('prefill'))
ctx['form'] = ReservationForm(initial=r.values(), request=self.request)
return ctx
This gives me: dictionary update sequence element #0 has length 30; 2 is required
Error stack:
Environment:
Request Method: GET
Request URL: http://localhost:8000/r/create/?prefill=56cc36bd-c766-4e45-8a1b-cdde3cd87dc4
Django Version: 1.10.3
Python Version: 2.7.10
Installed Applications:
['django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.humanize',
'tags',
'profiles',
'reservations',
'drivers',
'import_export',
'src',
'crispy_forms',
'rest_framework',
'rest_framework.authtoken',
'corsheaders',
'anymail',
'wf',
'storages',
'djangoformsetjs']
Installed Middleware:
['corsheaders.middleware.CorsMiddleware',
'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',
'htmlmin.middleware.HtmlMinifyMiddleware',
'htmlmin.middleware.MarkRequestMiddleware']
Traceback:
File "/Users/jhotujec/Documents/projects/optilimo/venv/lib/python2.7/site-packages/django/core/handlers/exception.py" in inner
39. response = get_response(request)
File "/Users/jhotujec/Documents/projects/optilimo/venv/lib/python2.7/site-packages/django/core/handlers/base.py" in _get_response
187. response = self.process_exception_by_middleware(e, request)
File "/Users/jhotujec/Documents/projects/optilimo/venv/lib/python2.7/site-packages/django/core/handlers/base.py" in _get_response
185. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/Users/jhotujec/Documents/projects/optilimo/venv/lib/python2.7/site-packages/django/views/generic/base.py" in view
68. return self.dispatch(request, *args, **kwargs)
File "/Users/jhotujec/Documents/projects/optilimo/venv/lib/python2.7/site-packages/django/contrib/auth/mixins.py" in dispatch
56. return super(LoginRequiredMixin, self).dispatch(request, *args, **kwargs)
File "/Users/jhotujec/Documents/projects/optilimo/venv/lib/python2.7/site-packages/django/views/generic/base.py" in dispatch
88. return handler(request, *args, **kwargs)
File "/Users/jhotujec/Documents/projects/optilimo/reservations/mixins.py" in get
68. route_formset=route_formset))
File "/Users/jhotujec/Documents/projects/optilimo/reservations/views.py" in get_context_data
108. ctx['form'] = ReservationForm(initial=r.values(), request=self.request)
File "/Users/jhotujec/Documents/projects/optilimo/reservations/forms.py" in __init__
30. super(ReservationForm, self).__init__(*args, **kwargs)
File "/Users/jhotujec/Documents/projects/optilimo/venv/lib/python2.7/site-packages/django/forms/models.py" in __init__
285. object_data.update(initial)
Exception Type: ValueError at /r/create/
Exception Value: dictionary update sequence element #0 has length 30; 2 is required
filter() always returns a queryset, and values() is then basically a list of dicts, whereas the form is expecting a single dict.
You could fix this by using r.values()[0] instead, but this is really the wrong approach. This is a model form; you should populate it by passing an actual model instance as the instance argument.
The problem is initial=r.values() where r is a QuerySet. values returns a list of dicts, initial expects a dict. You could get the Reservation instance and use the instance parameter of the form constructor instead:
# first() will return None if the QS is empty
r = Reservation.objects.get(pk=self.request.GET.get('prefill')).first()
ctx['form'] = ReservationForm(instance=r, request=self.request)

In DRF(django-rest-framework), AttributeError 'str' object has no attribute '~~' How to solve it?

I'm using DRF and be front of AttributeError 'str' object has no attribute '~~'.
my error page and code
Environment:
Request Method: GET
Request URL: http://127.0.0.1:8000/blog/
Django Version: 1.9.7
Python Version: 3.5.2
Installed Applications:
['django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.gis',
'blog',
'account',
'taggit',
'friendship',
'rest_framework']
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.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware']
Traceback:
File "/home/keepair/djangogirls/myvenv/lib/python3.5/site-packages/django/core/handlers/base.py" in get_response
149. response = self.process_exception_by_middleware(e, request)
File "/home/keepair/djangogirls/myvenv/lib/python3.5/site-packages/django/core/handlers/base.py" in get_response
147. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/keepair/djangogirls/myvenv/lib/python3.5/site-packages/django/views/decorators/csrf.py" in wrapped_view
58. return view_func(*args, **kwargs)
File "/home/keepair/djangogirls/myvenv/lib/python3.5/site-packages/django/views/generic/base.py" in view
68. return self.dispatch(request, *args, **kwargs)
File "/home/keepair/djangogirls/myvenv/lib/python3.5/site-packages/rest_framework/views.py" in dispatch
466. response = self.handle_exception(exc)
File "/home/keepair/djangogirls/myvenv/lib/python3.5/site-packages/rest_framework/views.py" in dispatch
463. response = handler(request, *args, **kwargs)
File "/home/keepair/djangogirls/myvenv/lib/python3.5/site-packages/rest_framework/decorators.py" in handler
52. return func(*args, **kwargs)
File "/home/keepair/djangogirls/blog/views.py" in post_list
37. return Response(serializer.data)
File "/home/keepair/djangogirls/myvenv/lib/python3.5/site-packages/rest_framework/serializers.py" in data
700. ret = super(ListSerializer, self).data
File "/home/keepair/djangogirls/myvenv/lib/python3.5/site-packages/rest_framework/serializers.py" in data
239. self._data = self.to_representation(self.instance)
File "/home/keepair/djangogirls/myvenv/lib/python3.5/site-packages/rest_framework/serializers.py" in to_representation
618. self.child.to_representation(item) for item in iterable
File "/home/keepair/djangogirls/myvenv/lib/python3.5/site-packages/rest_framework/serializers.py" in <listcomp>
618. self.child.to_representation(item) for item in iterable
File "/home/keepair/djangogirls/myvenv/lib/python3.5/site-packages/rest_framework/serializers.py" in to_representation
463. attribute = field.get_attribute(instance)
File "/home/keepair/djangogirls/myvenv/lib/python3.5/site-packages/rest_framework/relations.py" in get_attribute
157. return get_attribute(instance, self.source_attrs)
File "/home/keepair/djangogirls/myvenv/lib/python3.5/site-packages/rest_framework/fields.py" in get_attribute
83. instance = getattr(instance, attr)
Exception Type: AttributeError at /blog/
Exception Value: 'str' object has no attribute 'author'
I wonder how to make serializers.py codes.
I already studied : http://www.django-rest-framework.org/api-guide/relations/
But I don't understand what I should do. Where should I put serializers.py?
And how to make my serializers code? Or maybe models.ForienKey is unavailable on using DRF?
blog/views.py
#api_view(['GET'])
def post_list(request, format=None):
"""
List all snippets, or create a new snippet.
"""
if request.method == 'GET':
lat = request.POST.get('user_lat', '13')
lon = request.POST.get('user_lon', '15')
userpoint = GEOSGeometry('POINT(' + lat + ' ' + lon + ')', srid=4326)
i=1
while i:
list_i = Post.objects.filter(point__distance_lte = (userpoint, D(km=i)))
list_total = str(',' + ' list_i')
post_list = list(chain(list_total))
if len(post_list) >= 0 :
break
serializer = PostSerializer(post_list, many=True)
return Response(serializer.data)
This has nothing to do with your serializer, or where you put it. The error traceback is telling you that the error happens in the view.
So, in your post_list view, you build up a list (also called post_list) which is populated by a list of strings. Then you try and put it through the PostSerializer, which of course is expecting a queryset of Posts.
I'm not sure what the point of the list is; seems like you should be passing the Posts directly to the serializer.

get_or_create not creating object from POST form

Trying to create an object with get_or_create(). The response hits, but it never successfully creates the object.
Python code:
class Note(models.Model):
user = models.ForeignKey(User)
topic = models.CharField(max_length=500, null=True, blank=True)
created = models.DateTimeField(auto_now_add=True)
content = models.TextField(null=True, blank=True)
type = models.ForeignKey(NoteType, null=True, blank=True)
def __unicode__(self):
return self.topic
def post(request):
topic = request.POST['topic']
user = request.user
content = request.POST['content']
note_type = request.POST['type']
note, created = Note.objects.get_or_create(user=user, topic=topic, content=content, type=note_type)
return HttpResponseRedirect('/home/')
So the exception constantly hits and never creates the object. Urls are fine and I'm importing the model. Any reason why this object isn't being created? Theres no errors, it just redirects as normal.
traceback:
Environment:
Request Method: POST
Request URL: http://localhost:8000/post/
Django Version: 1.5.1
Python Version: 2.7.5
Installed Applications:
('django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.admin',
'django.contrib.admindocs',
'notes')
Installed Middleware:
('django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware')
Traceback:
File "c:\Python27\lib\site-packages\django\core\handlers\base.py" in get_response
115. response = callback(request, *callback_args, **callback_kwargs)
File "c:\Python27\lib\site-packages\django\contrib\auth\decorators.py" in _wrapped_view
25. return view_func(request, *args, **kwargs)
File "c:\Users\Alana\project-fridge\notes\views.py" in post_note
34. note, created = Note.objects.get_or_create(user=user, topic=topic, content=content, type=note_type)
File "c:\Python27\lib\site-packages\django\db\models\manager.py" in get_or_create
146. return self.get_query_set().get_or_create(**kwargs)
File "c:\Python27\lib\site-packages\django\db\models\query.py" in get_or_create
470. return self.get(**lookup), False
File "c:\Python27\lib\site-packages\django\db\models\query.py" in get
379. clone = self.filter(*args, **kwargs)
File "c:\Python27\lib\site-packages\django\db\models\query.py" in filter
655. return self._filter_or_exclude(False, *args, **kwargs)
File "c:\Python27\lib\site-packages\django\db\models\query.py" in _filter_or_exclude
673. clone.query.add_q(Q(*args, **kwargs))
File "c:\Python27\lib\site-packages\django\db\models\sql\query.py" in add_q
1266. can_reuse=used_aliases, force_having=force_having)
File "c:\Python27\lib\site-packages\django\db\models\sql\query.py" in add_filter
1197. connector)
File "c:\Python27\lib\site-packages\django\db\models\sql\where.py" in add
71. value = obj.prepare(lookup_type, value)
File "c:\Python27\lib\site-packages\django\db\models\sql\where.py" in prepare
339. return self.field.get_prep_lookup(lookup_type, value)
File "c:\Python27\lib\site-packages\django\db\models\fields\related.py" in get_prep_lookup
143. return self._pk_trace(value, 'get_prep_lookup', lookup_type)
File "c:\Python27\lib\site-packages\django\db\models\fields\related.py" in _pk_trace
216. v = getattr(field, prep_func)(lookup_type, v, **kwargs)
File "c:\Python27\lib\site-packages\django\db\models\fields\__init__.py" in get_prep_lookup
322. return self.get_prep_value(value)
File "c:\Python27\lib\site-packages\django\db\models\fields\__init__.py" in get_prep_value
555. return int(value)
Exception Type: ValueError at /post/
Exception Value: invalid literal for int() with base 10: 'text'
Thank you for your help in advance.
I assume that you are storing a list of various Note Types in the NoteType model...
To make this code work, you are first going to need to get one of them from that model and then set use that when creating your new note
note_type = request.POST['type']
note_type_orm = NoteType.objects.get(type=note_type)
note, created = Note.objects.get_or_create(user=user, topic=topic, content=content, type=note_type_orm)
Notice the change in the get_or_create that I am now using the note_type_orm and not just the note_type (which is just a string)

Categories

Resources