I'm trying to get the author of each post, so I've written this function in the views.py folder that allows you to add a post, except when I introduce post_form = poster I get errors
NOT NULL constraint failed: blog_post.author_id
Here is the addPost function:
def addPost(request):
context = RequestContext(request)
postAdded = False
poster = request.user
if request.method == 'POST':
post_form = PostForm(data=request.POST)
if post_form.is_valid():
postAdded = True
post_form.author = poster
post_form.save()
else:
print(post_form.errors)
else:
post_form = PostForm()
return render_to_response(
'Forum/addPost.html',
{'post_form': post_form, 'postAdded': postAdded},
context)
and here are the relevant models:
class UserProfile(models.Model):
user = models.OneToOneField(User)
class Post(models.Model):
author = models.ForeignKey(User, related_name='poster')
class PostForm(forms.ModelForm):
class Meta:
# Provide an association between the ModelForm and a model
newPost = Post
# newPost.category = check which url we are in
model = newPost
fields = ('title', 'body', 'category')
Thanks to all
Here is the error:
NOT NULL constraint failed: blog_post.author_id
Traceback:
File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/django/core/handlers/base.py" in get_response
111. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/Users/nicolasanastassacos/Desktop/DjangoProject/blog/views.py" in addPost
80. post_form.save()
File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/django/forms/models.py" in save
457. construct=False)
File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/django/forms/models.py" in save_instance
103. instance.save()
File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/django/db/models/base.py" in save
590. force_update=force_update, update_fields=update_fields)
File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/django/db/models/base.py" in save_base
618. updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields)
File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/django/db/models/base.py" in _save_table
699. result = self._do_insert(cls._base_manager, using, fields, update_pk, raw)
File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/django/db/models/base.py" in _do_insert
732. using=using, raw=raw)
File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/django/db/models/manager.py" in manager_method
92. return getattr(self.get_queryset(), name)(*args, **kwargs)
File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/django/db/models/query.py" in _insert
921. return query.get_compiler(using=using).execute_sql(return_id)
File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/django/db/models/sql/compiler.py" in execute_sql
920. cursor.execute(sql, params)
File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/django/db/backends/utils.py" in execute
81. return super(CursorDebugWrapper, self).execute(sql, params)
File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/django/db/backends/utils.py" in execute
65. return self.cursor.execute(sql, params)
File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/django/db/utils.py" in __exit__
94. six.reraise(dj_exc_type, dj_exc_value, traceback)
File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/django/utils/six.py" in reraise
549. raise value.with_traceback(tb)
File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/django/db/backends/utils.py" in execute
65. return self.cursor.execute(sql, params)
File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/django/db/backends/sqlite3/base.py" in execute
485. return Database.Cursor.execute(self, query, params)
Exception Type: IntegrityError at /Forum/addPost/
Exception Value: NOT NULL constraint failed: blog_post.author_id
I think that you need to something like that to avoid your error:
if post_form.is_valid():
new_post = post_form.save(commit=False)
new_post.author = poster
new_post.save()
I think your issue is at your author instance. You are trying to create a form, setting it the values, adding it an author and saving it.
First, the form does not have an author field, you are excluding it with the line:
fields = ('title', 'body', 'category')
Try something like this:
if post_form.is_valid():
postAdded = True
instance = post_form.save(commit=False)
instance.author = poster
instance.save()
That way you are not setting a NULL value to your author field.
Related
Tried to write custom create method for my model, but run into some unclear errors.
Here is my code:
# models.py:
class ItemModel(models.Model):
item_id = models.CharField(max_length=10, primary_key=True)
name = models.CharField(max_length=40)
active = models.BooleanField(default=True)
def __str__(self):
return self.item_id
class ItemVersion(models.Model):
item_ver_id = models.CharField(max_length=13, primary_key=True)
item_ver = models.TextField()
config = models.TextField()
model = models.ForeignKey(ItemModel, on_delete=models.CASCADE, default=0)
session_id = models.CharField(max_length=40, default=0)
creation_date = models.DateTimeField(auto_now=False, auto_now_add=True)
finished = models.BooleanField(default=False)
def name(self):
return self.model.name
def __str__(self):
return str(self.model)
# serializers.py:
class ItemModelSerializer(serializers.ModelSerializer):
item_id = serializers.RegexField(regex='^\d{3}-\d{9}$', allow_blank=False)
name = serializers.CharField(min_length=6, max_length=50, allow_blank=False)
class Meta:
model = ItemModel
fields = '__all__'
class ItemVersionSerializer(serializers.ModelSerializer):
item_ver_id = serializers.RegexField(regex='^r\d{2}$', allow_blank=False)
session_id = serializers.RegexField(regex='^s\d{2}$', allow_blank=False)
link = serializers.SerializerMethodField()
name = serializers.SerializerMethodField()
config = serializers.CharField(min_length=6)
item_ver = serializers.CharField(min_length=6)
def get_name(self, obj):
return obj.name()
def get_link(self, obj):
link = 'https://example.net/' + str(obj.model)
+ str('-dyn') + '/?iv_id=' + str(obj.item_ver_id)
+ '&sessid=' + str(obj.session_id)
return link
# views.py:
class ItemModelViewSet(viewsets.ModelViewSet):
queryset = ItemModel.objects.all()
serializer_class = ItemModelSerializer
lookup_field = 'item_id'
class ItemVersionViewSet(viewsets.ModelViewSet):
serializer_class = ItemVersionSerializer
lookup_field = 'item_ver_id'
def get_queryset(self):
pass
def create(self, request, *args, **kwargs):
data = request.data
model = ItemModel.objects.get(item_id=data["model"])
item_version = ItemVersion.objects.create(
# model=model,
item_ver_id=data["item_ver_id"],
config=data["config"],
item_ver=data["item_ver"],
session_id=data["session_id"]
# finished=data["finished"]
)
item_version.model.add(model)
finished = True if data["finished"] else False
item_version.finished.add(finished)
item_version.save()
serializer = ItemVersionSerializer(item_version)
return Response(data)
For some reason, I keep getting FOREIGN KEY constraint failed and the session_id=data["session_id"] line is highlighted as the one where problem occurs nearby.
Any ideas how to solve this?
Edit: traceback:
Traceback (most recent call last):
File "/home/aqv/workspace/django_rest_fw/ct_test/environ/lib/python3.6/site-packages/django/db/backends/utils.py", line 84, in _execute
return self.cursor.execute(sql, params)
File "/home/aqv/workspace/django_rest_fw/ct_test/environ/lib/python3.6/site-packages/django/db/backends/sqlite3/base.py", line 383, in execute
return Database.Cursor.execute(self, query, params)
sqlite3.IntegrityError: FOREIGN KEY constraint failed
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/aqv/workspace/django_rest_fw/ct_test/environ/lib/python3.6/site-packages/django/core/handlers/exception.py", line 34, in inner
response = get_response(request)
File "/home/aqv/workspace/django_rest_fw/ct_test/environ/lib/python3.6/site-packages/django/core/handlers/base.py", line 115, in _get_response
response = self.process_exception_by_middleware(e, request)
File "/home/aqv/workspace/django_rest_fw/ct_test/environ/lib/python3.6/site-packages/django/core/handlers/base.py", line 113, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/aqv/workspace/django_rest_fw/ct_test/environ/lib/python3.6/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view
return view_func(*args, **kwargs)
File "/home/aqv/workspace/django_rest_fw/ct_test/environ/lib/python3.6/site-packages/rest_framework/viewsets.py", line 116, in view
return self.dispatch(request, *args, **kwargs)
File "/home/aqv/workspace/django_rest_fw/ct_test/environ/lib/python3.6/site-packages/rest_framework/views.py", line 495, in dispatch
response = self.handle_exception(exc)
File "/home/aqv/workspace/django_rest_fw/ct_test/environ/lib/python3.6/site-packages/rest_framework/views.py", line 455, in handle_exception
self.raise_uncaught_exception(exc)
File "/home/aqv/workspace/django_rest_fw/ct_test/environ/lib/python3.6/site-packages/rest_framework/views.py", line 492, in dispatch
response = handler(request, *args, **kwargs)
File "/home/aqv/workspace/django_rest_fw/ct_test/core/views.py", line 47, in create
session_id=data["session_id"]
File "/home/aqv/workspace/django_rest_fw/ct_test/environ/lib/python3.6/site-packages/django/db/models/manager.py", line 82, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "/home/aqv/workspace/django_rest_fw/ct_test/environ/lib/python3.6/site-packages/django/db/models/query.py", line 422, in create
obj.save(force_insert=True, using=self.db)
File "/home/aqv/workspace/django_rest_fw/ct_test/environ/lib/python3.6/site-packages/django/db/models/base.py", line 741, in save
force_update=force_update, update_fields=update_fields)
File "/home/aqv/workspace/django_rest_fw/ct_test/environ/lib/python3.6/site-packages/django/db/models/base.py", line 779, in save_base
force_update, using, update_fields,
File "/home/aqv/workspace/django_rest_fw/ct_test/environ/lib/python3.6/site-packages/django/db/models/base.py", line 870, in _save_table
result = self._do_insert(cls._base_manager, using, fields, update_pk, raw)
File "/home/aqv/workspace/django_rest_fw/ct_test/environ/lib/python3.6/site-packages/django/db/models/base.py", line 908, in _do_insert
using=using, raw=raw)
File "/home/aqv/workspace/django_rest_fw/ct_test/environ/lib/python3.6/site-packages/django/db/models/manager.py", line 82, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "/home/aqv/workspace/django_rest_fw/ct_test/environ/lib/python3.6/site-packages/django/db/models/query.py", line 1186, in _insert
return query.get_compiler(using=using).execute_sql(return_id)
File "/home/aqv/workspace/django_rest_fw/ct_test/environ/lib/python3.6/site-packages/django/db/models/sql/compiler.py", line 1332, in execute_sql
cursor.execute(sql, params)
File "/home/aqv/workspace/django_rest_fw/ct_test/environ/lib/python3.6/site-packages/django/db/backends/utils.py", line 99, in execute
return super().execute(sql, params)
File "/home/aqv/workspace/django_rest_fw/ct_test/environ/lib/python3.6/site-packages/django/db/backends/utils.py", line 67, in execute
return self._execute_with_wrappers(sql, params, many=False, executor=self._execute)
File "/home/aqv/workspace/django_rest_fw/ct_test/environ/lib/python3.6/site-packages/django/db/backends/utils.py", line 76, in _execute_with_wrappers
return executor(sql, params, many, context)
File "/home/aqv/workspace/django_rest_fw/ct_test/environ/lib/python3.6/site-packages/django/db/backends/utils.py", line 84, in _execute
return self.cursor.execute(sql, params)
File "/home/aqv/workspace/django_rest_fw/ct_test/environ/lib/python3.6/site-packages/django/db/utils.py", line 89, in __exit__
raise dj_exc_value.with_traceback(traceback) from exc_value
File "/home/aqv/workspace/django_rest_fw/ct_test/environ/lib/python3.6/site-packages/django/db/backends/utils.py", line 84, in _execute
return self.cursor.execute(sql, params)
File "/home/aqv/workspace/django_rest_fw/ct_test/environ/lib/python3.6/site-packages/django/db/backends/sqlite3/base.py", line 383, in execute
return Database.Cursor.execute(self, query, params)
django.db.utils.IntegrityError: FOREIGN KEY constraint failed
The only foreign key I see is model there, and in your code you aren't passing it.
def create():
model = ItemModel.objects.get(item_id=data["model"])
item_version = ItemVersion.objects.create(
# model=model,
...
This will cause the FK constraint issue if you do not pass in a valid model instance or id because:
You have a default=0 for the model field
But no ItemModel with pk=0 exists in the databsae
If you want model to be nullable, then you can just add that to the FK definition:
class ItemVersion(models.Model):
...
model = models.ForeignKey(ItemModel, null=True, on_delete=CASCADE)
Later on I see you have these 2 lines:
item_version.model.add()
item_version.finished.add(finished).
These are both incorrect. add() doesn't work on boolean model field, and the .add() for an FK is only valid for many-to-many FKs, which are not being used here. The way you are passing them in the commented out sections is fine.
You can get a default value for the 'finished' flag by saying:
data.get('finished', False)
# this will throw a KeyError if "finished" isn't in the dict
True if data["finished"] else False
# this will not throw an error (but doesn't check the value of finished)
True if "finished" in data else False
Some other notes:
1) You use a ModelSerializer without a Meta class inside. Consider just using a standard serializer if you really want to do it by hand, or read up on ModelSerializers. If you use it correctly you shouldn't need a custom create method in the viewset.
2) default=<anything> is not a good idea on an FK. An FK should not generally have a default value (though there are some cases where its nice, like with pre-defined system data in constant tables)
3) You aren't using a serializer in your create method. You are accessing request.data directly. This will give you no validation, and no ability to say finished=BooleanField(default=False) and always get a value for serializer.validated_data['finished'].
How can i retrieve the foreign key from the form child relationship, save it at the same time that I am saving the parent information on the same page.
I am currently working with two forms, the Parent and the child. The logic of the page is saving the name of a book and the name of the course it contains.
Ex: Book = "Learn data structure and algorithms",
Language = "Python"
models.py
class Entity(models.Model):
entity_name = models.CharField(max_length=250, blank=False)
owner = models.ForeignKey(User, on_delete=models.CASCADE, related_name='users')
class Meta:
verbose_name_plural = "Entities"
def __str__(self):
return self.entity_name
def get_absolute_url(self):
return reverse('snippets:password', kwargs={'pk': self.pk})
class Password(models.Model):
password_name = models.CharField(max_length=12, blank=False)
entity = models.ForeignKey(Entity, on_delete=models.CASCADE, related_name='passwords')
def __str__(self):
return self.password_name
forms.py
from django import forms
from snippets.models import Entity, Password
class EntityForm(forms.ModelForm):
class Meta:
model = Entity
fields = ('entity_name',)
class PasswordForm(forms.ModelForm):
class Meta:
model = Password
fields = ('password_name',)
views.py
def password_creation(request):
if request.method == 'POST':
form_one = EntityForm(request.POST)
form_two = PasswordForm(request.POST)
if form_one.is_valid():
entity_form = form_one.save(commit=False)
entity_form.owner = request.user
entity_form.save()
password_form = form_two.save(commit=False)
# HERE : what is the right way to retrieve name from PK
# owner is not part the Password table field therefore
# need to be changed to 'password_name'or 'entity'
# then, how to retrieve the field from the view??
password_form.owner = request.user
password_form.save()
return redirect('snippets:entity')
else:
form_one = EntityForm()
form_two = PasswordForm()
context = {
'form_one':form_one,
'form_two':form_two,
}
return render(request, 'snippets/create-password.html', context)
I have tried the codes above. The problem is that Django is saving the name of the "Book" but not the name of the "Language" in the database. The system also breaks and return this message : NOT NULL constraint failed: snippets_password.entity_id.
Any help would be much appreciated.
Traceback error
Traceback (most recent call last):
File "/Users/macadmin/Documents/Django_wapps/password_change_test/lib/python3.7/site-packages/django/core/handlers/exception.py", line 35, in inner
response = get_response(request)
File "/Users/macadmin/Documents/Django_wapps/password_change_test/lib/python3.7/site-packages/django/core/handlers/base.py", line 128, in _get_response
response = self.process_exception_by_middleware(e, request)
File "/Users/macadmin/Documents/Django_wapps/password_change_test/lib/python3.7/site-packages/django/core/handlers/base.py", line 126, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/Users/macadmin/Documents/Django_wapps/password_change_test/password_change/snippets/views.py", line 67, in password_creation
password_form.save()
File "/Users/macadmin/Documents/Django_wapps/password_change_test/lib/python3.7/site-packages/django/db/models/base.py", line 729, in save
force_update=force_update, update_fields=update_fields)
File "/Users/macadmin/Documents/Django_wapps/password_change_test/lib/python3.7/site-packages/django/db/models/base.py", line 759, in save_base
updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields)
File "/Users/macadmin/Documents/Django_wapps/password_change_test/lib/python3.7/site-packages/django/db/models/base.py", line 842, in _save_table
result = self._do_insert(cls._base_manager, using, fields, update_pk, raw)
File "/Users/macadmin/Documents/Django_wapps/password_change_test/lib/python3.7/site-packages/django/db/models/base.py", line 880, in _do_insert
using=using, raw=raw)
File "/Users/macadmin/Documents/Django_wapps/password_change_test/lib/python3.7/site-packages/django/db/models/manager.py", line 82, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "/Users/macadmin/Documents/Django_wapps/password_change_test/lib/python3.7/site-packages/django/db/models/query.py", line 1125, in _insert
return query.get_compiler(using=using).execute_sql(return_id)
File "/Users/macadmin/Documents/Django_wapps/password_change_test/lib/python3.7/site-packages/django/db/models/sql/compiler.py", line 1280, in execute_sql
cursor.execute(sql, params)
File "/Users/macadmin/Documents/Django_wapps/password_change_test/lib/python3.7/site-packages/django/db/backends/utils.py", line 100, in execute
return super().execute(sql, params)
File "/Users/macadmin/Documents/Django_wapps/password_change_test/lib/python3.7/site-packages/django/db/backends/utils.py", line 68, in execute
return self._execute_with_wrappers(sql, params, many=False, executor=self._execute)
File "/Users/macadmin/Documents/Django_wapps/password_change_test/lib/python3.7/site-packages/django/db/backends/utils.py", line 77, in _execute_with_wrappers
return executor(sql, params, many, context)
File "/Users/macadmin/Documents/Django_wapps/password_change_test/lib/python3.7/site-packages/django/db/backends/utils.py", line 85, in _execute
return self.cursor.execute(sql, params)
File "/Users/macadmin/Documents/Django_wapps/password_change_test/lib/python3.7/site-packages/django/db/utils.py", line 89, in __exit__
raise dj_exc_value.with_traceback(traceback) from exc_value
File "/Users/macadmin/Documents/Django_wapps/password_change_test/lib/python3.7/site-packages/django/db/backends/utils.py", line 85, in _execute
return self.cursor.execute(sql, params)
File "/Users/macadmin/Documents/Django_wapps/password_change_test/lib/python3.7/site-packages/django/db/backends/sqlite3/base.py", line 303, in execute
return Database.Cursor.execute(self, query, params)
django.db.utils.IntegrityError: NOT NULL constraint failed: snippets_password.entity_id
Your diagnosis is not at all correct. Password doesn't have an owner field, or in fact any relation with User. Its relationship is with Entity, and the error clearly states that it is the entity or that is missing. So you just have to assign the Entity you just created:
if form_one.is_valid() and form_two.is_valid():
entity = form_one.save(commit=False)
entity.owner = request.user
entity.save()
password = form_two.save(commit=False)
password.entity = entity
password.save()
Note, I added a check that that form_two is valid, and also renamed the objects: the result of calling form.save is not a form, but an instance of the model.
I'm trying my hand at creating a little django api for school. At the moment I'm having trouble getting the authorized user when I attempt to create a model with a foreign key. Here is the code I've been trying
MODEL:
class JobListing(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
company_name = models.CharField(max_length=80)
job_position = models.CharField(max_length=50)
job_phone = models.CharField(max_length=10)
job_email = models.EmailField()
job_description = models.TextField()
job_schedule = models.CharField(max_length=500)
job_post_date = models.DateField(auto_now_add=True)
VIEW:
class CreatePostView(generics.CreateAPIView):
"""
API endpoint that allows a Job Post to be created
"""
#queryset = ''
authentication_classes = (TokenAuthentication,)
permission_classes = (IsAuthenticated,)
serializer_class = JobPostingSerializer
SERIALIZER:
class JobPostingSerializer(serializers.ModelSerializer):
user = serializers.SerializerMethodField()
class Meta:
model = JobListing
fields = ('user', 'company_name', 'job_position', 'job_phone', 'job_email', 'job_description', 'job_schedule')
def create(self, validated_data):
post = super().create(validated_data)
post.save()
return post
def get_user(self, instance):
user = self.context['request'].user
return user.id
URLS:
urlpatterns = [
url(r'^', include(router.urls)),
url(r'^api-auth', include('rest_framework.urls', namespace='rest_framework')),
path('home/', views.Home.as_view(), name='home'),
path('login/', views.Login.as_view(), name='login'),
path('getUserDetail/', views.TestSimpleUserJsonAuth.as_view(), name='getUserDetail'),
path('getPosts/', views.getPosts.as_view(), name='getPosts'),
url(r'signup/', views.CreateUserView.as_view(), name='signup'),
url(r'createPost/', views.CreatePostView.as_view(), name='createPost')
I have tried a number of different variations of this including overriding the get context method and trying to change the viewset I'm using. Nothing seems to get it working. Error I'm seeing right now is
IntegrityError at /createPost/
NOT NULL constraint failed: temploybackend_joblisting.user_id
Request Method: POST
Request URL: http://192.168.99.100:8000/createPost/
Traceback:
File "/usr/local/lib/python3.6/site-packages/django/db/backends/utils.py" in _execute
85. return self.cursor.execute(sql, params)
File "/usr/local/lib/python3.6/site-packages/django/db/backends/sqlite3/base.py" in execute
303. return Database.Cursor.execute(self, query, params)
The above exception (NOT NULL constraint failed: temploybackend_joblisting.user_id) was the direct cause of the following exception:
File "/usr/local/lib/python3.6/site-packages/django/core/handlers/exception.py" in inner
35. response = get_response(request)
File "/usr/local/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response
128. response = self.process_exception_by_middleware(e, request)
File "/usr/local/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response
126. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/usr/local/lib/python3.6/site-packages/django/views/decorators/csrf.py" in wrapped_view
54. return view_func(*args, **kwargs)
File "/usr/local/lib/python3.6/site-packages/django/views/generic/base.py" in view
69. return self.dispatch(request, *args, **kwargs)
File "/usr/local/lib/python3.6/site-packages/rest_framework/views.py" in dispatch
494. response = self.handle_exception(exc)
File "/usr/local/lib/python3.6/site-packages/rest_framework/views.py" in handle_exception
454. self.raise_uncaught_exception(exc)
File "/usr/local/lib/python3.6/site-packages/rest_framework/views.py" in dispatch
491. response = handler(request, *args, **kwargs)
File "/usr/local/lib/python3.6/site-packages/rest_framework/generics.py" in post
192. return self.create(request, *args, **kwargs)
File "/usr/local/lib/python3.6/site-packages/rest_framework/mixins.py" in create
21. self.perform_create(serializer)
File "/usr/local/lib/python3.6/site-packages/rest_framework/mixins.py" in perform_create
26. serializer.save()
File "/usr/local/lib/python3.6/site-packages/rest_framework/serializers.py" in save
214. self.instance = self.create(validated_data)
File "/var/www/temploybackend/serializers.py" in create
54. post = super().create(validated_data)
File "/usr/local/lib/python3.6/site-packages/rest_framework/serializers.py" in create
917. instance = ModelClass.objects.create(**validated_data)
File "/usr/local/lib/python3.6/site-packages/django/db/models/manager.py" in manager_method
82. return getattr(self.get_queryset(), name)(*args, **kwargs)
File "/usr/local/lib/python3.6/site-packages/django/db/models/query.py" in create
417. obj.save(force_insert=True, using=self.db)
File "/usr/local/lib/python3.6/site-packages/django/db/models/base.py" in save
729. force_update=force_update, update_fields=update_fields)
File "/usr/local/lib/python3.6/site-packages/django/db/models/base.py" in save_base
759. updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields)
File "/usr/local/lib/python3.6/site-packages/django/db/models/base.py" in _save_table
842. result = self._do_insert(cls._base_manager, using, fields, update_pk, raw)
File "/usr/local/lib/python3.6/site-packages/django/db/models/base.py" in _do_insert
880. using=using, raw=raw)
File "/usr/local/lib/python3.6/site-packages/django/db/models/manager.py" in manager_method
82. return getattr(self.get_queryset(), name)(*args, **kwargs)
File "/usr/local/lib/python3.6/site-packages/django/db/models/query.py" in _insert
1125. return query.get_compiler(using=using).execute_sql(return_id)
File "/usr/local/lib/python3.6/site-packages/django/db/models/sql/compiler.py" in execute_sql
1281. cursor.execute(sql, params)
File "/usr/local/lib/python3.6/site-packages/django/db/backends/utils.py" in execute
100. return super().execute(sql, params)
File "/usr/local/lib/python3.6/site-packages/django/db/backends/utils.py" in execute
68. return self._execute_with_wrappers(sql, params, many=False, executor=self._execute)
File "/usr/local/lib/python3.6/site-packages/django/db/backends/utils.py" in _execute_with_wrappers
77. return executor(sql, params, many, context)
File "/usr/local/lib/python3.6/site-packages/django/db/backends/utils.py" in _execute
85. return self.cursor.execute(sql, params)
File "/usr/local/lib/python3.6/site-packages/django/db/utils.py" in __exit__
89. raise dj_exc_value.with_traceback(traceback) from exc_value
File "/usr/local/lib/python3.6/site-packages/django/db/backends/utils.py" in _execute
85. return self.cursor.execute(sql, params)
File "/usr/local/lib/python3.6/site-packages/django/db/backends/sqlite3/base.py" in execute
303. return Database.Cursor.execute(self, query, params)
Exception Type: IntegrityError at /createPost/
Exception Value: NOT NULL constraint failed: temploybackend_joblisting.user_id
Thank you for any help that can be provided!
SerializerMethodField is read_only field and not using in object creation. You need to replace it with PrimaryKeyRelatedField with default CurrentUserDefault:
class JobPostingSerializer(serializers.ModelSerializer):
user = serializers.PrimaryKeyRelatedField(
read_only=True,
default=serializers.CurrentUserDefault()
)
class Meta:
model = JobListing
fields = ('user', 'company_name', 'job_position', 'job_phone', 'job_email', 'job_description', 'job_schedule')
def create(self, validated_data):
post = super().create(validated_data)
post.save()
return post
I have created a Django project in which type-1 users can create a Post and type-2 users can bid on a post out of post_queryset = Post.objects.filter(accepted=False). Finally, post_owner can accept a bid. After accepting I wanted to remove the accepted_object from post_queryset. So, I created a view(accept_bid) in which a type-1 user can accept a bid and simultaneously it passes a BooleanField(accepted) = True. With this, the post will no longer appear in the post_list page. But when I saving the accept_bid instance, it raising an IntegrityError: (1048, "Column 'date' cannot be null"). I'm not sure whether my approach in changing the BooleanField() = True in my view is correct. I would appreciate helping me solve this.
Here's My code:
Models.py:
class Post(models.Model):
item = models.CharField(max_length=20)
post_owner = models.OneToOneField(settings.AUTH_USER_MODEL, default=1)
date = models.DateField()
accepted = models.BooleanField(default = False)
class Bid(models.Model):
post = models.ForeignKey(Post, related_name = bids)
amount = models.IntegerField(max_length = 20)
bidder = models.ForeingKey(settings.AUTH_USER_MODEL)
class Auction(models.Model):
post = models.OneToOneField(Post)
post_owner = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, blank=True)
bid = models.OneToOneField('truck.Bid', related_name='auctions')
forms.py:
class AcceptedForm(forms.ModelForm):
accepted = forms.BooleanField(required=False)
class Meta:
model = Post
fields = ('accepted', )
views.py:
def accept_bid(request, post_id, bid_id):
post = get_object_or_404(Post, id=post_id)
bid = get_object_or_404(Bid, id=bid_id)
if request.method=='POST':
form = AuctionForm(request.POST or None)
form1 = AcceptedForm(request.POST)
if form.is_valid() and form1.is_valid():
accept_bid = form.save(commit=False)
accept_bid.bid = bid
accept_bid.post = post
accept_bid.post_owner = request.user
accepted = form1.save()
accepted.accepted = True
accept_bid.save()
form.save()
form1.save()
else:
form = AuctionForm()
form1 = AcceptedForm()
context = {
"bid_id" : bid_id,
"post_id" : post_id,
"bid": bid,
"post":post,
'form': form
'form1': form1,
}
return render(request, 'loggedin_load/active_deals.html', context)
TraceBack:
Traceback:
File "c:\python34\lib\site-packages\django\db\backends\mysql\base.py" in execute
112. return self.cursor.execute(query, args)
File "c:\python34\lib\site-packages\MySQLdb\cursors.py" in execute
226. self.errorhandler(self, exc, value)
File "c:\python34\lib\site-packages\MySQLdb\connections.py" in defaulterrorhandler
36. raise errorvalue
File "c:\python34\lib\site-packages\MySQLdb\cursors.py" in execute
217. res = self._query(query)
File "c:\python34\lib\site-packages\MySQLdb\cursors.py" in _query
378. rowcount = self._do_query(q)
File "c:\python34\lib\site-packages\MySQLdb\cursors.py" in _do_query
341. db.query(q)
File "c:\python34\lib\site-packages\MySQLdb\connections.py" in query
280. _mysql.connection.query(self, query)
During handling of the above exception ((1048, "Column 'date' cannot be null")), another exception occurred:
File "c:\python34\lib\site-packages\django\core\handlers\base.py" in get_response
149. response = self.process_exception_by_middleware(e, request)
File "c:\python34\lib\site-packages\django\core\handlers\base.py" in get_response
147. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "c:\python34\lib\site-packages\django\contrib\auth\decorators.py" in _wrapped_view
23. return view_func(request, *args, **kwargs)
File "c:\python34\lib\site-packages\django\contrib\auth\decorators.py" in _wrapped_view
23. return view_func(request, *args, **kwargs)
File "C:\Users\sumanth\Desktop\django-custom-user-master\search field\Project\mysite\personal\views.py" in accept_bid
447. accepted = form1.save()
File "c:\python34\lib\site-packages\django\forms\models.py" in save
451. self.instance.save()
File "c:\python34\lib\site-packages\django\db\models\base.py" in save
708. force_update=force_update, update_fields=update_fields)
File "c:\python34\lib\site-packages\django\db\models\base.py" in save_base
736. updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields)
File "c:\python34\lib\site-packages\django\db\models\base.py" in _save_table
820. result = self._do_insert(cls._base_manager, using, fields, update_pk, raw)
File "c:\python34\lib\site-packages\django\db\models\base.py" in _do_insert
859. using=using, raw=raw)
File "c:\python34\lib\site-packages\django\db\models\manager.py" in manager_method
122. return getattr(self.get_queryset(), name)(*args, **kwargs)
File "c:\python34\lib\site-packages\django\db\models\query.py" in _insert
1039. return query.get_compiler(using=using).execute_sql(return_id)
File "c:\python34\lib\site-packages\django\db\models\sql\compiler.py" in execute_sql
1060. cursor.execute(sql, params)
File "c:\python34\lib\site-packages\django\db\backends\utils.py" in execute
79. return super(CursorDebugWrapper, self).execute(sql, params)
File "c:\python34\lib\site-packages\django\db\backends\utils.py" in execute
64. return self.cursor.execute(sql, params)
File "c:\python34\lib\site-packages\django\db\backends\mysql\base.py" in execute
117. six.reraise(utils.IntegrityError, utils.IntegrityError(*tuple(e.args)), sys.exc_info()[2])
File "c:\python34\lib\site-packages\django\utils\six.py" in reraise
685. raise value.with_traceback(tb)
File "c:\python34\lib\site-packages\django\db\backends\mysql\base.py" in execute
112. return self.cursor.execute(query, args)
File "c:\python34\lib\site-packages\MySQLdb\cursors.py" in execute
226. self.errorhandler(self, exc, value)
File "c:\python34\lib\site-packages\MySQLdb\connections.py" in defaulterrorhandler
36. raise errorvalue
File "c:\python34\lib\site-packages\MySQLdb\cursors.py" in execute
217. res = self._query(query)
File "c:\python34\lib\site-packages\MySQLdb\cursors.py" in _query
378. rowcount = self._do_query(q)
File "c:\python34\lib\site-packages\MySQLdb\cursors.py" in _do_query
341. db.query(q)
File "c:\python34\lib\site-packages\MySQLdb\connections.py" in query
280. _mysql.connection.query(self, query)
Exception Type: IntegrityError at /post/3/bid/7/
Exception Value: (1048, "Column 'date' cannot be null")
The error trips when you try to save form1 rather than when saving the accept_bid instance:
File "C:\Users\sumanth\Desktop\django-custom-user-master\search field\Project\mysite\personal\views.py" in accept_bid
447. accepted = form1.save()
form1 is a ModelForm based on your Post model. Since your Post model already has an accepted attribute, you don't have to manually define a field for it like you did here - including that field in the Meta definition for the form like you've done is enough.
You will need to do one of three things from there:
Also include the date field in your ModelForm so that it can be set by the submitter,
Set up your model to either automatically include a date on creation (auto_now_add=True), or to allow that field to be blank. Or,
Use commit=False to interrupt the save and add a date to your object:
accepted = form1.save(commit=False)
accepted.date = ...
accepted.save()
Also note that here:
accepted = form1.save()
accepted.accepted = True
You save accepted to your database, then update the object locally. The second line is only updating the object in memory, not the database. If you print accepted.accepted it will indeed show up as True, but if you re-fetch the object from the database and then try it again it'll show up as False since that change was never saved to the DB.
I am getting an 'Exception Value: expected string or buffer' every time I submit my form. It definitely seems like the issue is with the model field 'pub_date'. I have attached my code and the traceback I'm getting.
My question is, what exactly is going wrong here and is there any way to work around it?
#MODELS
class Entry(models.Model):
pub_date=models.DateTimeField(default=datetime.datetime.now,blank=True)
#FORMS
class SellForm(ModelForm):
class Meta:
model = Entry
fields = ['pub_date']
#VIEWS
def get_entry(request):
if request.method == 'POST':
f = SellForm(request.POST)
if f.is_valid():
obj=f.save(commit=False)
obj.save()
return HttpResponseRedirect('/storefront/')
else:
f = SellForm()
return render(request, 'sell.html', {'form': f})
Traceback:
File "/Users/benjamino/Desktop/deal/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response
114. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/Users/benjamino/Desktop/deal/deal/accounts/views.py" in get_entry
27. form.save()
File "/Users/benjamino/Desktop/deal/lib/python2.7/site-packages/django/db/models/base.py" in save
545. force_update=force_update, update_fields=update_fields)
File "/Users/benjamino/Desktop/deal/lib/python2.7/site-packages/django/db/models/base.py" in save_base
573. updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields)
File "/Users/benjamino/Desktop/deal/lib/python2.7/site-packages/django/db/models/base.py" in _save_table
654. result = self._do_insert(cls._base_manager, using, fields, update_pk, raw)
File "/Users/benjamino/Desktop/deal/lib/python2.7/site-packages/django/db/models/base.py" in _do_insert
687. using=using, raw=raw)
File "/Users/benjamino/Desktop/deal/lib/python2.7/site-packages/django/db/models/manager.py" in _insert
232. return insert_query(self.model, objs, fields, **kwargs)
File "/Users/benjamino/Desktop/deal/lib/python2.7/site-packages/django/db/models/query.py" in insert_query
1511. return query.get_compiler(using=using).execute_sql(return_id)
File "/Users/benjamino/Desktop/deal/lib/python2.7/site-packages/django/db/models/sql/compiler.py" in execute_sql
897. for sql, params in self.as_sql():
File "/Users/benjamino/Desktop/deal/lib/python2.7/site-packages/django/db/models/sql/compiler.py" in as_sql
855. for obj in self.query.objs
File "/Users/benjamino/Desktop/deal/lib/python2.7/site-packages/django/db/models/fields/__init__.py" in get_db_prep_save
350. prepared=False)
File "/Users/benjamino/Desktop/deal/lib/python2.7/site-packages/django/db/models/fields/__init__.py" in get_db_prep_value
911. value = self.get_prep_value(value)
File "/Users/benjamino/Desktop/deal/lib/python2.7/site-packages/django/db/models/fields/__init__.py" in get_prep_value
895. value = self.to_python(value)
File "/Users/benjamino/Desktop/deal/lib/python2.7/site-packages/django/db/models/fields/__init__.py" in to_python
854. parsed = parse_datetime(value)
File "/Users/benjamino/Desktop/deal/lib/python2.7/site-packages/django/utils/dateparse.py" in parse_datetime
67. match = datetime_re.match(value)
Exception Type: TypeError at /sell/
Exception Value: expected string or buffer
I is because here:
obj=f.save(commit=False)
obj.save()
you are saving a WHOLE form. For what?
I think it will be better to extract data from form fields and use them.
There is a built in form cleaned_data attribute. f.cleaned_data - and you will get dictionary
of form field values.