IntegrityError using q.save(): may not be NULL - django

I'm not sure why I'm getting the error. Here are the views and clesses
from polls.models import Word, Results
def detail(request):
q = Word(type="How do you like")
q.save()
Word.objects.get(pk=1)
q.score_set.create(score=5)
q.score_set.create(score=4)
q.score_set.create(score=3)
q.score_set.create(score=2)
q.score_set.create(score=1)
return render_to_response('/$')
Models.py
from django.db import models
class Word(models.Model):
type = models.CharField(max_length=200)
def __unicode__(self):
return self.type
class Results(models.Model):
word = models.ForeignKey(Word)
score = models.IntegerField()
def __unicode__(self):
return self.score
Error:
IntegrityError at /
polls_word.score may not be NULLRequest Method: GET
Request URL: Django Version: 1.4.1
Exception Type: IntegrityError
Exception Value: polls_word.score may not be NULL
Exception Location: /home/oveledar/.virtualenvs/django/lib/python2.6/site-packages/django/db/backends/sqlite3/base.py in execute, line 337
Python Executable: /home/oveledar/.virtualenvs/django/bin/python
Python Version: 2.6.6
Python Path: ['/home/oveledar/django/mysite',
'/home/oveledar/.virtualenvs/django/lib/python2.6/site-packages/setuptools-0.6c11-py2.6.egg',
'/home/oveledar/.virtualenvs/django/lib/python2.6/site-packages/pip-1.0.2-py2.6.egg',
'/home/oveledar/.virtualenvs/django/lib64/python26.zip',
'/home/oveledar/.virtualenvs/django/lib64/python2.6',
'/home/oveledar/.virtualenvs/django/lib64/python2.6/plat-linux2',
'/home/oveledar/.virtualenvs/django/lib64/python2.6/lib-tk',
'/home/oveledar/.virtualenvs/django/lib64/python2.6/lib-old',
'/home/oveledar/.virtualenvs/django/lib64/python2.6/lib-dynload',
'/usr/lib/python2.6',
'/usr/lib64/python2.6',
'/home/oveledar/.virtualenvs/django/lib/python2.6/site-packages']

You table structure incorrect, you need:
class Results(models.Model):
word = models.ForeignKey(Word)
score = models.IntegerField(blank=True, null=True)
after, remove this table and run command:
python manange.py syncdb
#blank option it`s required or not this node for form validate
#null option it`s for you database (Null true or false)

Related

How to set 'A' model's ImageField from 'B' model's ImageField Using Django signal(Pre_save,Post_save)

Here Is my Model
from django.db import models
from django.utils import timezone
# Create your models here.
class send_message_model(models.Model):
mail = models.EmailField(max_length=100)
msg = models.TextField(max_length=500)
class projectmodel(models.Model):
project_name = models.CharField(max_length=100)
project_url = models.URLField()
project_desc = models.CharField(max_length=200)
project_short_desc = models.CharField(max_length=100,default='')
project_date = models.DateField(default=timezone.now)
rate = models.IntegerField()
project_thumb = models.ImageField(blank=True)
def __str__(self):
return f'{self.id}'
class projectimage(models.Model):
project_id = models.ForeignKey(projectmodel,on_delete=models.CASCADE,blank=True,null=True)
project_pic = models.FileField(upload_to = 'imgs/')
time = models.DateTimeField( auto_now=False, auto_now_add=True)
def __str__(self):
return f"{self.project_id}"
I Want to set the ProjectImage's image to my projectmodel imageField,while saving projectmodel
i have tried this,
from django.contrib.auth.models import User
from Portfolio.models import projectimage,projectmodel
from django.db.models.signals import post_save,pre_save
from django.dispatch import receiver
def do_something(sender,instance,**kwargs):
print("User Saved")
print(sender)
print(instance)
# print(created)
pre_save.connect(do_something,sender = User)
#receiver(pre_save,sender=projectmodel)
def add_image(sender,instance,**kwargs):
if not instance.project_thumb:
print("Image Empty")
instance_id = instance.id
img = projectimage.objects.filter(id = instance_id).order_by('id')[0]
print(img)
print(type(img))
thumb = projectmodel.objects.filter(id = instance_id)
thumb_save = thumb(project_thumb = img)
thumb_save.save()
else:
print("Image here")
But its not working,
showing this error,
TypeError at /admin/Portfolio/projectmodel/4/change/
'QuerySet' object is not callable
Request Method: POST
Request URL: http://127.0.0.1:8000/admin/Portfolio/projectmodel/4/change/
Django Version: 3.1.4
Exception Type: TypeError
Exception Value:
'QuerySet' object is not callable
Exception Location: C:\Django Python\SecondPortfolio\Portfolio\signals.py, line 27, in add_image
Python Executable: C:\Program Files\Python38\python.exe
Python Version: 3.8.2
Python Path:
['C:\\Django Python\\SecondPortfolio',
'C:\\Program Files\\Python38\\python38.zip',
'C:\\Program Files\\Python38\\DLLs',
'C:\\Program Files\\Python38\\lib',
'C:\\Program Files\\Python38',
'C:\\Users\\Rak1b\\AppData\\Roaming\\Python\\Python38\\site-packages',
'C:\\Program Files\\Python38\\lib\\site-packages']
Server time: Tue, 19 Jan 2021 20:39:51 +0000
After Doing the solution
there's a new problem occured
AttributeError at /admin/Portfolio/projectmodel/1/change/
'projectimage' object has no attribute '_committed'
Request Method: POST
Request URL: http://127.0.0.1:8000/admin/Portfolio/projectmodel/1/change/
Django Version: 3.1.4
Exception Type: AttributeError
Exception Value:
'projectimage' object has no attribute '_committed'
Exception Location: C:\Users\Rak1b\AppData\Roaming\Python\Python38\site-packages\django\db\models\fields\files.py, line 305, in pre_save
Python Executable: C:\Program Files\Python38\python.exe
Python Version: 3.8.2
Python Path:
['C:\\Django Python\\SecondPortfolio',
'C:\\Program Files\\Python38\\python38.zip',
'C:\\Program Files\\Python38\\DLLs',
'C:\\Program Files\\Python38\\lib',
'C:\\Program Files\\Python38',
'C:\\Users\\Rak1b\\AppData\\Roaming\\Python\\Python38\\site-packages',
'C:\\Program Files\\Python38\\lib\\site-packages']
Server time: Tue, 19 Jan 2021 22:31:15 +0000
It will be very helpful ,if anyoone give me the idea,how to set the image on another model
filter() returns a QuerySet and use img.project_pic instead img
Best use get().
from django.core.files.base import ContentFile
...
def add_image(sender,instance,**kwargs):
...
thumb = projectmodel.objects.get(id=instance_id)
thumb.project_thumb.save(img.project_pic.name, ContentFile(img.project_pic.read()), save=False)
thumb.save()
OR
...
def add_image(sender,instance,**kwargs):
...
thumb = projectmodel.objects.get(id=instance_id)
thumb.project_thumb = img.project_pic
thumb.save()
If you want to use filter() than also have to use update()
thumb.update(...)

Embedded Field: must be instance of Model: <class 'django.db.models.base.Model'>

I tried to do a dummy seeder for the Entry model (extended from djongo model) with the object manager but I got an error while saving.
Error: must be instance of Model: <class 'django.db.models.base.Model'>`
Python script
<The complete python script used to produce the issue.>
from djongo import models
from django.core.management.base import BaseCommand, CommandError
class Blog(models.Model):
name = models.CharField(max_length=100)
tagline = models.TextField()
class Meta:
abstract = True
class Entry(models.Model):
_id = models.ObjectIdField()
blog = models.EmbeddedField(
model_container=Blog
)
headline = models.CharField(max_length=255)
objects = models.DjongoManager()
def build_dummy_entry():
e = Entry.objects.create(
headline='h1',
blog={
'name': 'b1',
'tagline': 't1'
})
g = Entry.objects.get(headline='h1')
assert e == g
e = Entry()
e.blog = {
'name': 'b2',
'tagline': 't2'
}
e.headline = 'h2'
e.save()
class Command(BaseCommand):
help='Create a preset dummy entry'
def handle(self, *args, **options):
try:
build_dummy_entry()
self.stdout.write(self.style.SUCCESS(f'Successfully created dummy blog'))
except Exception as e:
raise CommandError(f'{e}')
Traceback
CommandError: Value: {'name': 'b1', 'tagline': 't1'} must be instance of Model: <class 'django.db.models.base.Model'>
---EDIT SOLUTION---
I was using the 1.3.1.
I check the version 1.3.2 and 1.3.3 and it looks like these version contains the fix for the instantiation error.
As error says, you should use model instance, but you're using dict.
def build_dummy_entry():
e = Entry.objects.create(
headline='h1',
blog=Blog(**{'name': 'b2', 'tagline': 't2'}),
)
...

django Markdown problems

Django:1.11.5
Python:3.5.2
Markdown 2.6.9 https://pypi.python.org/pypi/Markdown/
views.py
from django.shortcuts import render
from .models import Post
import markdown
def home(request):
Post_list = Post.objects.all().order_by('-pub_date')
Post.content = markdown.markdown(Post.content)
return render(request, 'home.html',
context={'Post_list':Post_list})
# Create your views here.
models.py
from django.db import models
import django.utils.timezone as timezone
class Category(models.Model):
name = models.CharField(max_length=100)
class Post(models.Model):
title = models.CharField(max_length=256)
content = models.TextField(blank = True, null = True)
pub_date = models.DateTimeField(default=timezone.now)
update_time = models.DateTimeField(auto_now=True)
category = models.ForeignKey(Category)
# Create your models here.
Error message
AttributeError at /
'DeferredAttribute' object has no attribute 'strip'
Request Method: GET
Request URL: http://www.balinzuoqi.com/
Django Version: 1.11.5
Exception Type: AttributeError
Exception Value:
'DeferredAttribute' object has no attribute 'strip'
Exception Location: /usr/local/lib/python3.5/dist-packages/markdown/__init__.py in convert, line 355
Python Executable: /usr/bin/python3
Python Version: 3.5.2
Python Path:
['/data/mysite',
'/usr/local/bin',
'/usr/lib/python35.zip',
'/usr/lib/python3.5',
'/usr/lib/python3.5/plat-i386-linux-gnu',
'/usr/lib/python3.5/lib-dynload',
'/usr/local/lib/python3.5/dist-packages',
'/usr/lib/python3/dist-packages']
Do not know where there is a problem.
Remove Post.content = markdown.markdown (Post.content), show normal!
English is not my native language; please excuse typing errors.
You are reading content from and writing content to the Post class, not an instance of the class. You need to iterate through the list and update each instance:
def home(request):
Post_list = Post.objects.all().order_by('-pub_date')
for post in Post_list:
post.content = markdown.markdown(post.content)
return render(request, 'home.html',
context={'Post_list':Post_list})
Whether that is a recommended way of converting Markdown to HTML to pass to a template is another matter. Its been a few years since I've used Django, but that wasn't how it used to be done. However, that is a different question.
Regardless, you were not actually passing any Markdown text to the Markdown parser as you were not using an instance of the class. With the for loop I added above, the Markdown content for each 'Post' is now being passed to the Markdown parser.

Django says it has to be a model instance

I'm using Django 1.3 and South those should be useful information. My problem is that, when saving the form it says:
ValueError at /reportforms/c13
Cannot assign "u'3'": "c13.job" must be a "joblist" instance.
Request Method: POST
Request URL: http://localhost:9000/reportforms/c13
Django Version: 1.3
Exception Type: ValueError
Exception Value: Cannot assign "u'3'": "c13.job" must be a "joblist" instance.
Exception Location: /media/Django/path_env/local/lib/python2.7/site-packages/django/db/models/fields/related.py in __set__, line 331
Python Version: 2.7.3
Any idea what's wrong with this?
models.py
class joblist(models.Model):
job_english = models.CharField(_('Job name in english'), max_length=255, default="")
job_hungarian = models.CharField(_('Job name in hungarian'), max_length=255, default="")
class c13(models.Model):
job = models.ForeignKey(joblist, verbose_name=_('Job'))
forms.py
class C13Form(ModelForm):
job = forms.ChoiceField(choices=[(item.pk, item.job_english) for item in joblist.objects.all()])
class Meta:
model = c13
exclude = ('added_by')
views.py
form = C13Form(request.POST)
if form.is_valid():
new_c13 = c13.objects.create(
job = joblist.objects.get(pk=form.cleaned_data['job']),
year = form.cleaned_data['year'],
needlestick_injuries = form.cleaned_data['needlestick_injuries'],
staff_beginning = form.cleaned_data['staff_beginning'],
staff_end = form.cleaned_data['staff_end'],
working_hours_beginning = form.cleaned_data['working_hours_beginning'],
working_hours_end = form.cleaned_data['working_hours_end'],
added_by = request.user,
)
new_c13.save()
return render_to_response('filled_out.html', {}, context_instance=RequestContext(request))
else:
form = C13Form(request.POST)
return render(request, 'c13.html', { 'form': form })
Maybe you have to use ModelChoiceField, see https://docs.djangoproject.com/en/dev/ref/forms/fields/#django.forms.ModelChoiceField
job = forms.ModelChoiceField(queryset=joblist.objects.all())

Django auth.User in Admininterface: coercing to Unicode: need string or buffer, User found

I'm pretty new to django. I try to use the auth.User object as a foreign key.
My model:
from django.contrib.auth.models import User
(...)
class Entry(models.Model):
(...)
user = models.ForeignKey(User)
date = models.DateTimeField()
def __unicode__(self):
return self.user
When creating a new Entry with a user in admin interface, i get: "coercing to Unicode: need string or buffer, User found"
Exception Type: TypeError
Exception Value: coercing to Unicode: need string or buffer, User
found
Exception
Location: /Library/Python/2.7/site-packages/django/utils/encoding.py
in force_unicode, line 71
What am i missing?
this should work and explain itself
def __unicode__(self):
return unicode(self.user)