gpt4 book ai didi

python - Django - 形式参数?

转载 作者:行者123 更新时间:2023-12-01 01:51:31 27 4
gpt4 key购买 nike

views.py

from django.shortcuts import render
from basic_app.forms import UserForm,UserProfileInfoForm



# Extra Imports for the Login and Logout Capabilities
from django.contrib.auth import authenticate, login, logout
from django.http import HttpResponseRedirect, HttpResponse
from django.urls import reverse
from django.contrib.auth.decorators import login_required

# Create your views here.
def index(request):
return render(request,'basic_app/index.html')

@login_required
def special(request):
# Remember to also set login url in settings.py!
# LOGIN_URL = '/basic_app/user_login/'
return HttpResponse("You are logged in. Nice!")

@login_required
def user_logout(request):
# Log out the user.
logout(request)
# Return to homepage.
return HttpResponseRedirect(reverse('index'))

def register(request):

registered = False

if request.method == 'POST':

# Get info from "both" forms
# It appears as one form to the user on the .html page
user_form = UserForm(data=request.POST)
profile_form = UserProfileInfoForm(data=request.POST)

# Check to see both forms are valid
if user_form.is_valid() and profile_form.is_valid():

# Save User Form to Database
user = user_form.save()

# Hash the password
user.set_password(user.password)

# Update with Hashed password
user.save()

# Now we deal with the extra info!

# Can't commit yet because we still need to manipulate
profile = profile_form.save(commit=False)

# Set One to One relationship between
# UserForm and UserProfileInfoForm
profile.user = user

# Check if they provided a profile picture
if 'profile_pic' in request.FILES:
print('found it')
# If yes, then grab it from the POST form reply
profile.profile_pic = request.FILES['profile_pic']

# Now save model
profile.save()

# Registration Successful!
registered = True

else:
# One of the forms was invalid if this else gets called.
print(user_form.errors,profile_form.errors)

else:
# Was not an HTTP post so we just render the forms as blank.
user_form = UserForm()
profile_form = UserProfileInfoForm()

# This is the render and context dictionary to feed
# back to the registration.html file page.
return render(request,'basic_app/registration.html',
{'user_form':user_form,
'profile_form':profile_form,
'registered':registered})

forms.py

-

from django import forms
from django.contrib.auth.models import User
from basic_app.models import UserProfileInfo

class UserForm(forms.ModelForm):
password = forms.CharField(widget=forms.PasswordInput())

class Meta():
model = User
fields = ('username','email','password')


class UserProfileInfoForm(forms.ModelForm):
class Meta():
model = UserProfileInfo
fields = ('portfolio_site','profile_pic')

而且,这是我在互联网上找到的另一个文件。此代码与上面的代码是分开的

forms.py ---- different

@login_required
def edit_profile(request):
''' edit profile view for the accounts application '''
user = get_object_or_404(User, username=request.user)
form = EditProfileForm(instance=user)

print('Files : {}'.format(request.FILES))
if request.method == 'POST':

form = EditProfileForm(instance=user,
data=request.POST,
files=request.FILES
)

我不明白如何将参数传递到我定义的形式中。例如,我不明白这些代码行:

    user_form = UserForm(data=request.POST)
profile_form = UserProfileInfoForm(data=request.POST)

参数data在哪里定义?同样的,在这几行代码中:

form = EditProfileForm(instance=user,
data=request.POST,
files=request.FILES
)

参数、实例数据文件在哪里定义的?

我认为我缺乏对用户请求如何与表单结合使用的理解。

最佳答案

您提供的表单是 ModelForm子类:

class UserForm(<b>forms.ModelForm</b>):
password = forms.CharField(widget=forms.PasswordInput())

class Meta():
model = User
fields = ('username','email','password')

ModelForm(及其父类(super class))是一组类,它们实现模型实例和 Form 之间的某种绑定(bind)。例如,它将确保如果提供了实例,则表单元素将填充该数据。另一方面,如果您提供数据,它可以构造一个新的模型实例等。

例如,如果我们检查 source code我们看到:

class ModelForm(BaseModelForm, metaclass=ModelFormMetaclass):
pass

所以基本上 ModelForm 继承了 BaseModelForm 的所有内容,并且涉及一个 metaclass ,它基本上会检查是否存在 Meta 类在您的 Form 中(这里有),并对其执行一些操作。

无论元类做什么,我们都会看到 BaseModelForm__init__defined as [src] :

class BaseModelForm(BaseForm):
def __init__(<b>self, data=None, files=None, auto_id='id_%s', prefix=None,
initial=None, error_class=ErrorList, label_suffix=None,
empty_permitted=False, instance=None, use_required_attribute=None</b>):
# ...
pass

由于我们继承了__init__函数,所有的参数如datafilesauto_id等都被继承。也会遗传。

关于python - Django - 形式参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50665192/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com