在Django中使用form.py将当前登录用户导入表单的步骤如下:
from django import forms
from .forms import YourForm
return render(request, 'your_template.html', {'form': form})
{{ form.as_p }}
或其他渲染方式。下面是一个示例代码:
forms.py:
from django import forms
from .models import YourModel
class YourForm(forms.ModelForm):
class Meta:
model = YourModel
fields = ['field1', 'field2', ...] # 根据你的需求指定字段
def __init__(self, user, *args, **kwargs):
super(YourForm, self).__init__(*args, **kwargs)
self.fields['current_user'] = forms.CharField(initial=user.username, widget=forms.HiddenInput())
views.py:
from .forms import YourForm
def your_view(request):
form = YourForm(user=request.user)
return render(request, 'your_template.html', {'form': form})
def submit_view(request):
if request.method == 'POST':
form = YourForm(request.user, request.POST)
if form.is_valid():
# 处理表单数据
form.save()
return redirect('success_url')
else:
form = YourForm(request.user)
return render(request, 'your_template.html', {'form': form})
your_template.html:
<form method="post" action="{% url 'submit_view' %}">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">提交</button>
</form>
请注意,上述示例代码中的YourModel和success_url需要根据你的实际情况进行替换。另外,这只是一个简单的示例,实际应用中可能需要根据具体需求进行修改和扩展。
领取专属 10元无门槛券
手把手带您无忧上云