Django文档上传表单未在浏览器中显示

时间:2013-12-10 14:12:23

标签: python django pycharm

这实际上是我正在进行的课程作业。我在django中创建了文档上传和注册的模型,视图和表单类。我一直在咨询不同的教程并尝试不同的技术,这就是为什么我的代码中可能有不同的方法。请原谅我新手提醒。

  1. 第一个问题:注册表格未提交到表格(用户)。我从管理员端添加了用户,它完美登录。
  2. Model.py

    class Users(models.Model):
        id = models.AutoField(primary_key=True, unique=True)
        title = models.CharField(max_length='10')
        surname = models.CharField(max_length='50')
        firstname = models.CharField(max_length='50')
        username = models.CharField(max_length='50')
        password = models.CharField(max_length='50')
        email = models.EmailField(max_length='50')
        phone = models.BigIntegerField(max_length='12')
        city = models.CharField(max_length='50')
        country = models.CharField(max_length='50')
        usertype = models.CharField(max_length=13)
    

    Form.py

     class RegisterForm(forms.Form):
            #define fields for form
            title = forms.CharField(max_length='10')
            surname = forms.CharField(max_length='10')
            firstname = forms.CharField(max_length='10')
            username = forms.CharField(max_length='50')
            password = forms.PasswordInput()
            email = forms.EmailField(required=True)
            phone = forms.CharField(max_length='15')
            city = forms.CharField(max_length='50')
            country = forms.CharField(max_length='20')
            userlevel = (
                (u'Client', 'Client'),
                (u'Proof Reader', 'Proof Reader'),
                (u'Admin', 'Admin'),
            )
            usertype = forms.ModelChoiceField( widget=forms.Select, queryset=userlevel )
    
            class Meta:
                model = Users
                fields = ('username', 'email', 'password', 'password2')
    
        def save(self, commit=True):
                Users = super(RegisterForm, self).save(commit=False)
                Users.title = self.cleaned_data['title']
                Users.surname = self.cleaned_data['surname']
                Users.firstname = self.cleaned_data['firstname']
                Users.username = self.cleaned_data['username']
                Users.password = self.cleaned_data['password']
                Users.email = self.cleaned_data['email']
                Users.phone = self.cleaned_data['phone']
                Users.city = self.cleaned_data['city']
                Users.country = self.cleaned_data['country']
                Users.usertype = self.cleaned_data['usertype']
                if commit:
                    Users.save()
                    return Users
    
        def clean_username(self):
                        username = self.cleaned_data['username']
                        try:
                                User.objects.get(username=username)
                        except User.DoesNotExist:
                                return username
                        raise forms.ValidationError("That username is already taken, please select another.")
    

    View.py

    def register(request):
        #model = Users
        #check  the request object if there is a method post for a form action
        if request.method == 'POST':
            #handle the form if method is found to be post
            #create a form object
            form = RegisterForm(request.POST)
            context = {'form': RegisterForm}
            #check if form is valid
            if form.is_valid():
                #save form
                Users.title = form.cleaned_data['title']
                Users.surname = form.cleaned_data['surname']
                Users.firstname = form.cleaned_data['firstname']
                Users.username = form.cleaned_data['username']
                Users.password = form.cleaned_data['password']
                Users.email = form.cleaned_data['email']
                Users.phone = form.cleaned_data['phone']
                Users.city = form.cleaned_data['city']
                Users.country = form.cleaned_data['country']
                Users.usertype = form.cleaned_data['usertype']
                #redirect to success page
                return HttpResponseRedirect('register_success')
            else:
                form = RegisterForm()
                #create arguments to check against CSRF attacks
        args = {}
        args.update(csrf(request))
        args['form'] = RegisterForm()
        return render_to_response('register.html', args)
    
    def auth_view(request):
        username = request.POST.get('username', '')
        password = request.POST.get('password', '')
        user = auth.authenticate(username=username, password=password)
    
        if user is not None:
            auth.login(request, user)
            return HttpResponseRedirect('welcome')
        else:
            return HttpResponseRedirect('invalid')
            #return render_to_response('auth_view.html')
    

    模板文件 - register.html

    {% extends "main.html" %}
    {% block title %}Register{% endblock %}
    {% block content %}
        <h2>Register</h2>
    
        <form action="" method="post"> {% csrf_token %}
      <table> {{ form }} </table>
        <input type="submit" value="Register">
        </form>
    
    {% endblock %}
    
    1. 文档上传表单也未显示。我不知道为什么会这样。
    2. Models.py

      class document(models.Model):
          id = models.AutoField(primary_key=True, unique=True)
          file = models.FileField(upload_to=get_upload_file_name)
          statusid = models.ForeignKey('status')
          userID = models.ForeignKey('Users')
          #feedback = models.TextField(blank=True)
          time = models.DateTimeField()
          completion_time = models.DateTimeField(blank=True)
          choice = ((u'Audio', 'Audio'), (u'Text', 'Text'))
          filetype = models.CharField(max_length='50')
      

      views.py

      def uploaddocs(request):
          if request.method == 'POST':
              form = DocumentForm(request.POST, request.FILES)
              context = {'form': DocumentForm}
              if form.is_valid():
                     form.upload()
                     return HttpResponseRedirect('upload_success')
      
          args = {}
          args.update(csrf(request))
          args['forms'] = DocumentForm()
          return render_to_response('uploaddocs.html', args)
      

      forms.py

      class DocumentForm(forms.Form):
          #define fields for form
          model = document
          file = forms.FileField()
          statusid = forms.CharField(max_length='10')
          userID = forms.CharField(max_length='10')
          #feedback = models.TextField(blank=True)
          time = forms.DateTimeField()
          completion_time = forms.DateTimeField()
          choice = ((u'Audio', 'Audio'), (u'Text', 'Text'))
          filetype = forms.ChoiceField(choices=choice)
      
      def upload(self, commit=True):
         document = DocumentForm.save(commit=False)
         document.statusid = self.cleaned_data['statusid']
         document.time = self.cleaned_data['time']
         document.completion_time = self.cleaned_data['completion_time']
         document.filetype = self.cleaned_data['filetype']
         if commit:
             document.upload()
             return document
      

      我知道这似乎是整个任务,但请相信我,这只是我未来许多错误的开始。谢谢你的回复。

