我正在研究引导模板。但是在将配置文件信息保存到数据库中遇到了麻烦。这是我的代码。我不知道我是否做对了。但是它不起作用。
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
Propic = models.ImageField(upload_to="Banners/", null=True,blank=True)
bio = models.TextField(max_length=500, blank=True)
location = models.CharField(max_length=30, blank=True)
def profile(request):
ids = request.user.id
user = User.objects.get(pk=ids)
if request.method == "POST":
bio = request.POST["bio"]
location = request.POST["location"]
image = request.FILES['pic']
form = user.profile(bio = bio , location = location , propic=image)
form.save()
return HttpResponse("info saved")
return render(request, "dashbord/user.html", {"user": user })
答案 0 :(得分:0)
在您的应用程序目录中,创建表格。py包含:
forms.py:
from django import forms
from your-app.models import Profile # insert your currently app name
class ProfileForm(forms.ModelForm):
class Meta:
model = Profile
和views.py:
from django.views import View
from your-app.models import Profile # your curr app name
from your-app.forms import ProfileForm
class UpdateProfile(View):
model = Profile
template_name = 'some.html'
def get(self, request, **kwargs):
user = Profile.objects.get(id=request.user.id)
form = ProfileForm(initial=user.__dict__)
return render(request, self.template_name, locals())
def post(self, request, **kwargs):
user = Profile.objects.get(id=request.user.id)
os.remove(user.propic.path)
form.ProfileForm(request.POST, request.FILES, instance=user)
form.save()
return redirect('/')
和您的urls.py:
urlpatterns = [
....,
path('update', UpdateProfile.as_view()),
...
]
更新模板:
<form action="update/" method="post" enctype="multipart/form-data"> <!-- this line requered, otherwise your form won't take a photo -->
{% csrf_token %}
<table>
{{ form }}
</table>
<input type="submit" name="update" value="update">
<input type="submit" name="cancel" value="cancel">
</form>
只需复制一个假设即可,
答案 1 :(得分:0)
感谢帮助人员。我想出了怎么做。您需要像这样分别保存每列。
def profile(request , *args, **kwargs):
ids = request.user.id
user = User.objects.get(pk=ids)
if request.method == "POST":
if "bio" in request.POST and "location" in request.POST:
bio = request.POST["bio"]
location = request.POST["location"]
user.profile.bio = bio
user.profile.location = location
user.profile.save()
elif "image" in request.FILES:
image = request.FILES['image']
user.profile.Propic.save(image.name , image)
return render(request, "dashbord/user.html", {"user": user })