Luis A. Borit Guitton Luis A. Borit Guitton - 4 months ago 18
Python Question

int() argument must be a string or a number, not 'SimpleLazyObject' in django

I have this problem catching the pk of the Selfie model, i'm trying to save a comment, but i have this error, the mistake is in the CreateComment class in the views.py, please guys i need a hand

in models.py

class Selfie(models.Model):
selfie_title = models.CharField(max_length=50)
selfie_description = models.TextField(null=True, blank=True)
selfie_image = models.ImageField(upload_to="images/",
width_field="selfie_width",
height_field="selfie_height",
)
selfie_height = models.IntegerField(default=0)
selfie_width = models.IntegerField(default=0)
selfie_favorite = models.BooleanField()
selfie_user = models.ForeignKey("auth.User")
selfie_timestamp = models.DateTimeField(auto_now=True)

def __unicode__(self):
return unicode(self.selfie_title)

def __str__(self):
return self.selfie_title

class Comment(models.Model):
comment_user = models.ForeignKey("auth.User")
body_comment = models.TextField()
timestamp_comment = models.DateTimeField(auto_now=True)
post_comment = models.ForeignKey("Selfie")

def __unicode__(self):
return unicode(self.body_comment[:20])

def __str__(self):
return self.body_comment[:20]


in views.py

class SelfieDetail(DetailView):
template_name = "SelfieDetail.html"
model = Selfie

def get_context_data(self, **kwargs):
context = super(SelfieDetail, self).get_context_data(**kwargs)
context['form'] = CommentForm
if self.request.POST:
context['form'] = CommentForm(self.request.POST)
else:
context['form'] = CommentForm()
return context

class CreateComment(FormView):
form_class = CommentForm
success_url = '../login'
template_name = "SelfieDetail.html"

def get_form_kwargs(self):
form_kwargs = super(CreateComment, self).get_form_kwargs()
if 'pk' in self.kwargs:
form_kwargs['instance'] = models.Selfie.objects.get(pk=int(self.kwargs['pk']))
return form_kwargs

def form_valid(self, form, *args, **kwargs):
context = self.get_context_data()
form = context['form']
obj = form.save(commit=False)
obj.comment_user_id = self.request.user
#obj.post_comment_id = kwargs={'pk': Selfie.pk} .... self.request.POST.get('comment')
obj.post_comment_id = self.request.GET.get( 'post_comment_id' )
obj.save()
return redirect('/login')


template

<form method="POST" action="{% url 'createComment' %}">
{% csrf_token %}
{{ form.as_p }}
<button type="submit" class="btn btn-lg">(Comentar)</button>
</form>


traceback

Environment:


Request Method: POST
Request URL: http://127.0.0.1:8000/comment/

Django Version: 1.9
Python Version: 2.7.12
Installed Applications:
['django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'stylizrApp']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware']



Traceback:

File "/home/l/Desktop/stylizr/local/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response
149. response = self.process_exception_by_middleware(e, request)

File "/home/l/Desktop/stylizr/local/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response
147. response = wrapped_callback(request, *callback_args, **callback_kwargs)

File "/home/l/Desktop/stylizr/local/lib/python2.7/site-packages/django/views/generic/base.py" in view
68. return self.dispatch(request, *args, **kwargs)

File "/home/l/Desktop/stylizr/local/lib/python2.7/site-packages/django/views/generic/base.py" in dispatch
88. return handler(request, *args, **kwargs)

File "/home/l/Desktop/stylizr/local/lib/python2.7/site-packages/django/views/generic/edit.py" in post
221. return self.form_valid(form)

File "/home/l/Desktop/stylizr/src/stylizrApp/views.py" in form_valid
49. obj.save()

File "/home/l/Desktop/stylizr/local/lib/python2.7/site-packages/django/db/models/base.py" in save
700. force_update=force_update, update_fields=update_fields)

File "/home/l/Desktop/stylizr/local/lib/python2.7/site-packages/django/db/models/base.py" in save_base
728. updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields)

File "/home/l/Desktop/stylizr/local/lib/python2.7/site-packages/django/db/models/base.py" in _save_table
812. result = self._do_insert(cls._base_manager, using, fields, update_pk, raw)

File "/home/l/Desktop/stylizr/local/lib/python2.7/site-packages/django/db/models/base.py" in _do_insert
851. using=using, raw=raw)

File "/home/l/Desktop/stylizr/local/lib/python2.7/site-packages/django/db/models/manager.py" in manager_method
122. return getattr(self.get_queryset(), name)(*args, **kwargs)

File "/home/l/Desktop/stylizr/local/lib/python2.7/site-packages/django/db/models/query.py" in _insert
1039. return query.get_compiler(using=using).execute_sql(return_id)

File "/home/l/Desktop/stylizr/local/lib/python2.7/site-packages/django/db/models/sql/compiler.py" in execute_sql
1064. cursor.execute(sql, params)

File "/home/l/Desktop/stylizr/local/lib/python2.7/site-packages/django/db/backends/utils.py" in execute
79. return super(CursorDebugWrapper, self).execute(sql, params)

File "/home/l/Desktop/stylizr/local/lib/python2.7/site-packages/django/db/backends/utils.py" in execute
64. return self.cursor.execute(sql, params)

File "/home/l/Desktop/stylizr/local/lib/python2.7/site-packages/django/db/utils.py" in __exit__
95. six.reraise(dj_exc_type, dj_exc_value, traceback)

File "/home/l/Desktop/stylizr/local/lib/python2.7/site-packages/django/db/backends/utils.py" in execute
64. return self.cursor.execute(sql, params)

Exception Type: IntegrityError at /comment/
Exception Value: null value in column "post_comment_id" violates not-null constraint
DETAIL: Failing row contains (22, asda, 2016-08-05 17:18:07.513423+00, 1, null).

Answer

You can't assign the user to comment_user_id because it expects an integer. Either of the following would work:

obj.comment_user_id = self.request.user.id

obj.comment_user = self.request.user