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
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 am using Django Rest Framework. I have a model TestSuite which has Foreign key relations to the model Team and EmailTemplates. When I do a post() to Test Suite through postman, the data is inserted in the TestSuite table and request works successfully. However, when I do a get() or try to click on the url link from localhost to access TestSuite, it throws below error
AttributeError at /dqf_api/test_suite/
'str' object has no attribute 'pk'
error traceback
File "/usr/local/lib/python3.6/dist-packages/django/core/handlers/exception.py" in inner
35. response = get_response(request)
File "/usr/local/lib/python3.6/dist-packages/django/core/handlers/base.py" in _get_response
128. response = self.process_exception_by_middleware(e, request)
File "/usr/local/lib/python3.6/dist-packages/django/core/handlers/base.py" in _get_response
126. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/usr/lib/python3.6/contextlib.py" in inner
52. return func(*args, **kwds)
File "/usr/local/lib/python3.6/dist-packages/django/views/decorators/csrf.py" in wrapped_view
54. return view_func(*args, **kwargs)
File "/usr/local/lib/python3.6/dist-packages/rest_framework/viewsets.py" in view
116. return self.dispatch(request, *args, **kwargs)
File "/usr/local/lib/python3.6/dist-packages/rest_framework/views.py" in dispatch
495. response = self.handle_exception(exc)
File "/usr/local/lib/python3.6/dist-packages/rest_framework/views.py" in handle_exception
455. self.raise_uncaught_exception(exc)
File "/usr/local/lib/python3.6/dist-packages/rest_framework/views.py" in dispatch
492. response = handler(request, *args, **kwargs)
File "/usr/local/lib/python3.6/dist-packages/rest_framework/mixins.py" in list
48. return Response(serializer.data)
File "/usr/local/lib/python3.6/dist-packages/rest_framework/serializers.py" in data
768. ret = super(ListSerializer, self).data
File "/usr/local/lib/python3.6/dist-packages/rest_framework/serializers.py" in data
262. self._data = self.to_representation(self.instance)
File "/usr/local/lib/python3.6/dist-packages/rest_framework/serializers.py" in to_representation
686. self.child.to_representation(item) for item in iterable
File "/usr/local/lib/python3.6/dist-packages/rest_framework/serializers.py" in <listcomp>
686. self.child.to_representation(item) for item in iterable
File "/usr/local/lib/python3.6/dist-packages/rest_framework/serializers.py" in to_representation
530. ret[field.field_name] = field.to_representation(attribute)
File "/usr/local/lib/python3.6/dist-packages/rest_framework/relations.py" in to_representation
272. return value.pk
Exception Type: AttributeError at /dqf_api/test_suites/
Exception Value: 'str' object has no attribute 'pk'
models.py
class Team(models.Model):
team_name = models.CharField(primary_key=True, max_length=30)
description = models.CharField(max_length=100, blank=True, null=True)
class Meta:
managed = False
db_table = 'team'
class TestSuite(models.Model):
team_name = models.ForeignKey(Team, on_delete=models.DO_NOTHING, db_column='team_name')
suite_name = models.CharField(max_length=100)
description = models.CharField(max_length=200, blank=True, null=True)
schedule = models.CharField(max_length=100, blank=True, null=True)
email_list_ok = models.CharField(max_length=200, blank=True, null=True)
email_list_fail = models.CharField(max_length=200, blank=True, null=True)
template_name = models.ForeignKey(EmailTemplates, on_delete=models.DO_NOTHING, db_column='template_name')
class Meta:
managed = False
db_table = 'test_suite'
unique_together = (('team_name', 'suite_name'),)
views.py
class TestSuiteViewSet(viewsets.ModelViewSet):
queryset = models.TestSuite.objects.values('team_name','suite_name', 'description','schedule','email_list_ok','email_list_fail','template_name')
serializer_class = serializers.TestSuiteSerializer
class TeamViewSet(viewsets.ModelViewSet):
queryset = models.Team.objects.all()
serializer_class = serializers.TeamSerializer
serializers.py
class TestSuiteSerializer(serializers.ModelSerializer):
class Meta:
model = models.TestSuite
fields = ['team_name','suite_name', 'description','schedule','email_list_ok','email_list_fail','template_name']
Can someone please help here. I am new to django and DRF
EDIT
When I used queryset = models.TestSuite.objects.all() in serializers.py, it throws below error.
File "/usr/local/lib/python3.6/dist-packages/django/db/backends/utils.py" in _execute
85. return self.cursor.execute(sql, params)
File "/usr/local/lib/python3.6/dist-packages/django/db/backends/mysql/base.py" in execute
71. return self.cursor.execute(query, args)
File "/usr/local/lib/python3.6/dist-packages/MySQLdb/cursors.py" in execute
206. res = self._query(query)
File "/usr/local/lib/python3.6/dist-packages/MySQLdb/cursors.py" in _query
312. db.query(q)
File "/usr/local/lib/python3.6/dist-packages/MySQLdb/connections.py" in query
224. _mysql.connection.query(self, query)
The above exception ((1054, "Unknown column 'test_suite.id' in 'field list'")) was the direct cause of the following exception:
File "/usr/local/lib/python3.6/dist-packages/django/core/handlers/exception.py" in inner
35. response = get_response(request)
File "/usr/local/lib/python3.6/dist-packages/django/core/handlers/base.py" in _get_response
128. response = self.process_exception_by_middleware(e, request)
File "/usr/local/lib/python3.6/dist-packages/django/core/handlers/base.py" in _get_response
126. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/usr/lib/python3.6/contextlib.py" in inner
52. return func(*args, **kwds)
File "/usr/local/lib/python3.6/dist-packages/django/views/decorators/csrf.py" in wrapped_view
54. return view_func(*args, **kwargs)
File "/usr/local/lib/python3.6/dist-packages/rest_framework/viewsets.py" in view
116. return self.dispatch(request, *args, **kwargs)
File "/usr/local/lib/python3.6/dist-packages/rest_framework/views.py" in dispatch
495. response = self.handle_exception(exc)
File "/usr/local/lib/python3.6/dist-packages/rest_framework/views.py" in handle_exception
455. self.raise_uncaught_exception(exc)
File "/usr/local/lib/python3.6/dist-packages/rest_framework/views.py" in dispatch
492. response = handler(request, *args, **kwargs)
File "/usr/local/lib/python3.6/dist-packages/rest_framework/mixins.py" in list
48. return Response(serializer.data)
File "/usr/local/lib/python3.6/dist-packages/rest_framework/serializers.py" in data
768. ret = super(ListSerializer, self).data
File "/usr/local/lib/python3.6/dist-packages/rest_framework/serializers.py" in data
262. self._data = self.to_representation(self.instance)
File "/usr/local/lib/python3.6/dist-packages/rest_framework/serializers.py" in to_representation
686. self.child.to_representation(item) for item in iterable
File "/usr/local/lib/python3.6/dist-packages/django/db/models/query.py" in __iter__
272. self._fetch_all()
File "/usr/local/lib/python3.6/dist-packages/django/db/models/query.py" in _fetch_all
1179. self._result_cache = list(self._iterable_class(self))
File "/usr/local/lib/python3.6/dist-packages/django/db/models/query.py" in __iter__
54. results = compiler.execute_sql(chunked_fetch=self.chunked_fetch, chunk_size=self.chunk_size)
File "/usr/local/lib/python3.6/dist-packages/django/db/models/sql/compiler.py" in execute_sql
1064. cursor.execute(sql, params)
File "/usr/local/lib/python3.6/dist-packages/django/db/backends/utils.py" in execute
100. return super().execute(sql, params)
File "/usr/local/lib/python3.6/dist-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/dist-packages/django/db/backends/utils.py" in _execute_with_wrappers
77. return executor(sql, params, many, context)
File "/usr/local/lib/python3.6/dist-packages/django/db/backends/utils.py" in _execute
85. return self.cursor.execute(sql, params)
File "/usr/local/lib/python3.6/dist-packages/django/db/utils.py" in __exit__
89. raise dj_exc_value.with_traceback(traceback) from exc_value
File "/usr/local/lib/python3.6/dist-packages/django/db/backends/utils.py" in _execute
85. return self.cursor.execute(sql, params)
File "/usr/local/lib/python3.6/dist-packages/django/db/backends/mysql/base.py" in execute
71. return self.cursor.execute(query, args)
File "/usr/local/lib/python3.6/dist-packages/MySQLdb/cursors.py" in execute
206. res = self._query(query)
File "/usr/local/lib/python3.6/dist-packages/MySQLdb/cursors.py" in _query
312. db.query(q)
File "/usr/local/lib/python3.6/dist-packages/MySQLdb/connections.py" in query
224. _mysql.connection.query(self, query)
Exception Type: OperationalError at /dqf_api/test_suites/
Exception Value: (1054, "Unknown column 'test_suite.id' in 'field list'")
I think the problem is here:
class TestSuiteViewSet(viewsets.ModelViewSet):
queryset = models.TestSuite.objects.values('team_name','suite_name', 'description','schedule','email_list_ok','email_list_fail','template_name') # <-- Here
serializer_class = serializers.TestSuiteSerializer
You need to provide a queryset, not a dictionary. So it should be like this:
class TestSuiteViewSet(viewsets.ModelViewSet):
queryset = models.TestSuite.objects.all()
serializer_class = serializers.TestSuiteSerializer
models.py:
from django.contrib.auth.models import User
class Location(models.Model):
user = models.ForeignKey(User)
...
...
views.py:
class AddLocationPageView(CreateView):
model = Location
form_class = LocationForm
template_name = 'add_location.html'
success_url = '/add_location/location_added/'
#method_decorator(login_required)
def dispatch(self, *args, **kwargs):
return super(AddLocationPageView, self).dispatch(*args, **kwargs)
forms.py:
from multiupload.fields import MultiFileField
from .models import Location, LocationType, Equipment, VisitTime, Photo
class LocationForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(LocationForm, self).__init__(*args, **kwargs)
self.fields["types"].queryset = LocationType.objects.all()
self.fields["equipment"].queryset = Equipment.objects.all()
self.fields["visit_times"].queryset = VisitTime.objects.all()
class Meta:
model = Location
fields = ['name', 'types', 'equipment', 'visit_times', 'keywords', 'description']
widgets = {
'name': forms.TextInput(attrs={'placeholder': 'Напр. Стоунхендж'}),
'keywords': forms.TextInput(attrs={'placeholder': 'Напр. море, побережье, скалы'}),
'description': forms.Textarea(attrs={'placeholder': 'Любая информация, которую посчитаете нужной'}),
'types': forms.CheckboxSelectMultiple(),
'equipment': forms.CheckboxSelectMultiple(),
'visit_times': forms.CheckboxSelectMultiple(),
}
photos = MultiFileField(min_num=1, max_num=10)
def save(self, commit=True):
instance = super(LocationForm, self).save(commit)
for each in self.cleaned_data['photos']:
Photo.objects.create(photo=each, location=instance)
return instance
urls.py:
url(r'^add_location/$', AddLocationPageView.as_view(), name='add_location'),
When I am trying to save the location form I see the error.
What I have to do in order to get rid of this trouble?
Any advices will be a lot appreciated!
Thanks a lot!
I am adding traceback below for more clearness.
Traceback:
File "C:\commercial_projects\fl\lib\site-packages\django\core\handlers\base.py" in get_response
132. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\commercial_projects\fl\lib\site-packages\django\views\generic\base.py" in view
71. return self.dispatch(request, *args, **kwargs)
File "C:\commercial_projects\fl\lib\site-packages\django\utils\decorators.py" in _wrapper
34. return bound_func(*args, **kwargs)
File "C:\commercial_projects\fl\lib\site-packages\django\contrib\auth\decorators.py" in _wrapped_view
22. return view_func(request, *args, **kwargs)
File "C:\commercial_projects\fl\lib\site-packages\django\utils\decorators.py" in bound_func
30. return func.__get__(self, type(self))(*args2, **kwargs2)
File "C:\commercial_projects\fl\src\findlocation_app\views.py" in dispatch
43. return super(AddLocationPageView, self).dispatch(*args, **kwargs)
File "C:\commercial_projects\fl\lib\site-packages\django\views\generic\base.py" in dispatch
89. return handler(request, *args, **kwargs)
File "C:\commercial_projects\fl\lib\site-packages\django\views\generic\edit.py" in post
249. return super(BaseCreateView, self).post(request, *args, **kwargs)
File "C:\commercial_projects\fl\lib\site-packages\django\views\generic\edit.py" in post
215. return self.form_valid(form)
File "C:\commercial_projects\fl\lib\site-packages\django\views\generic\edit.py" in form_valid
193. self.object = form.save()
File "C:\commercial_projects\fl\src\findlocation_app\forms.py" in save
33. instance = super(LocationForm, self).save(commit)
File "C:\commercial_projects\fl\lib\site-packages\django\forms\models.py" in save
459. construct=False)
File "C:\commercial_projects\fl\lib\site-packages\django\forms\models.py" in save_instance
105. instance.save()
File "C:\commercial_projects\fl\lib\site-packages\django\db\models\base.py" in save
734. force_update=force_update, update_fields=update_fields)
File "C:\commercial_projects\fl\lib\site-packages\django\db\models\base.py" in save_base
762. updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields)
File "C:\commercial_projects\fl\lib\site-packages\django\db\models\base.py" in _save_table
846. result = self._do_insert(cls._base_manager, using, fields, update_pk, raw)
File "C:\commercial_projects\fl\lib\site-packages\django\db\models\base.py" in _do_insert
885. using=using, raw=raw)
File "C:\commercial_projects\fl\lib\site-packages\django\db\models\manager.py" in manager_method
127. return getattr(self.get_queryset(), name)(*args, **kwargs)
File "C:\commercial_projects\fl\lib\site-packages\django\db\models\query.py" in _insert
920. return query.get_compiler(using=using).execute_sql(return_id)
File "C:\commercial_projects\fl\lib\site-packages\django\db\models\sql\compiler.py" in execute_sql
974. cursor.execute(sql, params)
File "C:\commercial_projects\fl\lib\site-packages\django\db\backends\utils.py" in execute
79. return super(CursorDebugWrapper, self).execute(sql, params)
File "C:\commercial_projects\fl\lib\site-packages\django\db\backends\utils.py" in execute
64. return self.cursor.execute(sql, params)
File "C:\commercial_projects\fl\lib\site-packages\django\db\utils.py" in __exit__
98. six.reraise(dj_exc_type, dj_exc_value, traceback)
File "C:\commercial_projects\fl\lib\site-packages\django\db\backends\utils.py" in execute
64. return self.cursor.execute(sql, params)
File "C:\commercial_projects\fl\lib\site-packages\django\db\backends\sqlite3\base.py" in execute
318. return Database.Cursor.execute(self, query, params)
Exception Type: IntegrityError at /add_location/
Exception Value: findlocation_app_location.user_id may not be NULL
You have to understand what the problem is first. You have a foreign key to user field in model, but you exclude that in your form. Since user field cannot be empty, your save will be rejected by database. To set the foreign key for a ModelForm, you should override the form_valid method:
class AddLocationPageView(CreateView):
model = Location
def form_valid(self, form):
location = form.save(commit=False)
location.user = self.request.user
return super(CreateArticle, self).form_valid(form)
You could also include user in your form, so your form would contain the information when you save so there's no code change. But I bet that's not what you want because then your form would show a dropdown and let you select a user which doesn't make sense.
See django doc for what's going on with commit=False.
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.