Django IntegrityError: UNIQUE constraint failed user.id ( OnetoOneField) - django-models

I want to send data to database. But the error said return Database.Cursor.execute(self, query, params)
django.db.utils.IntegrityError: UNIQUE constraint failed: dashboard_userusulan.ketua_id
[27/Dec/2021 23:46:14] "POST /dashboard/usulan-penelitian/ HTTP/1.1" 500 196035
Im use CreateView and form_valid() to send the data. I want when i click submit button field 'ketua' automatic create current user.
models.py
class UserUsulan(models.Model):
YEAR_CHOICES = [(r,r) for r in range(1984, datetime.date.today().year+1)]
JENIS_PENELITIAN_CHOICE = (
('DASAR', 'Penelitian Dasar'),
('MADYA', 'Penelitian Madya'),
('UTAMA', 'Penelitian Utama'),
)
BIDANG_PENELITIAN_CHOICE = (
('TEKNOLOGI', 'Teknologi'),
('SAINS', 'Sains'),
('PENDIDIKAN', 'Pendidikan'),
('EKONOMI', 'Ekonomi'),
('HUKUM', 'Hukum'),
('MANAJEMEN', 'Manajemen'),
)
TARGET_LUARAN_CHOICE = (
('JURNAL INTERNASIONAL', 'Jurnal Internasional Bereputasi'),
('JURNAL NASIONAL', 'Jurnal Nasional Terakreditasi'),
('PROSIDING INTERNASIONAL', 'Prosiding Internasional'),
('PROSIDING NASIONAL', 'Prosiding Nasional'),
('HKI', 'Hak Kekayaan Intelektual'),
('BUKU','Buku'),
('PRODUK','Produk'),
)
STATUS_USULAN_CHOICE = (
('DITERIMA', 'Diterima'),
('MENUNGGU', 'Menunggu'),
('DITOLAK', 'Ditolak'),
)
SUMBER_DANA_CHOICE = (
('LP3M', 'DIPA LP3M Universitas Mulia'),
)
SKEMA_PENELITIAN_CHOICE = (
('L', 'Lektor'),
('AA', 'Asisten Ahli'),
('TENDIK', 'Tenaga Pengajar'),
)
tahun = models.IntegerField(_('year'), choices=YEAR_CHOICES, default=datetime.datetime.now().year)
judul_penelitian = models.TextField(blank=True)
jenis_penelitian = models.CharField(max_length=16, blank=True, default="", choices=JENIS_PENELITIAN_CHOICE)
tmt_awal = models.DateField(null=True, blank=True)
tmt_akhir = models.DateField(null=True, blank=True)
bidang_penelitian = models.CharField(max_length=10, blank=True, default="", choices=BIDANG_PENELITIAN_CHOICE)
tujuan_sosial_ekonomi = models.TextField(blank=True)
sumber_dana = models.CharField(max_length=30, blank=True, default="", choices=SUMBER_DANA_CHOICE)
skema_penelitian = models.CharField(max_length=15, blank=True, default="", choices=SKEMA_PENELITIAN_CHOICE)
jumlah_dana_usulan = MoneyField(max_digits=14, decimal_places=2, default_currency='IDR')
target_luaran = models.CharField(max_length=23, blank=True, default="", choices=TARGET_LUARAN_CHOICE)
ketua = models.OneToOneField(settings.AUTH_USER_MODEL, related_name='ketua_penelitian', on_delete=models.CASCADE, null=True, blank=True)
anggota = models.ManyToManyField(settings.AUTH_USER_MODEL, related_name='anggota_penelitian')
upload_file = models.FileField(upload_to='Penelitian/', null=True, blank=True)
status_usulan = models.CharField(max_length=8, blank=True, choices=STATUS_USULAN_CHOICE)
jumlah_dana_disetujui = MoneyField(max_digits=14, decimal_places=2, default_currency='IDR', null=True, blank=True)
keterangan_operator = models.TextField(null=True, blank=True)
com_reviewer_1 = models.TextField(null=True, blank=True)
com_reviewer_2 = models.TextField(null=True, blank=True)
views.py
class UserUsulanPenelitian(LoginRequiredMixin, CreateView):
template_name = 'dashboard/usulan-penelitian.html'
form_class = UserUsulanCreatePenelitianForm
success_url = 'dashboard/usulan-penelitian'
def form_valid(self, form):
#fetch user login data and input current user
form.instance.ketua = self.request.user
# form.save()
print(self.request.user)
# message.success(self.request, 'Berhasil Menambahkan Usulan Penelitian')
print('Success Menambahkan Data')
return super().form_valid(form)

