I have a column list. I'm trying to update one row from that list. After i select a row, i am trying to update it. After i select a row, i get one of the parameters which is table_id. table_id is defined in model.py and forms.py . I show that table_id as modelchoicefield in djangoproject but i can't initiate my instance value as modelchoicefield.
updateView.py
from django.shortcuts import render,redirect,get_object_or_404
from django.urls import reverse
from django.contrib import messages
from Columns_definition.forms import ColumnsDefinitionsForms
from Columns_definition.models import sysColumns
def update_table(request,id):
column_data = get_object_or_404(sysColumns, id = id)
columns_form = ColumnsDefinitionsForms(request.POST or None, request.FILES or None, instance = column_data)
if columns_form.is_valid():
aciklama = request.POST.get('tabloid')
columns_form.save()
messages.info(request, "\'" + column_data.name + "\'" + "{}".format((": is updated")))
return redirect("Columns_definition:columns_def")
context = {
"columns_form":columns_form,
"id":id,
}
return render(request, 'columnsCreate.html', context)
forms.py
from django import forms
from Columns_definition.models import sysColumns
from Utilities.custom_enum import DataTypes
from Table_definition.models import sysTables
class ColumnsDefinitionsForms(forms.ModelForm):
datatype = forms.ChoiceField(choices=DataTypes, required=False, label='Alan Veri Tipi' , widget=forms.Select(attrs={
'placeholder': '','class':'form-control select-access-open select2-hidden-accessible popUp'
}))
def __init__(self, *args, **kwargs):
super(ColumnsDefinitionsForms, self).__init__(*args, **kwargs)
self.fields['datatype'].choices.insert(0, ('','---------' ) )
tabloid = forms.ModelChoiceField(queryset=sysTables.objects.all(),
empty_label=None,
widget=forms.Select(attrs={
'class': 'form-control select-access-open select2-hidden-accessible'
}))
class Meta:
model = sysColumns
fields = [ 'tabloid',
'name',
'alias' ,
'aliasLng1' ,
'aliasLng2' ,
'visible',
'datatype',
'datalength',
'comboid' ,
'reftype'
]
widgets = {
'name':forms.TextInput(attrs={'placeholder': '','class':'rc-form-control-input form-control-user'}),
'alias': forms.TextInput(attrs={'placeholder': '','class':'rc-form-control-input form-control-user'}),
'aliasLng1': forms.TextInput(attrs={'placeholder': '','class':'rc-form-control-input form-control-user'}),
'aliasLng2': forms.TextInput(attrs={'placeholder': '','class':'rc-form-control-input form-control-user'}),
'visible': forms.CheckboxInput(attrs={'placeholder': '','class':'form-check-input','id':'visible'}),
'datalength':forms.NumberInput(attrs={'placeholder': '','id':'datalength','class':'form-control rc-form-control-input form-control-user'}),
'comboid': forms.NumberInput(attrs={'placeholder': '','id':'comboid','class':'form-control rc-form-control-input form-control-user'}),
'reftype': forms.NumberInput(attrs={'placeholder': '','id':'reftype','class':'form-control rc-form-control-input form-control-user'}),
}
models.py
sysColumns
from django.db import models
import uuid
from django.utils.translation import ugettext_lazy as _
from Table_definition.models import sysTables
from model_utils import Choices
DataTypes=(
(0 , 'String'),
(1 , 'Numeric'),
(2 ,'Currency' ),
(3 ,'DateTime' ),
(4 ,'Yes/No' ),
(5 ,'UUID' ),
(6 ,'Combo' ),
(7 ,'Image / Binary' ),
)
class sysColumns(models.Model):
class Meta:
db_table = 'sysColumns'
id = models.UUIDField(primary_key=True,default=uuid.uuid4, editable=False)
tableid=models.ForeignKey(sysTables, on_delete=models.CASCADE)
name = models.CharField(_('Alan Adı'),max_length=64,null=False, blank=False)
alias = models.CharField(_('Alan Açıklaması (Yerel Dil)'),max_length=100,null=False, blank=False)
aliasLng1 = models.CharField(_('Alan Açıklaması (Dil-1)'),max_length=100,null=False, blank=False)
aliasLng2 = models.CharField(_('Alan Açıklaması (Dil-2)'),max_length=100,null=True,blank=True)
visible = models.BooleanField(_('Görünüm'),null=True,blank=True)
datatype = models.IntegerField(_('Alanın Veri Tipi'),null=True,blank=True,choices=DataTypes)
datalength = models.IntegerField(_('Alanın Uzunluğu'),null=True,blank=True)
comboid = models.IntegerField(_('Kombo Değeri'),null=True,blank=True)
reftype =models.IntegerField(_('Referans Tipi'),null=True,blank=True)
def __str__(self):
return self.name
SysTables - Models.py
from django.db import models
import uuid
from django.utils.translation import ugettext_lazy as _
class sysTables(models.Model):
class Meta:
db_table = 'sysTables'
id = models.UUIDField(primary_key=True,default=uuid.uuid4, editable=False)
name = models.CharField(_('Tablo Adı'),max_length=64,null=False, blank=False)
alias = models.CharField(_('Tablo Açıklaması (Yerel Dil)'),max_length=100,null=False, blank=False)
aliasLng1 = models.CharField(_('Tablo Açıklaması (Dil-1)'),max_length=100,null=False, blank=False)
aliasLng2 = models.CharField(_('Tablo Açıklaması (Dil-2)'),max_length=100,null=True,blank=True)
chistory = models.BooleanField(_('Yeni Kayıt Tarihçesi '),null=True,blank=True)
rhistory = models.BooleanField(_('Kayıt Okuma Tarihçesi'),null=True,blank=True)
uhistory = models.BooleanField(_('Kayıt Güncelleme Tarihçesi'),null=True,blank=True)
dhistory = models.BooleanField(_('Kayıt Silme Tarihçesi '),null=True,blank=True)
log = models.BooleanField(_('Kayıt Logu'),null=True,blank=True)
def __str__(self):
return self.alias
columnsCreate.html
<div class="row">
<div class="col-md-12">
<div class="card">
<div class="card-header">
<div class="row">
<div class="col-md-10 offset-md-1">
<div class="header-elements-inline">
{% if islem_turu == "detay" %}
<legend class="text-uppercase font-size-sm font-weight-bold">{% trans " Kolon Detay Kartı " %}</legend>
{% elif islem_turu == "guncelle"%}
<legend class="text-uppercase font-size-sm font-weight-bold">{% trans " Kolon Güncelle Kartı " %}</legend>
{% else %}
<legend class="text-uppercase font-size-sm font-weight-bold">{% trans " Kolon Oluşturma Kartı " %}</legend>
{% endif %}
</div>
</div>
</div>
</div>
<div class="card-body">
<div class="row">
<div class="col-md-10 offset-md-1">
<form method="post">
{% csrf_token %}
{% for field in columns_form %}
<div class="form-group row">
<label class="col-lg-3 col-form-label"> {{field.label}}
</label>
<div class="col-lg-9">
{{ field }}
</div>
</div>
{% endfor %}
{% if islem_turu == "detay" %}
{% elif islem_turu == "guncelle" %}
<button class="btn btn-info btn-md" style="margin:.5em; width:8em; float:right; color: #333;background: #41bd1e;" type="submit">
<i class="icon-floppy-disk " style="color: #333; background:#41bd1e;"></i> {% trans "Kaydet" %}
</button>
{% else %}
<button class="btn btn-info btn-md" style="margin:.5em; width:8em; float:right; color: #333;background: #41bd1e;" type="submit">
<i class="icon-floppy-disk " style="color: #333; background:#41bd1e;"></i> {% trans "Kaydet" %}
</button>
<a href="{% url 'Columns_definition:columns_def' %}" class="btn btn-danger btn-md"
style="margin:.5em; width:8em; float:right;">
<i class="fas fa-close"></i> {% trans "İptal" %}
</a>
{% endif %}
</div>
</form>
</div>
</div>
</div>
Edit: When you check (1) and after pressing update button then in picture (2) you can see that i get comboid from (1) in (2) as my selected modelchoicefield. But in (3) my tableid doesn't match up with my tableid in (4). I can't get in (4) what is selected previously on (3). Instead i get my first element of tableid values from database in modelchoicefield.
I expect to select field of table_id in column_data and send it to initial value and want to select it as default modelchoicefield. I made a a lot of examples in my other projects but can't work it out on this one. Thanks for your help in advance.
I Think, cause of problem is variable name in forms.py. in Forms.py tabloid should be defined as tableid. Because of your project use modelform library in forms.py. Object in forms and models must match in Django project.
Best Regards,