繁体   English   中英

以不保存到数据库的形式输入

[英]Input give in the form not saving to the database

这是我创建的模型制作表格。 使用抽象用户在表单中添加了另外两个字段。 模型.py

from django.db import models
from django.contrib.auth.models import AbstractUser

class MyUser(AbstractUser):
    phone=models.CharField(max_length=20)
    profile_pic=models.ImageField(upload_to="dp",null=True,blank=True)

注册表单继承自UserCreationForm。

表单.py

from django.contrib.auth.forms import UserCreationForm
from socialapp.models import MyUser
from django import forms

class RegistrationForm(UserCreationForm):
    widgets={
        "password1":forms.PasswordInput(attrs={"class":"form-control"}),
        "password2":forms.PasswordInput(attrs={"class":"form-control"})
    }
    class Meta:
        model=MyUser
        fields=["first_name","last_name",
                "username","email",
                "phone","profile_pic",
                "password1","password2"]
        widgets={
            "first_name":forms.TextInput(attrs={"class":"form-control"}),
            "last_name":forms.TextInput(attrs={"class":"form-control"}),
            "username":forms.TextInput(attrs={"class":"form-control"}),
            "email":forms.TextInput(attrs={"class":"form-control"}),
            "phone":forms.TextInput(attrs={"class":"form-control"}),
            "profile_pic":forms.FileInput(attrs={"class":"form-control"}),
        }

这是映射到模板 views.py 的视图

from django.shortcuts import render
from socialapp.forms import RegistrationForm
from socialapp.models import MyUser
from django.views.generic import CreateView
from django.urls import reverse_lazy



class SignupView(CreateView):
    model=MyUser
    form_class=RegistrationForm
    template_name="register.html"
    success_url=reverse_lazy("register")
    
    

    

这可能不起作用,因为首先,您有一个模型MyUser并且该模型的所有属性都是phoneprofile_pic 在表单中添加所有这些属性可能会或可能不会在模板中很好地呈现,但这不会改变模型。

解决这个问题的方法是在模型中添加属性,然后根据您在表单中的喜好修改这些属性。

其次,您甚至没有在视图中保存表单:-)试试这个:

 class SignupView(CreateView): model=MyUser form_class=RegistrationForm template_name="register.html" success_url=reverse_lazy("register") def form_valid(self,form): return super().form_valid(form)

如果您还没有注册MyUser模型,请记住在管理员中注册。

 from django.contrib import admin # Register your models here. from.models import MyUser admin.site.register(MyUser)

您没有发布模板,但您的模板应该类似于:

 <form action="" method="POST" enctype="multipart/form-data"> {{form|crispy}}{%csrf_token%} <button class="btn btn-lg bg-primary " type="submit" style='float: right;margin: 5px 0 10px;'> Done! </button> </form>

您还可以考虑使用基于函数的视图,以便更好地控制视图中发生的事情。

如果您仍然卡住,请务必进一步解释我如何帮助您。

祝你今天过得愉快:-)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM