我有三個模型jobposition, wage,kitfee它們通過 OneToMany 關系相關聯。
class JobPosition(models.Model):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
title = models.ForeignKey(Title, on_delete=models.CASCADE)
...
class Wage(models.Model):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
amount = models.FloatField(blank=True,null=True)
type = models.CharField(choices=WAGETYPE, max_length=30)
position = models.ForeignKey(JobPosition, related_name='wages', on_delete=models.CASCADE, blank=True, null=True)
class KitFee(models.Model):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
kit_name = models.CharField(max_length=20, blank=True, null=True)
amount = models.FloatField(blank=True, null=True)
type = models.CharField(choices=WAGETYPE, max_length=30)
position = models.ForeignKey(JobPosition, related_name='kit_fees', on_delete=models.CASCADE, blank=True, null=True)
我正在構建一個用戶界面,用戶可以在其中創建一個帶有相關工資和 kit_fee 的職位(假設現在只有一個工資和一個套件費用)。
我面臨的問題是我不確定如何以正確的方式發出帖子請求。
我創建了這兩個表單并使用模板視圖將它們提供給 django 模板。
class JobPositionForm(forms.ModelForm):
class Meta:
model = JobPosition
fields = ['title','city','dept_head','files','department_budget']
...
class WageForm(forms.ModelForm):
class Meta:
model = Wage
exclude = ['id']
我的觀點
class NewPosition(MyLoginRequiredMixin,TemplateView):
template_name = 'action/crew/position.html'
def get_context_data(self, **kwargs):
self.project = get_object_or_404(JobProject, id=kwargs['project_id'])
context = super().get_context_data(**kwargs)
context['position_form'] = JobPositionForm(project=self.project, user=self.request.user)
context['wage_form'] = WageForm()
context['kit_fee_form'] = KitFeeForm()
return context
def post(self,request, **kwargs):
print(request.POST)
self.project = get_object_or_404(JobProject, id=kwargs['project_id'])
position_form = JobPositionForm(request.POST, project=self.project, user=self.request.user)
wage_form = WageForm(request.POST)
kit_fee_form = KitFeeForm(request.POST)
print(kit_fee_form.data['amount'])
print(wage_form.data['amount'])
頁面呈現流暢,但是我現在意識到我不知道如何在單個發布請求中一起提交這兩個表單,也不知道如何在處理發布請求時初始化視圖中的表單。
我想過使用 formset 但我不知道如何將它用于不同的表單。
我想我總是可以使用 Javascript手動執行此操作來決議每個值并將其放入同一個 POST 中……但我希望可以使用一些不錯的 django 功能來解決它??。特別是因為手動方法不能很好地擴展。
<form id="position_form">
<div id="title_div" style="margin-top: 20px;">
<label for="id_title" style="margin-bottom: 5px;" class="lead">Title</label><br/>
{{position_form.title}}
<div id="city_div" style="margin-top: 20px;" onfocus="$('#title_creation_div').hide();">
<label for="id_city" style="margin-bottom: 5px;" class="lead">City</label><br/>
{{position_form.city}}
</div>
<br>
<div class="inner" style="display: inline-block;margin-right: 5px;margin-left: 5px; text-align: center">
<label for="OtherComp">Department Budget</label><br/>
{{position_form.department_budget}}
</div>
<div class="inner" style="display: inline-block;margin-right: 5px;margin-left: 5px; text-align: center">
<label for="TeamInfo">Department Head</label><br/>
{{ position_form.dept_head }}
</div>
</form>
<form id="wage_form">
<div id="outer" style="width:100%; margin-top: 20px ">
<div class="inner" style="display: inline-block;margin-right: 5px;margin-left: 5px">
<label for="{{ wage_form.amount.id_for_label }}">Rate</label><br/>
{{wage_form.amount}}
</div>
<div class="inner" style="display: inline-block;margin-right: 5px;margin-left: 5px; text-align: center">
<label for="{{ wage_form.type.id_for_label }}">Rate Type</label><br/>
{{wage_form.type}}
</div>
</div>
</form>
任何的想法?
編輯 我正在使用這個 javascript 將所有表單發送到同一個 post 請求中,它似乎作業正常。但是,我注意到許多欄位具有相同的 ID,因此我無法正確啟動表單。此外,如果我開始在螢屏上添加額外的工資/kitfee,該程序似乎不可擴展。
$("form").submit(function (e) {
e.preventDefault();
let data_array = $("form").map(function(){
return $(this).serializeArray();
});
data_array.push({csrfmiddlewaretoken: "{{ csrf_token }}"})
console.log(data_array)
$.ajax({
type: "POST",
url: "{% if source == 'edit' %}{% url 'action:edit_position' project.id position.id %}{% else %}{% url 'action:new_position' project.id %}{% endif %}",
data:data_array,
success:function(html){
}
});
});

uj5u.com熱心網友回復:
由于您使用的是模型表單,您可以直接將請求傳遞到表單實體中以同時處理這兩個表單......請參閱下面的簡單注冊場景,其中正在處理兩個模型表單(User_form 和 User_profile_Form),
視圖.py
def signup(request):
registered = False
if request.method == "POST":
user_form = User_form(data=request.POST)
user_profileform = user_profile_form(data=request.POST)
if(user_form.is_valid() and user_profileform.is_valid()):
user = user_form.save()
user.set_password(user.password)
user.save()
profile = user_profileform.save(commit=False)
profile.user = user
if 'profile_picture' in request.FILES:
profile.profile_picture = request.FILES['profile_picture']
profile.save()
registered = True
else:
print(user_form.errors, user_profileform.errors)
更新 1 添加模板部分
<!DOCTYPE html>
{% extends "base.html" %}
{% load static %}
{% load bootstrap_tags %}
{% block title %}
Signup
{% endblock %}
{% block body %}
<div class="container">
{% if registered %}
<h1>Thankyou for REGISTERING with us</h1>
<br>
<a href="{% url 'homepage:home' %}"> click here to continue </a>
{% else %}
<a href="{% url 'registration:signin' %}"> <h4 style="text-align: center;" > Already have an account ? </h4></a>
<h3>PLEASE fill the registration form below</h3>
<form enctype="multipart/form-data" method="POST">
<div class="container sign-form">
{% csrf_token %}
<h4>
<u>Account Information : </u>
{{ user_form |as_bootstrap }}
<br>
<hr>
<br>
<u><h4>Personal Information :</h4></u>
{{ user_profileform |as_bootstrap }}
</h4>
<input type="submit" class = "btn btn-primary" name="submit" value="Sign Up" style="margin: 0% 15%; width: 70%">
</div>
</form>
{% endif %}
{% endblock %}
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/378907.html
標籤:姜戈 形式 django-forms
