We have a model called Column
, and we want user to be able to create Table
model based on Column
model fields he created, we successfully do that using the method below:
def create_table(request):
columns = Column.objects.filter(user=request.user)
fields = {}
for column in columns:
if column.field_type.data_type == 'number':
fields[column.name] = forms.IntegerField()
elif column.field_type.data_type == 'character':
fields[column.name] = forms.CharField(max_length=20)
elif column.field_type.data_type == 'decimal':
fields[column.name] = forms.DecimalField(max_digits=20, decimal_places=10)
elif column.field_type.data_type == 'image':
fields[column.name] = forms.ImageField()
elif column.field_type.data_type == 'boolean':
fields[column.name] = forms.BooleanField()
elif column.field_type.data_type == 'date':
fields[column.name] = forms.DateField()
TableForm = type('TableForm', (forms.Form,), fields)
if request.method == 'POST':
form = TableForm(request.POST, request.FILES)
if form.is_valid():
table = Table()
table.user = user=request.user
for column in columns:
setattr(table, column.name, form.cleaned_data[column.name])
table.save()
return redirect('Table')
else:
form = TableForm()
return render (request, 'create_table.html', {'form':form})
As you can see our view, our users can create Table
model based on a Column
model fields they created, but when the form is submitted, the value created from TableForm
is null in the database, instead of showing us the object of the Table
model created by a user, it is shown nothing, how can we solve this problem?
the models:
class Column(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
list_of_album = models.ForeignKey(Album, on_delete=models.CASCADE)
name = models.CharField(max_length=20, blank=True, null=True)
field_type = models.ForeignKey(Type, on_delete=models.CASCADE, blank=True, null=True)
def __str__(self):
return str(self.name)
class Table(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
number = models.IntegerField(blank=True, null=True)
decimal = models.DecimalField(max_digits=20, decimal_places=10, blank=True, null=True)
image = models.ImageField(upload_to='table-image', blank=True, null=True)
character = models.CharField(max_length=500, blank=True, null=True)
check_box = models.BooleanField(blank=True, null=True)
date = models.DateField(blank=True, null=True)