简体   繁体   中英

How to properly create ModelForm in django?

There is my model:

class Profile(models.Model):
    user = models.OneToOneField(User, related_name='profile')
    street_address = models.CharField(max_length=511, blank=True)
    photo = models.ImageField(upload_to='images/userpics/', blank=True)
    phone_number = models.CharField(max_length=50, blank=True)
    about_me = models.TextField(blank=True)
    status = models.CharField(max_length=140, blank=True)

Form:

class ProfileForm(forms.ModelForm):
    class Meta:
        model = Profile
        exclude = ('user_id', )

View:

@login_required
def update_profile(request):
    # if this is a POST request we need to process the form data
    if request.method == 'POST':
        # create a form instance and populate it with data from the request:
        form = ProfileForm(request.POST)
        form.data['user_id'] = str(request.user.id)
        # check whether it's valid:
        if form.is_valid():
            profile = form.save(commit=False)
            # commit=False tells Django that "Don't send this to database yet.
            # I have more things I want to do with it."

            profile.user = request.user # Set the user object here
            profile.save() # Now you can send it to DB
        else:
            return render(request, "dashboard/account.html", {"form_profile": form, "form_password": ChangePasswordForm(), 'balance': get_user_balance(request.user)})

All I want is simple UpdateProfileForm where User will be able to update their info. What is the best way to implement this?

You would be better off just using an update view

class ProfileFormView(UpdateView):
    template_name = 'dashboard/account.html'
    form_class = ProfileForm
    success_url = '#'

    def get_object(self, queryset=None):
        return Profile.objects.get(self.kwargs['id'])

url(r'^update_profile/(?P<id>\d+)/$', ProfileFormView.as_view(), name="update_profile"),

Django docs are currently down right now.. I will update with a link to documentation when I can

Your template then just becomes

<form method="post">
        {% csrf_token %}
        {{ form }}
            <button id="submit" type="submit">Submit</button>
</form>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM