After using HttpResponseRedirect and reverse to redirect to another view, I am getting a ValueError. This is the view that processes a posted form (the form uses a ModelChoiceField to get a dropdown set of options from my Make model:
def browse(request):
thing_list = Thing.objects.all()
if request.method == 'POST':
form = BrowseForm(request.POST)
if form.is_valid():
make = form.cleaned_data['make']
return HttpResponseRedirect(reverse('browse_makes', kwargs={'make':make}))
else:
form = BrowseForm()
return render(request, 'browse.html', {'form':form, 'thing_list':thing_list})
.. then redirects to next view adding make as a kwarg to use to filter the next queryset:
def makes(request, make):
thing_list = Thing.objects.filter(make=make)
return render(request, 'browse-makes.html', {'thing_list':thing_list})
urls:
url(r'^browse/$', 'myapp.views.browse.browse', name='browse'),
url(r'^browse/(?P<make>[\w-]+)/$', 'myapp.views.browse.makes', name='browse_makes'),
Results in ValueError: invalid literal for int() with base 10: 'Samsung' when selecting an option from the form. After googling, still not sure how to solve this.. Thanks for any ideas how to solve this error!
EDIT:
abbreviated model:
class Thing(models.Model):
user = models.ForeignKey(User)
created_on = models.DateTimeField(auto_now_add=True)
updated_on = models.DateTimeField(auto_now=True)
slug = models.SlugField()
make = models.ForeignKey(Make)
Traceback:
Traceback: File "/lib/python2.7/django/core/handlers/base.py" in get_response
111. response = callback(request, *callback_args, **callback_kwargs) File "/myproject/myapp/views/browse.py" in makes
21. thing_list = Thing.objects.filter(make=make) File "/lib/python2.7/django/db/models/manager.py" in filter
143. return self.get_query_set().filter(*args, **kwargs) File "/lib/python2.7/django/db/models/query.py" in filter
624. return self._filter_or_exclude(False, *args, **kwargs) File "/lib/python2.7/django/db/models/query.py" in _filter_or_exclude
642. clone.query.add_q(Q(*args, **kwargs)) File "/lib/python2.7/django/db/models/sql/query.py" in add_q
1250. can_reuse=used_aliases, force_having=force_having) File "/lib/python2.7/django/db/models/sql/query.py" in add_filter
1185. connector) File "/lib/python2.7/django/db/models/sql/where.py" in add
69. value = obj.prepare(lookup_type, value) File "/lib/python2.7/django/db/models/sql/where.py" in prepare
320. return self.field.get_prep_lookup(lookup_type, value) File "/lib/python2.7/django/db/models/fields/related.py" in get_prep_lookup
137. return self._pk_trace(value, 'get_prep_lookup', lookup_type) File "/lib/python2.7/django/db/models/fields/related.py" in _pk_trace
210. v = getattr(field, prep_func)(lookup_type, v, **kwargs) File "/lib/python2.7/django/db/models/fields/__init__.py" in get_prep_lookup
310. return self.get_prep_value(value) File "/lib/python2.7/django/db/models/fields/__init__.py" in get_prep_value
537. return int(value)
Exception Type: ValueError at /browse/Samsung/ Exception Value: invalid literal for int() with base 10: 'Samsung'
If you post your Make model, I can give a complete answer. But in general you are referencing the make foreign key directly - which is an int (the Make ID). You are comparing this int to the string 'samsung' at make=make causing the error.
Depending on what string fields your Make model has, you need to reference one of those fields. For instance, if Make had a name field that accepted strings:
thing_list = Thing.objects.filter(make__name=make)
Otherwise, you need to pass the make ID instead of 'samsung'
Related
I am on django 4.0.4 and have a benign but annoying problem with the above error code.
Previous responses to similar questions don't help me.
When I backspace, (an incovenience a user may not think of) everything has actually gone well, the list and detail views are correctly updated.
The create form is however as it was as if it was not saved, and the view doesn't change to the detail view as suggested by the get_absolute_url, which may lead one to process it again.
The code from previous models is exactly the same where it matters. An example is the TaskCreate view which is giving the problem and the ObjectiveCreate view just before it which works as expected.
In the views, I find the user and his/her entity (even though there is one entity), and process that user as a supervisor1 and also automatically process the entity.
The error finds fault with the TaskCreate view's "return super().form_valid(form)" but not with that in the ObjectiveCreate view.
Here is the code for the two views
class ObjectiveCreate(LoginRequiredMixin, CreateView):
model = Objective
form_class = ObjectiveCreateForm
template_name = "internalcontrol/objective_create_form.html"
def form_valid(self, form):
user = self.request.user
profile = Profile.objects.get(user=user)
entity = profile.entity
new_profile = Profile.objects.get(user=user, entity=entity)
form.instance.supervisor1 = new_profile
form.instance.entity = entity
return super().form_valid(form)
def get_form_kwargs(self):
kwargs = super(ObjectiveCreate, self).get_form_kwargs()
kwargs["request"] = self.request
return kwargs
class TaskCreate(LoginRequiredMixin, CreateView):
model = Task
form_class = TaskCreateForm
template_name = "internalcontrol/task_create_form.html"
def form_valid(self, form):
user = self.request.user
profile = Profile.objects.get(user=user)
entity = profile.entity
new_profile = Profile.objects.get(user=user, entity=entity)
form.instance.supervisor1 = new_profile
form.instance.entity = entity
return super().form_valid(form)
def get_form_kwargs(self):
kwargs = super(TaskCreate, self).get_form_kwargs()
kwargs["request"] = self.request
return kwargs
The respective get_absolute_url for both models are:
def get_absolute_url(self):
return reverse(
"internalcontrol:objective_detail",
kwargs={"pk": self.pk},
)
and
def get_absolute_url(self):
return (
reverse("internalcontrol:task_detail", kwargs={"pk": self.pk}),
)
The traceback is as follows:
Internal Server Error: /task_create/
Traceback (most recent call last):
File "C:\Users\User\.virtualenvs\nguyena-QPBkFrkQ\lib\site-packages\django\core\handlers\exception.py", line 55, in inner
response = get_response(request)
File "C:\Users\User\.virtualenvs\nguyena-QPBkFrkQ\lib\site-packages\django\core\handlers\base.py", line 197, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\User\.virtualenvs\nguyena-QPBkFrkQ\lib\site-packages\django\views\generic\base.py", line 84, in view
return self.dispatch(request, *args, **kwargs)
File "C:\Users\User\.virtualenvs\nguyena-QPBkFrkQ\lib\site-packages\django\contrib\auth\mixins.py", line 73, in dispatch
return super().dispatch(request, *args, **kwargs)
File "C:\Users\User\.virtualenvs\nguyena-QPBkFrkQ\lib\site-packages\django\views\generic\base.py", line 119, in dispatch
return handler(request, *args, **kwargs)
File "C:\Users\User\.virtualenvs\nguyena-QPBkFrkQ\lib\site-packages\django\views\generic\edit.py", line 184, in post
return super().post(request, *args, **kwargs)
File "C:\Users\User\.virtualenvs\nguyena-QPBkFrkQ\lib\site-packages\django\views\generic\edit.py", line 153, in post
return self.form_valid(form)
File "C:\Users\User\Documents\django projects\nguyena\internalcontrol\views.py", line 231, in form_valid
return super().form_valid(form)
File "C:\Users\User\.virtualenvs\nguyena-QPBkFrkQ\lib\site-packages\django\views\generic\edit.py", line 136, in form_valid
return super().form_valid(form)
File "C:\Users\User\.virtualenvs\nguyena-QPBkFrkQ\lib\site-packages\django\views\generic\edit.py", line 65, in form_valid
return HttpResponseRedirect(self.get_success_url())
File "C:\Users\User\.virtualenvs\nguyena-QPBkFrkQ\lib\site-packages\django\http\response.py", line 538, in __init__
self["Location"] = iri_to_uri(redirect_to)
File "C:\Users\User\.virtualenvs\nguyena-QPBkFrkQ\lib\site-packages\django\utils\encoding.py", line 139, in iri_to_uri
return quote(iri, safe="/#%[]=:;$&()+,!?*#'~")
File "c:\users\user\appdata\local\programs\python\python39\lib\urllib\parse.py", line 871, in quote
return quote_from_bytes(string, safe)
File "c:\users\user\appdata\local\programs\python\python39\lib\urllib\parse.py", line 896, in quote_from_bytes
raise TypeError("quote_from_bytes() expected bytes")
TypeError: quote_from_bytes() expected bytes
[18/Apr/2022 17:08:13] "POST /task_create/ HTTP/1.1" 500 125026
I think the problem is the final address to which the user should be redirected.
To solve this problem, first edit the get_absolute_url function to return a string, not a tuple.
If it still does not work, try adding a success_url to the view with reverse_lazy
i have problem editing my queryset in Django REST framwork.
Basically i need to filter my query and return single one, so my DRF view look like this:
class MyModelViewSet(viewsets.ModelViewSet):
queryset = MyModel.objects.all()
serializer_class = MyModelSerializer
def get_queryset(self):
start = self.kwargs['start']
end = self.kwargs['end']
qs, created = MyModel.objects.get_or_create(start=start, end=end)
return qs
So i return single model instance, but when i try to get access true the DRF web interface i get an error 'MyModel' object has no attribute 'model'
Traceback:
File "/Users/stay-wide-awake/code/env/lib/python3.4/site-packages/django/core/handlers/base.py" in get_response
132. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/Users/stay-wide-awake/code/env/lib/python3.4/site-packages/django/views/decorators/csrf.py" in wrapped_view
58. return view_func(*args, **kwargs)
File "/Users/stay-wide-awake/code/env/lib/python3.4/site-packages/rest_framework/viewsets.py" in view
85. return self.dispatch(request, *args, **kwargs)
File "/Users/stay-wide-awake/code/env/lib/python3.4/site-packages/rest_framework/views.py" in dispatch
456. response = self.handle_exception(exc)
File "/Users/stay-wide-awake/code/env/lib/python3.4/site-packages/rest_framework/views.py" in dispatch
444. self.initial(request, *args, **kwargs)
File "/Users/stay-wide-awake/code/env/lib/python3.4/site-packages/rest_framework/views.py" in initial
359. self.check_permissions(request)
File "/Users/stay-wide-awake/code/env/lib/python3.4/site-packages/rest_framework/views.py" in check_permissions
304. if not permission.has_permission(request, self):
File "/Users/stay-wide-awake/code/asp/src/apps/api2/permission.py" in has_permission
34. perms = self.get_required_permissions(request.method, queryset.model)
Exception Type: AttributeError at /api/v2/geo/36.606111,-118.062778|36.578581,-120.291994/
Exception Value: 'MyModel' object has no attribute 'model'
Router and all other parts is OK (tested via prints :))
Will be grateful for any hints.
The object received via MyModel.objects.get_or_create(start=start, end=end) is not a queryset hence you are getting this error.
Django's get_or_create() returns a tuple of (object, created) where object is the retrieved or created object and created is a boolean specifying whether a new object was created.
In your get_queryset() method, you are setting queryset qs to this received object when infact its a model object.
get_queryset() should return a queryset and not a model object which you are doing.
You can do something like:
def get_queryset(self):
start = self.kwargs['start']
end = self.kwargs['end']
mymodel_obj, created = MyModel.objects.get_or_create(start=start, end=end)
return MyModel.objects.filter(id=mymodel_obj.id) # returns a queryset now
I'm getting a strange 500 error when issuing an OPTION request to an endpoint in my API built with Django Rest Framework. GET, POST, PUT all work fine and DELETE is not allowed.
When issuing an OPTION request to the endpoint, I get the following error and traceback:
Traceback:
File "/Users/awwester/Sites/django/rlg/lib/python3.4/site-packages/django/core/handlers/base.py" in get_response
111. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/Users/awwester/Sites/django/rlg/lib/python3.4/site-packages/django/views/decorators/csrf.py" in wrapped_view
57. return view_func(*args, **kwargs)
File "/Users/awwester/Sites/django/rlg/lib/python3.4/site-packages/rest_framework/viewsets.py" in view
85. return self.dispatch(request, *args, **kwargs)
File "/Users/awwester/Sites/django/rlg/lib/python3.4/site-packages/rest_framework/views.py" in dispatch
452. response = self.handle_exception(exc)
File "/Users/awwester/Sites/django/rlg/lib/python3.4/site-packages/rest_framework/views.py" in dispatch
449. response = handler(request, *args, **kwargs)
File "/Users/awwester/Sites/django/rlg/lib/python3.4/site-packages/rest_framework/views.py" in options
463. data = self.metadata_class().determine_metadata(request, self)
File "/Users/awwester/Sites/django/rlg/lib/python3.4/site-packages/rest_framework/metadata.py" in determine_metadata
63. actions = self.determine_actions(request, view)
File "/Users/awwester/Sites/django/rlg/lib/python3.4/site-packages/rest_framework/metadata.py" in determine_actions
89. actions[method] = self.get_serializer_info(serializer)
File "/Users/awwester/Sites/django/rlg/lib/python3.4/site-packages/rest_framework/metadata.py" in get_serializer_info
106. for field_name, field in serializer.fields.items()
File "/Users/awwester/Sites/django/rlg/lib/python3.4/site-packages/rest_framework/metadata.py" in <listcomp>
106. for field_name, field in serializer.fields.items()
File "/Users/awwester/Sites/django/rlg/lib/python3.4/site-packages/rest_framework/metadata.py" in get_field_info
129. if hasattr(field, 'choices'):
File "/Users/awwester/Sites/django/rlg/lib/python3.4/site-packages/rest_framework/relations.py" in choices
382. for item in iterable
Exception Type: TypeError at /v1/powerChatSessions
Exception Value: 'NoneType' object is not iterable
Here is the model, serializer, and view:
# models.py - error happens when issuing OPTIONS /powerChatSession
class VideoConversation(models.Model):
"""
Capture data about a video chat session
SO note: this is inherited by other classes besides PowerChat
"""
created = models.DateTimeField(auto_now_add=True)
end = models.DateTimeField(null=True, blank=True)
users = models.ManyToManyField(User)
class PowerChat(VideoConversation):
"""
power chat session
"""
start = models.DateTimeField(null=True, blank=True)
extended = models.BooleanField(default=False)
active = models.BooleanField(default=False)
# serializers.py
class PowerChatSerializer(serializers.ModelSerializer):
class Meta:
model = PowerChat
read_only_fields = ('users', 'start', 'extended',)
# views.py
class PowerChatViewSet(ModelViewSet):
queryset = PowerChat.objects.all()
permission_classes = (PowerChatPermission,)
serializer_class = PowerChatSerializer
resource_name = "powerChatSession"
Any ideas why this is happening? It has something to do with the users field, and it seems that it could be a bug with Django Rest Framework? It's checking if the field has the choices kwarg, which it doesn't, but apparently DRF thinks it does?
I think this issue was addressed by:
https://github.com/tomchristie/django-rest-framework/issues/3115
The gist is that "At the moment, self.action is None in viewsets if I get an OPTIONS request."
This issue ceased for me after I upgraded to djangorestframework-3.2.3
I am designing a simple MCQ application using the ManyToOne relationship from django website, django version 1.6.1. I have an inline admin form which supposedly allows me to add / edit answers to a given question from the same changeform. However, if after saving a question with its answers once, i am unable to edit / add answers from the same form and get a MultiValueDictKeyError. My models are:
class SBA (models.Model):
question = models.TextField(blank=False)
system = models.CharField(max_length=3, choices=pacscon.System.which_system)
case = models.ForeignKey('pacscon.Patient')
created = models.DateField(auto_now_add=True)
reference = models.TextField(blank=True)
def __unicode__(self):
return self.question
class Answer(models.Model):
id = models.AutoField(primary_key=True)
body = models.TextField()
correct = models.BooleanField(default=False)
sba = models.ForeignKey(SBA, null=True)
def __unicode__(self):
return self.body
the admin.py looks like this :
from models import Answer, SBA, Mnemonic
#from django import forms
from django.contrib import admin
class AnswerInline(admin.StackedInline):
model = Answer
extra = 2
class SBAAdmin(admin.ModelAdmin):
fieldsets = (
(None, {
'fields': ('question', 'system', 'case', 'reference')
}),
)
inlines = [
AnswerInline,
]
readonly_fields = ('created',)
admin.site.register(SBA, SBAAdmin)
admin.site.register(Answer)
admin.site.register(Mnemonic)
And the error message is :
MultiValueDictKeyError at /admin/knowledge/sba/1/
Traceback:
File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py" in get_response
114. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/usr/local/lib/python2.7/dist-packages/django/contrib/admin/options.py" in wrapper
432. return self.admin_site.admin_view(view)(*args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/django/utils/decorators.py" in _wrapped_view
99. response = view_func(request, *args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/django/views/decorators/cache.py" in _wrapped_view_func
52. response = view_func(request, *args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/django/contrib/admin/sites.py" in inner
198. return view(request, *args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/django/utils/decorators.py" in _wrapper
29. return bound_func(*args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/django/utils/decorators.py" in _wrapped_view
99. response = view_func(request, *args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/django/utils/decorators.py" in bound_func
25. return func(self, *args2, **kwargs2)
File "/usr/local/lib/python2.7/dist-packages/django/db/transaction.py" in inner
339. return func(*args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/django/contrib/admin/options.py" in change_view
1229. if all_valid(formsets) and form_validated:
File "/usr/local/lib/python2.7/dist-packages/django/forms/formsets.py" in all_valid
415. if not formset.is_valid():
File "/usr/local/lib/python2.7/dist-packages/django/forms/formsets.py" in is_valid
292. err = self.errors
File "/usr/local/lib/python2.7/dist-packages/django/forms/formsets.py" in errors
267. self.full_clean()
File "/usr/local/lib/python2.7/dist-packages/django/forms/formsets.py" in full_clean
314. form = self.forms[i]
File "/usr/local/lib/python2.7/dist-packages/django/utils/functional.py" in __get__
49. res = instance.__dict__[self.func.__name__] = self.func(instance)
File "/usr/local/lib/python2.7/dist-packages/django/forms/formsets.py" in forms
133. forms = [self._construct_form(i) for i in xrange(self.total_form_count())]
File "/usr/local/lib/python2.7/dist-packages/django/forms/models.py" in _construct_form
848. form = super(BaseInlineFormSet, self)._construct_form(i, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/django/forms/models.py" in _construct_form
564. pk = self.data[pk_key]
File "/usr/local/lib/python2.7/dist-packages/django/utils/datastructures.py" in __getitem__
301. raise MultiValueDictKeyError(repr(key))
Exception Type: MultiValueDictKeyError at /admin/knowledge/sba/1/
Exception Value: "u'answer_set-0-id'"
I have searched similar requests on google and stackoverflow and my django package is fully upto date (including admin inline templates as suggested in some other answers). Will appreciate any help. Thanks
P.S This is almost certainly a bug because I can replicate the problem on official django "Polls" tutorial which uses a similar ManyToOne relationship model.
In Django <= 1.7.3, I needed to change the primary key field of my model to AutoField:
wrong:
class Answer(models.Model):
id = IntegerField(primary_key=True)
correct:
class Answer(models.Model):
id = AutoField(primary_key=True)
See
https://code.djangoproject.com/ticket/15665
I have similar issue which was solved by update django-grappelli. If you did not use it, check your packages maybe you find what can affect work of admin site.
pip freeze | grep django- will show you current packages with versions
This answer https://stackoverflow.com/a/20246225/554807 has the explanation.
The best fix is actually to get silverfix's branch of nested-inlines: https://github.com/silverfix/django-nested-inlines
This has the fix mentioned in that answer, and others.
After migrating an application from Django==1.4.20 to Django==1.8.3 i had an outdated templates_django/admin/edit_inline/stacked.html and templates_django/admin/edit_inline/tabular.html files.
So i have just removed them and everything works fine now.
You can also upgrade them to your current django version instead of deleting.
I am making a post via jquery to my backend. I first look to see if a pledge has already been made. If not, I create one.
#csrf_exempt
def pledgeReceive(request):
fname = request.POST.get('fname', '')
lname = request.POST.get('lname', '')
participantName = request.POST.get('participantName', '')
participantID = request.POST.get('participantID', '')
ppl = request.POST.get('ppl', '')
maxi = request.POST.get('maxi', '')
sponsor = fname + ' ' + lname
participant_obj = Participant.objects.get(pk = participantID)
try:
pledge = Pledge.objects.get(sponsor = sponsor, participant = participant_obj, pledge_amount = ppl, max_pledge_amount = maxi, datetime = datetime.now())
except Pledge.DoesNotExist:
pledge = Pledge(sponsor = sponsor, participant = participant_obj, pledge_amount = ppl, max_pledge_amount = maxi, datetime = datetime.now())
pledge.save()
response = HttpResponse()
response.content = serialized_obj = serializers.serialize('json', [ pledge, ])
response['Content-Type'] = 'application/json'
return response
I get a 500 internal server error. With the following traceback:
ValidationError at /pledgeReceive/
No exception supplied
Traceback:
File "/home/vtrelayc/lib/python2.6/site-packages/django/core/handlers/base.py" in get_response
111. response = callback(request, *callback_args, **callback_kwargs)
File "/home/vtrelayc/lib/python2.6/site-packages/django/views/decorators/csrf.py" in wrapped_view
77. return view_func(*args, **kwargs)
File "/home/vtrelayc/projects/relay/relayapp/views.py" in pledgeReceive
461. pledge.save()
File "/home/vtrelayc/lib/python2.6/site-packages/django/db/models/base.py" in save
463. self.save_base(using=using, force_insert=force_insert, force_update=force_update)
File "/home/vtrelayc/lib/python2.6/site-packages/django/db/models/base.py" in save_base
551. result = manager._insert([self], fields=fields, return_id=update_pk, using=using, raw=raw)
File "/home/vtrelayc/lib/python2.6/site-packages/django/db/models/manager.py" in _insert
203. return insert_query(self.model, objs, fields, **kwargs)
File "/home/vtrelayc/lib/python2.6/site-packages/django/db/models/query.py" in insert_query
1593. return query.get_compiler(using=using).execute_sql(return_id)
File "/home/vtrelayc/lib/python2.6/site-packages/django/db/models/sql/compiler.py" in execute_sql
911. for sql, params in self.as_sql():
File "/home/vtrelayc/lib/python2.6/site-packages/django/db/models/sql/compiler.py" in as_sql
872. for obj in self.query.objs
File "/home/vtrelayc/lib/python2.6/site-packages/django/db/models/fields/__init__.py" in get_db_prep_save
873. return connection.ops.value_to_db_decimal(self.to_python(value),
File "/home/vtrelayc/lib/python2.6/site-packages/django/db/models/fields/__init__.py" in to_python
850. raise exceptions.ValidationError(msg)
Exception Type: ValidationError at /pledgeReceive/
I am providing an exception though with except Pledge.DoesNotExist:?
Why not just use get_or_create? It is a shortcut for what you are attempting to do.
pledge, created = Pledge.objects.get_or_create(sponsor = sponsor, participant = participant_obj, pledge_amount = ppl, max_pledge_amount = maxi, datetime = datetime.now())
Now you have a pledge object and a boolean, created, that lets you know whether the object was created or fetched.
Other than that, the error is probably caused by the fact that you are just getting the GET parameters without casting them to the types that your Pledge object expects. They are getting passed as strings even though most of your fields probably aren't expecting strings. Maybe use a form (for it's built in validation/type casting) or manually convert your GET parameters to the correct types.
ValidationError exception is raised when data fails form or model field validation but because your not using form.is_valid() or any validator which validate your input values this will result to No Exception Supplied. Even your Pledge.DoesNotExist cannot catch the error because it's only check when an object is not found for the given parameters of a query.
Based on your code, I found invalid values.
ppl = request.POST.get('ppl', '')
maxi = request.POST.get('maxi', '')
If I'm not wrong the code above pass an integer. But you didn't know your passing a string not an int. It must be,
ppl = int(request.POST.get('ppl', 0))
maxi = int(request.POST.get('maxi', 0))
I don't know your model code pattern, if your passing a value for foreignkey or date your must also check that because they are very sensitive. You don't have to worry about CharField because they can handle it unless if required. But I suggest you use form, if you can't handle this error.