2 个答案:

答案 0 :(得分:0)

看起来您希望RegisterForm的行为与ModelForm实例相似。如果您将RegisterForm更改为继承django.forms.ModelForm而不是django.forms.Form,并将{= 1}模型的用户名字段添加唯一= True,那么您最终会得到以下结果:< / p>

Users

关于文档表单:它似乎不一致地命名:在视图中它被命名为class RegisterForm(forms.ModelForm): class Meta: model = User ,在模板中它被命名为forms

希望有所帮助!

答案 1 :(得分:0)

这里有多个问题:

  1. 正如Martin Ogden所说,如果要直接保存到数据库,则应使用ModelForm。这样,您就可以摆脱RegisterForm.save()方法以及视图中的明确分配(title = form.cleaned_data['title']等)。

  2. 在您看来,Users.title = form.cleaned_data['title']无法正常工作:您要分配到Users ,而不是特定的实例。使用ModelForm,您不需要这些明确的作业,但作为参考,以下是您可以使用常规Form编写此内容的方法:

    if form.is_valid():
        u = Users()  # create a Users instance
        u.title = form.cleaned_data['title']   # assign the title attribute 
        # ...
        u.save()   # save this Users instance
    
  3. 您始终需要将表单 instance 传递给模板,而不是类。所以不是context = {'form': RegisterForm}而是写

    form = RegisterForm()
    if request.method == "POST":
        form = RegisterForm(request.POST)
        # ...
    context={'form': form}
    

    一个非常有用的模式如下:

    def some_view(request):
        form = RegisterModelForm(request.POST or None)
        if form.is_valid()
            form.save()
            return redirect(...)
        context = {'form': form}
        return render_to_response('register.html', context)
    

    这样,您只需要创建一次表单实例。

  4. 您的Users模型中存在错误:您手动验证两个Users实例不能具有相同的用户名,但想象两个用户正在注册确切同一时间使用相同的名称:clean_username中的存在检查将为两个用户运行,并且将创建两个实例。最好为需要唯一的字段设置unique=True,因为数据库可以为您保证这类事情(并且您不需要编写该自定义数据