Django - 形式上的争论?

时间:2018-06-03 10:03:05

标签: python django django-forms django-views

  

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 ----不同

@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
                      )

参数instancedatafiles定义在哪里?

我认为我不了解用户请求如何与表单一起使用。

1 个答案:

答案 0 :(得分:2)

您提供的表单是 ModelForm 的子类:

<input type="file">

class UserForm(forms.ModelForm): password = forms.CharField(widget=forms.PasswordInput()) class Meta(): model = User fields = ('username','email','password')(及其超类)是一组实现模型实例与ModelForm之间的某种绑定的类。例如,它将确保如果提供了实例,则表单元素将填充该数据。另一方面,如果您提供数据,它可以构建新的模型实例等。

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

Form

所以基本上class ModelForm(BaseModelForm, metaclass=ModelFormMetaclass): pass 继承了ModelForm的所有内容,并且涉及BaseModelForm,基本上会检查metaclass中是否有Meta个班级(这里有),并对其进行一些操作。

无论元类的作用如何,我们都会看到Form的{​​{1}}为defined as [src]

__init__

由于我们继承了BaseModelForm函数,所以class BaseModelForm(BaseForm): def __init__(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): # ... pass__init__data等所有参数都会被继承。