[英]rendered form isnt saving any input into database, why isnt it working?
[英]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
並且該模型的所有屬性都是phone
和profile_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.