IntegrityError : yonetim_ders.ogretim_elemani_id may not be NUL - django

My models.py:
from django.db import models
class OgretimElemani(models.Model):
adi = models.CharField(max_length=50)
soyadi = models.CharField(max_length=50)
telefonu = models.CharField(max_length = 10 , blank=True)
e_posta_adresi = models.EmailField(blank=True)
def __unicode__(self):
return '%s %s' % (self.soyadi,self.adi)
class Ders(models.Model):
kodu = models.CharField(max_length=10)
adi = models.CharField(max_length=50)
ogretim_elamani = models.ForeignKey(OgretimElemani)
tanimi = models.CharField(max_length=1000,blank = True)
def __unicode__(self):
return '%s %s %s' % (self.kodu,self.adi,self.ogretim_elamani)
class Ogrenci(models.Model):
numarasi = models.IntegerField()
adi = models.CharField(max_length=50)
soyadi = models.CharField(max_length=50)
aldigi_dersler = models.ManyToManyField(Ders)
def __unicode__(self):
return '%s %s %s' % (self.soyadi,self.adi,self.aldigi_dersler)
Django shell :
>>>ders1=Ders(kodu='KIM101', adi='Kimya-1')
>>>ders1.ogretim_elemani=OgretimElemani[0]
>>>ders1.save()
IntegrityError : yonetim_ders.ogretim_elemani_id may not be NULL

