简体   繁体   中英

How do I update the user's model fields in Django?

I'm currently creating a Social platform with Django. Right now, I'm developing the Profile Settings page and want endusers to be able to change their Header and Display-image.

However, I'm not able to make the form work. Both the Header and Display-images are passing correctly through the POST form and end up getting stored in the media root, from where I call all my Header and Display-images in the template.

So the problem right now is refering the submitted images as a Header or Display-image for the current user. This is my Profiel (dutch for Profile)Models.py:

class Profiel(models.Model):
user = models.OneToOneField(User, primary_key=True)
Profielfoto = models.ImageField(blank=True, upload_to="profile_image", default="profile_image/no_profile_pic.jpg")
Profielheader = models.ImageField(blank=True, upload_to="profile_header")
Biografie = models.CharField(blank=True, max_length=150, default="Biografie nog niet ingevuld.")

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

def create_profile(sender, **kwargs):
    if kwargs['created']:
        user_profile = Profiel.objects.create(user=kwargs['instance'])

post_save.connect(create_profile, sender=User)

My Views.py

@login_required
def profile_edit_view(request):
if request.method == 'POST':
    form = Edit_profile_forms(request.POST, request.FILES)
    if form.is_valid():
        form.save()
        # Redirect to the document list after POST
        return HttpResponseRedirect(reverse('profiel_edit'))
else:
    form = Edit_profile_forms(request.POST, request.FILES)
    args = {'form':form}
    return render(request, 'Dashboard/profiel_edit.html', args)

And my forms.py:

class Edit_profile_forms(forms.ModelForm):
class Meta:
    model = Profiel
    fields = (
        'Profielfoto',
        'Profielheader',
        'Biografie',
    )

I think these are the only ones needed to show you guys for solving this problem, as the form is doing everything else correctly. So my end question is:

How do I update the current user's Header/Image files to the files submitted in the form?

Iv edited my answer so you can copy and paste into your view.

@login_required
@csrf_protect
def profile_edit_view(request):
    template = 'Dashboard/profiel_edit.html'
    qv = Profiel.objects.get(user=request.user.id)


    if request.method == 'POST':
        form = Edit_profile_forms(request.POST, request.FILES, instance=qv)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect(some_view)

        else:
            print form.errors
    else:
        form = Edit_profile_forms(instance=qv)

    return render(request, template, {'form':form})

Update

I understood that you want to let users to edit their profile/header picture by uploading new images by form. Your code is just to save new data from data through form, not to update existing data.

Django has class based view. please check this link

from django.views.generic.edit import UpdateView

class UpdateExampleView(UpdateView):
    model = your model
    form_class = your Form
    template_name = 'your template'
    success_url = path to go when form successfully passed

# additionally you can handle your data with these methods
    def get_form_kwargs(self):
    def get_context_data(self, **kwargs):
    def form_valid(self, form):

don't forget that you need to give pk number through url like this

url(r'^example/path/(?P<pk>[0-9]+)/$', your class view or function view, name='your name'),

previous answer

I wonder if I understood your question correctly. According to what I understood, you don't have problem to save images data with form. So I understood you are having problem to load this pictures for users.

you must set where your media file is saved in in settings.py like below.

settings.py

MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media/')

and you said your images saved in media root correctly.

so if you check your Profiel table in database, in field of Profielfoto, ProfielHeader, there will be path.

For example, if the name of your profilephoto was 'profiletest.jpg', data in Profielfoto field will be ' profile_image/profiletest.jpg '. because you set upload_to="profile_image" in Model class.

if you want to load image from media folder in view(template), you write like below.

<img src="{{MEDIA_URL}}{{yourimagepath}}"/>

to you use {{MEDIA_URL}}, you should put django.template.context_processors.media in settings.py

settings.py

...
TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, 'templates')],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.template.context_processors.media',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]
...

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