Невозможно сохранить представление создания в базе данных, так как запрос POST говорит, что все поля обязательны для заполнения, даже если перед отправкой данные упоминаются в полях формы.
Все поля данных предоставляются перед отправкой и данные раскрывающегося списка и флажки предварительно заполняются в соответствии с данными контекста.
models.py
class RawMaterial(models.Model):
rm_code = models.CharField(max_length = 10, unique = True)
rm_name = models.CharField(max_length = 100, unique = True)
rm_unit = models.ForeignKey(RMUnit, blank = False, on_delete = models.CASCADE)
rm_category = models.ForeignKey(RMCategory, on_delete = models.CASCADE)
rm_rate = models.FloatField()
rm_tax = models.FloatField(null = True)
rm_price = models.FloatField(blank = False)
rm_vendor = models.ManyToManyField(Vendor)
rm_store_issue_price = models.FloatField(null = True)
rm_dept_use = models.ManyToManyField(Department)
def __str__(self):
return self.rm_name
def get_absolute_url(self):
return reverse('rm-create', kwargs=None)
views.py
class RawMaterialCreateView(CreateView):
model = RawMaterial
fields = '__all__'
template_name = 'rm_registration.html'
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['itemcode'] = generateCode(RawMaterial, 'RM', 'rm_code')
context['categories'] = RMCategory.objects.all()
context['units'] = RMUnit.objects.all()
context['departments'] = Department.objects.all()
context['vendors'] = Vendor.objects.all()
return context
def form_valid(self, form):
itemcode = self.instance.itemcode
print("Item Code is : " + itemcode)
instance = form.save(commit=False)
instance.save()
return super(RawMaterialCreateView, self).form_valid(form)
регистрация. html
<form method="POST" action="">
{% csrf_token %}
<div class="row">
<div class="form-group col-6">
<label for="rm_code">Item Code : </label>
<input type="text" class="form-control form-control-sm" id="rm_code" value = "{{ itemcode }}" readonly="readonly" placeholder="Item Code">
</div>
<div class="form-group col-6">
<label for="rm_category">Item Category : </label>
<select class="form-control form-control-sm" id="rm_category">
{% for catname in categories %}
<option value = "{{ catname.pk }}">{{ catname }}</option>
{% endfor %}
</select>
</div>
</div>
<div class="row">
<div class="form-group col-6">
<label for="rm_name">Item Name : </label>
<input type="text" class="form-control" id="rm_name" value = "{{ item.name }}" placeholder="Item Name">
</div>
<div class="form-group col-6">
<label for="rm_unit">Unit of Measurement : </label>
<select class="form-control form-control-sm" id="rm_unit">
{% for u in units %}
<option value = "{{ u.pk }}">{{ u }}</option>
{% endfor %}
</select>
</div>
</div>
<div class="row">
<div class="form-group col-6">
<label for="rm_rate">Rate : </label>
<input type="number" step="0.01" class="form-control" id="rm_rate" value = "{{ item.rate }}" placeholder="Item Rate">
</div>
<div class="form-group col-6">
<label for="rm_tax">Tax : </label>
<div class="input-group">
<input type="number" step="0.01" id = "rm_tax" class="form-control" aria-label="" value = "{{ item.tax }}" placeholder="Tax Rate">
<div class="input-group-append">
<span class="input-group-text">%</span>
</div>
</div>
</div>
</div>
<div class="row">
<div class="form-group col-6">
<label for="rm_price">Price : </label>
<input type="number" step="0.01" class="form-control" id="rm_price" value = "{{ item.price }}" placeholder="Item Price">
</div>
<div class="form-group col-6">
<label for="rm_store_issue_price">Store Issue Price : </label>
<input type="number" step="0.01" class="form-control" id="rm_store_issue_price" value = "{{ item.storeprice }}" placeholder="Store Issue Price">
</div>
</div>
<div class="row">
<div class="form-group col-2">
<label>Select Department : </label>
</div>
<div class="form-group col-10">
{% for deptname in departments %}
<div class="form-check form-check-inline">
<input class="form-check-input" type="checkbox" id="rm_dept_use" value="{{ deptname.pk }}">
<label class="form-check-label" for="dept">
{{ deptname }}
</label>
</div>
{% endfor %}
</div>
</div>
<div class="row">
<div class="form-group col-md-6 col-lg-6 col-sm-6">
<label>Select Vendors : </label>
<select id="rm_vendor" data-style="btn-default" class="selectpicker form-control" multiple data-max-options="">
{% for vendor in vendors %}
<option value="{{ vendor.pk }}">{{ vendor }}</option>
{% endfor %}
</select>
</div>
</div>
<div class="ln_solid"></div>
<div class="form-group">
<div class="col-md-9 col-sm-9 col-xs-12 col-md-offset-3">
<button type="button" class="btn btn-primary">Cancel</button>
<button type="reset" class="btn btn-primary">Reset</button>
<button type="submit" class="btn btn-success">Submit</button>
</div>
</div>
</form>
при печати формы POST-запроса на терминале, ответ будет таким, как показано ниже:
Ошибка
Цена выпуска магазина Rm:
Требуется этот файл . Rm dept use: Это поле обязательно для заполнения.