选择字段形式的Django实际值



我有这样的模型:

class Projects(models.Model):
project = models.CharField(max_length=150, blank=True, null=True)
def __str__(self):
return self.project
class Profile(models.Model):
user = models.OneToOneField(get_user_model(), on_delete=models.CASCADE)
project = models.ForeignKey(Projects, on_delete=models.CASCADE, null=True, blank=True)

def __str__(self):
return self.user.username

我还制作了一个表格,我想在其中更改当前项目分配的配置文件:

class ProjectForm(ModelForm):
class Meta:
model = Profile
fields = [
'project'
]

我的观点是这样的:

def change_project(request, user):
user = User.objects.filter(username=user)[:1].get()
profile = Profile.objects.get(user=user)
form = ProjectForm(request.POST, instance=profile)
if request.method == 'POST':
if form.is_valid():
form.save()
context = {'form': form}
return render(request, 'datafiller/change_project.html', context)

我可以使用这个表单更改项目,但每次我想再次更改时,表单都像这个

我如何在表格中显示当前项目而不是"------"?

如果使用GET请求呈现表单,则不应使ProjectForm接地:

from django.shortcuts import get_object_or_404
def change_project(request, user):
profile =get_object_or_404(Profile, user__username=user)
if request.method == 'POST':
form = ProjectForm(request.POST, instance=profile)
if form.is_valid():
form.save()
else:
form = ProjectForm(instance=profile)
return render(request, 'datafiller/change_project.html', {'form': form})

相关内容

  • 没有找到相关文章

最新更新