Edit ketua field OneToOneField to ForeignKey
ketua = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='ketua_penelitian', on_delete=models.CASCADE, null=True, blank=True)

Related

Please explain the _set.all() method in django>

I have this models and the view for user profile.
class Room(models.Model):
admin = models.ForeignKey(User, on_delete=models.SET_NULL, null=True)
topic = models.ForeignKey(Topic, on_delete=models.SET_NULL, null=True)
group_photo = models.ImageField(null=True, upload_to = 'images/', default='avatar.svg')
name = models.CharField(unique=True, max_length=100)
description = models.TextField(null=True, blank=True)
members = models.ManyToManyField(User, related_name='members', blank=True)
created = models.DateTimeField(auto_now_add=True)
views.py
#login_required(login_url= 'login')
def userprofile(request, pk):
user = User.objects.get(username=pk)
#groups = user.room_set.all()
groups = Room.objects.filter(admin=user)
all_groups = Room.objects.filter(members=user)
return render(request, 'base/profile.html', {'user':user, 'groups':groups, 'all_groups':all_groups})
Please explain how _set.all method filter method are doing the same job.
I don't understand where the room is coming from (there is only (Room) model.
explain the mechanism of user.room_set.all line respect to filter;

filter objects by same value

Hey there i have a Order table which has created_at field, as multiple objects will be created at same date i want to list the objects by date.Such as i want to group the objects by date .Thank you.
#model
class SalesOrder(models.Model):
invoice_id = models.CharField(max_length=50, blank=True, null=True)
code = models.CharField(max_length=50, blank=True, null=True)
amount = models.FloatField(default=0.0, null=True, blank=True)
branch = models.ForeignKey('shop.Branch', on_delete=models.SET_NULL, null=True, blank=True)
customer = models.CharField(max_length=50, null=True, blank=True)
customer_contact = models.CharField(max_length=50, null=True, blank=True)
created_at = models.DateTimeField(auto_now_add=True)
def __str__(self):
return str(self.code)
def get_context_data(self, **kwargs): #View
cxt = super().get_context_data()
cxt['dates'] = SaleOrder.objects.annotate(
count=Count('created_at__date'))
# import pdb;pdb.set_trace()
cxt['form'] = SalesOrderForm(self.request.POST or None)

How To Spanning multi-valued relationships?