You must assign a OgretimElemani instance that has already been saved to the database.
For example, the following should work.
>>> ders1 = Ders(kodu='KIM101', adi='Kimya-1'
>>> ogretim_elemani = OgretimElemani.objects.all()[0] # fetch the first one from the database
>>> ders1.ogretim_elemani = ogretim_elemani
>>>ders1.save()
Your example is not very clear because you use OgretimElemani[0]. You shouldn't reuse the variable name OgretimElemani, it makes the code confusing.

Related

[django]Automatize changing value reach at my value

Question
If istek.yorumlar_set.all reach at Istek.hedef I want change Istek.publish value to false
But, How do this is :D
If yours want to other models, i do upload
Model file :
class Istek(models.Model):
publish = models.BooleanField(default=True)
baslik = models.CharField(max_length=50)
zaman = models.DateTimeField(auto_now_add=True,editable=False)
kime = models.CharField(max_length=100)
sebep = models.CharField(max_length=30)
aciklama = models.TextField(max_length=500)
hangidua = models.ForeignKey(Dualar)
slug = models.SlugField(unique=True,editable=False)
hedef = models.IntegerField(help_text="Toplam da kaƧ dua istiyorsunuz : ")
def __str__(self):
return self.baslik
def save(self,*args , **kwargs):
self.slug = slugify(self.baslik)
super(Istek,self).save()
class Yorumlar(models.Model):
isim = models.CharField(max_length=50)
email = models.EmailField(max_length=50,null=True,blank=True)
websitesi = models.URLField(max_length=50,null=True,blank=True)
yorum = models.TextField()
dua = models.ForeignKey(Istek)
zaman = models.DateTimeField(auto_now_add=True)
def __unicode__(self):
return self.yorum
def __str__(self):
return self.isim+" : " +self.websitesi
class Meta:
ordering = ['zaman']
I'm not sure I understand your question. Is this what you want to achieve?
class Istek(models.Model):
...
def save(self,*args , **kwargs):
if self.yorumlar_set.count() > self.hedef:
self.publish = False
...
I'm solved this problem.Used django.signals.
Here code:
#receiver(post_save,sender=Yorumlar)
def change_true_or_false(instance,created,**kwargs):
instance.dua.toplamdua += 1
if instance.dua.toplamdua > instance.dua.hedef:
instance.dua.publish = False
instance.dua.save()
else:
instance.dua.save()

Django ValueError when trying to save ManyToMany Values from a Form

I get the error "" needs to have a value for field "dataset" before this many-to-many relationship can be used." when trying to assign values to a ManyToMany field in my views. I've looked at many related questions here on SO that say I must save my Dataset object first. I think I am doing that...what is going wrong?? My database already contains four Subject items.
models.py
class Subject(TimeStampedModel):
subject_type = models.CharField(max_length=128, blank=False)
def __unicode__(self):
return self.subject_type
class Dataset(TimeStampedModel):
dataset_id = models.CharField(max_length=256)
dataset_doi = models.CharField(max_length=15)
dataset_name = models.CharField(max_length=256, blank=False)
dataset_description = models.TextField(blank=False)
lab = models.CharField(max_length=256, blank=False)
biological_sample = models.CharField(max_length=256, blank=False)
subject_type = models.ManyToManyField('Subject', related_name='datasets', blank=True)
date_collected = models.DateField(blank=True)
collection_facility = models.ManyToManyField('CollectionFacility', related_name='datasets', blank=True)
processing_notes = models.TextField(blank=True)
release_date = models.DateField()
release_asap = models.BooleanField()
pdb_code = models.CharField(max_length=256, blank=True)
publication_link = models.URLField(blank=True)
def create_name(self):
self.dataset_name = "%s %s" % (self.biological_sample, self.lab)
def save(self, *args, **kwargs):
self.dataset_id = self.id
def __unicode__(self):
return "%s : %s" % (self.dataset_name, self.dataset_id)
forms.py RegistrationForm:
class RegistrationForm(forms.Form):
subject_type = forms.ModelMultipleChoiceField(
label="Subject",
queryset = Subject.objects.all(),
widget=forms.CheckboxSelectMultiple(),
required = True,
)
views.py
def create_registration(form):
dataset = Dataset()
dataset.DOI = "preUpload"
dataset.lab = form.cleaned_data['lab']
dataset.biological_sample = form.cleaned_data['sample']
dataset.resource_type = form.cleaned_data['dataset_type']
dataset.dataset_description = form.cleaned_data['dataset_description']
dataset.date_collected = form.cleaned_data['date_collected']
dataset.release_date = form.cleaned_data['release_date']
dataset.release_asap = form.cleaned_data['release_asap']
if form.cleaned_data['pdb_code']:
dataset.pdb_code = form.cleaned_data['pdb_code']
if form.cleaned_data['publication_link']:
dataset.publication_link = form.cleaned_data['publication_link']
dataset.create_name()
dataset.save() # I don't think this save is working?
subjects = form.cleaned_data['subject_type']
dataset.subject_type = [x for x in subjects]
for facility in form.cleaned_data['facility']
dataset.collection_facility.add(facility)
dataset.save()
return dataset
def registration_submit(request):
registration_form = RegistrationForm(request.POST)
if registration_form.is_valid():
registration = create_registration(registration_form)
.......
You forgot to call the original save() in the overriden Dataset.save() method.
def save(self, *args, **kwargs):
self.dataset_id = self.id
super(Dataset, self).save(*args, **kwargs)

How can I remove duplicate objects in an order_by query?

>>> a = group.objects.order_by('groupname')
>>> print a
[<group: beginner 593785332>, <group: beginner 903647323>, <group: blbrz 229225098>]
I don't want to have objects with similar goupname, I want to have distinct groupname for each object:
[<group: beginner 593785332>, <group: blbrz 229225098>]
What can I do?
from django.db import models
class accounts(models.Model):
twitterid = models.IntegerField()
credit = models.IntegerField()
activate = models.TextField()
ban = models.TextField(blank=True)
others = models.TextField()
def __unicode__(self):
return u'%s' % (self.twitterid)
class Meta:
ordering = ['twitterid']
class group(models.Model):
groupname = models.TextField()
accounts=models.ForeignKey(accounts)
def __unicode__(self):
return u'%s %s' % (self.groupname, self.accounts)
If your database backend were PostgreSQL, you could do it with a queryset:
a = group.objects.order_by('groupname').distinct('groupname')
Unfortunately you are using SQLite, so you would preferably do it in python :
a = group.objects.order_by('groupname')
groupnames = set()
b = []
for item in a:
if a.groupname not in groupnames:
b.append(a)
groupnames.add(a.groupname)
a = b

Choose object and then another object related to this

It's quite hard for me to explain what i need with words so I here is some code:
class Configuration(models.Model):
name = models.CharField(max_length=250)
firmware_version = models.ForeignKey(FirmwareVersion)
devices_amount = models.PositiveIntegerField()
def __unicode__(self):
return unicode(self.name)
class Firmware(models.Model):
name = models.CharField(max_length=250)
circuit_model = models.ForeignKey(Versiiplates)
def __unicode__(self):
return unicode(self.name)
class FirmwareVersion(models.Model):
firmware = models.ForeignKey(Firmware)
version = models.CharField(max_length=100)
file = models.FileField(upload_to="firmware/")
upload_date = models.DateField(default = datetime.date.today())
notes = models.TextField(max_length=2500, null=True, blank=True)
def __unicode__(self):
return u'%s %s' % (self.firmware.__unicode__(), self.version)
Is there any way to choose in admin change-form for Configuration the Firmware first and then any FirmwareVersion related to it?
It's really simple to implement this behavior with django-smart-selects. In my case Configuration class should look like this:
class Configuration(models.Model):
name = models.CharField(max_length=250)
firmware = models.ForeignKey(Firmware, related_name="firmware")
firmware_version = ChainedForeignKey(FirmwareVersion, chained_field="firmware", chained_model_field="firmware", show_all="False", auto_choose=True)
devices_amount = models.PositiveIntegerField()
def __unicode__(self):
return unicode(self.name)

Django-models ForeignKey Objects display Field Name instead of Object Values

I am using a ForeignKey called Memberno in My Django models. After entering data in the Members Class, it appears in the other classes as "member object" in the 'memberno' field. For ForeignKey, I am using 'raw_id_fields' as a workaround, but for normal fields and even 'filter_horizontal' , each memberno value is displayed as "member object". I would like the values to appear as they are in the member class i.e. 1, 2, ...
from django.db import models
# Create your models here.
class Members(models.Model):
DESIGNATION_CHOICES=(
('ADM', 'Administrator'),
('OFF', 'Club Official'),
('MEM', 'Ordinary Member'),
)
memberno = models.AutoField(primary_key=True)
fname = models.CharField(max_length=15)
sname = models.CharField(max_length=15)
onames = models.CharField(max_length=30, blank=True)
email = models.EmailField()
phoneNumber = models.CharField(max_length=15)
regNo = models.CharField(max_length=15)
designation = models.CharField(max_length=3,choices=DESIGNATION_CHOICES)
image = models.ImageField(max_length=100,upload_to='photos/%Y/%m/%d', blank=True, null=True)
course = models.CharField(max_length=30, blank=True, null=True)
def __unicode__(self):
return u'%s %s %s' % (self.fname, self.sname, self.memberno)
def get_absolute_url(self):
return '%s%s/%s' % (settings.MEDIA_URL, settings.ATTACHMENT_FOLDER, self.id)
def get_download_url(self):
return '%s%s/%s' % (settings.MEDIA_URL, settings.ATTACHMENT_FOLDER, self.name)
class Security(models.Model):
memberno = models.ForeignKey(Members, unique=True)
username = models.CharField(max_length=30, primary_key=True)
password = models.CharField(max_length=70)
def __unicode__(self):
return u'%s %s %s' % (self.username, self.password, self.memberno)
class Subscriptions(models.Model):
memberno = models.ForeignKey(Members)
receiptNo = models.CharField(max_length=30, primary_key=True)
type = models.CharField(max_length=50)
date = models.DateField()
amount = models.FloatField(max_length=99)
def __unicode__(self):
return u'%s %s %s' % (self.receiptno, self.type, self.memberno)
class events(models.Model):
eventName = models.CharField(max_length=25)
eventID = models.AutoField(primary_key=True)
details = models.TextField()
attendanceFee = models.FloatField(max_length=99)
date = models.DateField()
memberno = models.ManyToManyField(Members)
def __unicode__(self):
return u'%s %s %s' % (self.eventName, self.eventID, self.memberno)
The admin interface appears to use __str__() to determine the display of a model. I make it a habbit to always define both __unicode__() and __str__() when I create a model. For example:
class Activity(models.Model):
activity_code = models.ForeignKey(ActivityCode)
note = models.TextField(blank=True)
def __str__(self):
return "(%s) %s" % (self.activity_code.short, self.note)
def __unicode__(self):
return u'(%s) %s' % (self.activity_code.short, self.note)
Update:
It looks as though your def __unicode__(self) is not indented properly in your code. As a result it is not a part of your class, and is not being used. Indenting is very important in Python.
I am not sure I understand your question completely, but have you defined a unicode method for your models?