如何使用Django表单从网页更新Profile模型的外键字段?

时间:2019-04-15 03:36:10

标签: django django-models django-forms django-views

我有一个名为profile的模型,该模型中具有一个字段,该字段使用ForeignKey链接到另一个称为广告的模型。我试图允许已登录的配置文件使用提交按钮从网页更改与其配置文件关联的广告实例。

这是配置文件模型:

class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    ethAddress = models.CharField(max_length=42, default='')
    advertisement = models.ForeignKey(Advertisement, on_delete=models.CASCADE, null=True, blank=True)

def __str__(self):
    return f'{self.user.username} Profile'

这是用于更改与其个人资料相关联的广告实例的表单:

class AdvertisementUpdateForm(forms.ModelForm):
    class Meta:
        model = Profile
        fields = ['advertisement']

这是视图:

def ad_update_view(request, my_id):

obj = Advertisement.objects.get(id=my_id)
profile = get_object_or_404(Profile, user=request.user)

if request.method == 'POST':
    ad_form = AdvertisementUpdateForm(request.POST, instance=profile)
    if ad_form.is_valid():
        ad_form.save()
        messages.success(request, f'Your account has been Updated!')
        return redirect('profile')
else:
    ad_form = AdvertisementUpdateForm(instance=profile)
context = {
    'ad_form':  ad_form,
    'object': obj,
}
return render(request, 'users/advertisement_update.html', context)

这是用户用来更改与其个人资料相关联的广告的模板。

{% extends "website/base.html" %}
{% block content %}
    <article class="media content-section">
        <div class="media-body">
            <form method="POST">
                <div class="article-metadata">
                    <a class="mr-2" href="#">{{ object.advertiser }}</a>
                    <small class="text-muted">{{ object.date_posted|date:"F d, Y" }}</small>
                </div>
                <h2 class="article-title">{{ object.ad }}</h2>
                <p class="article-available">Money Available: ${{ object.available }}</p>
                <p class="article-ppc">PPC: ${{ object.ppc }}</p>
                <p class="article-thumbnail">{{object.thumbnail}}</p>

                    {% csrf_token %}
                 <button class="btn btn-outline-info" type="submit" name="get_URL">Use Ad</button>
            </form>
        </div>
    </article>
{% endblock content %}

1 个答案:

答案 0 :(得分:0)

我不确定您在表单中正在做什么,但是如果要更新当前的用户配置文件,可以将其作为实例传递给表单,如下所示:

from django.shortcuts import get_object_or_404

def ad_update_view(request, my_id):
   profile = get_object_or_404(Profile, user=request.user)
   ad_form = AdvertisementUpdateForm(request.POST, instance=profile)
   ...

在您的表单中,您仅需要advertisement字段:

class AdvertisementUpdateForm(forms.ModelForm):
    class Meta:
        model = Profile
        fields = ['advertisement']