Im Try to Catch any data from database with table name is 'UserUsulan'.
I have two field, 'Ketua' and 'Anggota'.
In Ketua Field is ForeignKey from User, and Anggota is ManyToMany Field with relationship from User.
I want to render the data.
if in Ketua Field equal current.user render the data.
and also if current.user in Anggota field i want it render too.
So,
If the current.user is not able in Ketua Field, but able in Anggota Field. Render the Data
If the current.user is not able in Anggota Field, buat able in Ketua Field. Render the Data Too.
How To Solve this problem.
Im read with this documentation Spanning multi-valued relationships . But the Queryset is empty[].
models.py
tahun = models.IntegerField(_('year'), choices=YEAR_CHOICES, default=datetime.datetime.now().year)
judul_penelitian = models.TextField(blank=True)
jenis_penelitian = models.CharField(max_length=16, blank=True, default="", choices=JENIS_PENELITIAN_CHOICE)
tmt_awal = models.DateField(null=True, blank=True)
tmt_akhir = models.DateField(null=True, blank=True)
bidang_penelitian = models.CharField(max_length=10, blank=True, default="", choices=BIDANG_PENELITIAN_CHOICE)
tujuan_sosial_ekonomi = models.TextField(blank=True)
sumber_dana = models.CharField(max_length=30, blank=True, default="", choices=SUMBER_DANA_CHOICE)
skema_penelitian = models.CharField(max_length=15, blank=True, default="", choices=SKEMA_PENELITIAN_CHOICE)
jumlah_dana_usulan = MoneyField(max_digits=14, decimal_places=2, default_currency='IDR')
target_luaran = models.CharField(max_length=23, blank=True, default="", choices=TARGET_LUARAN_CHOICE)
ketua = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='ketua_penelitian', on_delete=models.CASCADE, null=True, blank=True)
anggota = models.ManyToManyField(settings.AUTH_USER_MODEL, related_name='anggota_penelitian')
upload_file = models.FileField(upload_to='Penelitian/', null=True, blank=True)
status_usulan = models.CharField(max_length=8, blank=True, choices=STATUS_USULAN_CHOICE, default='MENUNGGU')
jumlah_dana_disetujui = MoneyField(max_digits=14, decimal_places=2, default_currency='IDR', null=True, blank=True)
keterangan_operator = models.TextField(null=True, blank=True)
com_reviewer_1 = models.TextField(null=True, blank=True)
com_reviewer_2 = models.TextField(null=True, blank=True)
views.py
def get_queryset(self):
queryset = super(UserUsulanPenelitianCreateAndListView, self).get_queryset()
queryset = queryset.filter(ketua=self.request.user,).filter(anggota=self.request.user,)
print(queryset)
return queryset
I Found The Answer, Using Q for the queryset
Import Q
from django.db.models import Q
Using Q in Queryset
def get_queryset(self):
queryset = super(UserUsulanPenelitianCreateAndListView, self).get_queryset()
queryset = queryset.filter(Q(ketua=self.request.user)|Q(anggota=self.request.user)).distinct()
print(queryset)
return queryset

Django models save 2 Foreinkeys to same Model

Following this link and documentation, somehow it still can't save an Object with 2 Foreinkeys.
class Photo(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE, null=True) #User.photo_set.all() returns all Photo objects of the photo
photoURL = models.CharField(max_length=256, null=True)
secondPhoto = models.OneToOneField('self', on_delete=models.PROTECT, null=True, blank=True)
timestamp = models.DateTimeField(auto_now_add=True)
description = models.CharField(max_length=1000, null=True)
is_private = models.BooleanField(default=False)
class Clash(models.Model):
win_photo = models.ForeignKey(Photo,on_delete=models.PROTECT, related_name="wins", null=True)
loss_photo = models.ForeignKey(Photo,on_delete=models.PROTECT, related_name="losses", null=True)
is_private = models.BooleanField(default=False) #we will filter those out for user quality calculations

display existing values of database into formfields

How can i get data from databse(sqllite) into dropdown button and based on selected value retrive all matching values on datagrid or in csv in django
class AnalyzedFile(models.Model):
sha256 = models.CharField(db_column='SHA256', max_length=64, blank=True)
md5 = models.CharField(db_column='MD5', max_length=32, blank=True)
sha1 = models.CharField(db_column='SHA1', max_length=40, blank=True)
filename = models.CharField(db_column='FILENAME', max_length=5000, blank=True)
filelength = models.IntegerField(db_column='FILELENGTH', blank=True, null=True)
filetype = models.CharField(db_column='FILETYPE', max_length=3, blank=True)
fileentropy = models.CharField(db_column='FILEENTROPY', max_length=50, blank=True)
peidsig = models.CharField(db_column='PEIDSIG', max_length=1000, blank=True)
exeinfosig = models.CharField(db_column='EXEINFOSIG', max_length=1000, blank=True)
ssdeepsig = models.CharField(db_column='SSDEEPSIG', max_length=200, blank=True)
digitalsig = models.CharField(db_column='DIGITALSIG', max_length=100, blank=True)
description = models.CharField(db_column='DESCRIPTION', max_length=65000, blank=True) # Field name made lowercase.
analysis = models.CharField(db_column='ANALYSIS', max_length=65000, blank=True)
class Meta:
managed = False
db_table = 'ANALYZED_FILE'

Resources