我的配置文件模型包含太多字段。其中两个字段是lat
和lon
,我使用django表单来编辑
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
city = models.CharField(max_length=100)
state = models.CharField(max_length=100, blank=True, null=True)
country = models.CharField(max_length=100)
street_address = models.CharField(max_length=500, null=True, blank=True)
zip_code = models.CharField(max_length=10, default='')
phone_number = models.CharField(max_length=17, blank=True, null=True)
age = models.DateField(blank=True, null=True)
member_since = models.DateTimeField(auto_now_add=True)
profile_image = models.ImageField(default='', blank=True, null=True)
bio = models.TextField(default='', blank=True)
bio_images = models.ImageField(default='', blank=True, null=True)
activities_i_do = models.TextField(default='', blank=True, null=True)
activities_i_love = models.TextField(default='', blank=True, null=True)
is_verified = models.BooleanField(default=False)
lat = models.FloatField(blank=True, null=True)
lon = models.FloatField(blank=True, null=True)
下面是编辑属性的视图
@login_required
def edit_profile(request):
if request.method == 'POST':
user_form = UserEditForm(data=request.POST or None, instance=request.user)
profile_form = ProfileEditForm(data=request.POST or None, instance=request.user.profile, files=request.FILES)
if user_form.is_valid() and profile_form.is_valid():
user_form.save()
profile_form.save()
return redirect('accounts:profile', username=request.user.username)
else:
user_form = UserEditForm(instance=request.user)
profile_form = ProfileEditForm(instance=request.user.profile)
context = {'user_form': user_form,
'profile_form': profile_form}
return render(request, 'accounts/profile_edit.html', context)
现在的问题是,我可以使用另一种形式来编辑上述模型示例的lat
lon
字段吗?
<form method="post" action="{{ ??????????? }}">
<input id="jsLat" type="text" placeholder="latittude" >
<input id="jsLon" type="text" placeholder="longitude">
<button type="submit" id="submit">Submit</button>
</form>
我已经使用jquery制作了表单,以便当用户单击找到我时,表单会自动填写并提交。我可以使用此表单来编辑个人档案模型的两个字段
下面是我的个人资料修改表单
class ProfileEditForm(forms.ModelForm): #UserProfileForm or ProfileEdit
class Meta:
model = Profile
fields = ('city', 'state', 'country', 'street_address', 'zip_code', 'phone_number', 'age', 'profile_image',
'bio', 'bio_images', 'activities_i_do', 'activities_i_love', 'lat', 'lon')
PS:为简化起见,删除了geodjango代码。只需更新lat
lon
,就好像它们是常规字段一样
答案 0 :(得分:0)
您将无需创建其他表单。由于您未显示表单,因此我假设您使用了
class ProfileForm(forms.ModelForm):
class Meta:
model = Profile
fields = ('user', 'city', 'state'...)
您可以做的就是渲染profile_form并像这样使用它
<form method="post" action="{{ ??????????? }}">
<input id="jsLat" type="text" placeholder="latittude" value="{{profile_form.lat.value}}">
<input id="jsLon" type="text" placeholder="longitude" value="{{profile_form.lon.value}}">
<button type="submit" id="submit">Submit</button>
</form>
在您的views.py
profile_form = ProfileEditForm(request.POST)
profile_form.save()
希望它有助于或给您一个想法!当然,您将需要在表单中插入某种主键或ID,以便获得要编辑的配置文件的上下文。
答案 1 :(得分:0)