Django Updating Existing Model field

Enam picture Enam · May 9, 2016 · Viewed 9.4k times · Source

I have a model in Django with a foreign key to Django User Model. I am trying to update my model with a form, but database isn't updating. I can't figure out the problem.

model.py

from django.conf import settings

    class UserInfo(models.Model):
        username = models.CharField(max_length = 30)
        owner =  models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE,)

form.py

from django import forms
from society.models import UserInfo

    class Editform(forms.ModelForm):
        username=forms.CharField(widget=forms.TextInput(attrs={'onchange': 'this.form.submit();', 'class': 'editinput'}))
        class Meta:
            model = UserInfo
            fields ='__all__'

views.py

 from django.shortcuts import render
    from society.models import UserInfo
    from django.contrib.auth.models import User
    from society.forms import Editform

        def ProfileView(request):
            user = request.user
            username = UserInfo.objects.get(owner=user)
            if request.method == 'POST':
                form = Editform(request.POST, instance=username)
                if form.is_valid():
                    form.save()
            else:
                form = Editform(instance=username)


            return render (request, 'profile_view.html', {'user':username, 'form':form})

url.py

from django.conf.urls import url
from django.contrib import admin
import society.views

    urlpatterns = [
        url(r'^$', 'society.views.home'),
        url(r'^admin/', admin.site.urls),
        url(r'^login/', 'django.contrib.auth.views.login'),
        url(r'^logout/', 'django.contrib.auth.views.logout'),
        url(r'^userreg/', 'society.views.UserReg'),
        url(r'^profile/', 'society.views.ProfileView'),
    ]

profile_view.html

    <div>
        <form method="POST">
        {% csrf_token %}
            {{form.username}}
            {{user.username}}
        </form>
    </div>

When ever I change form.username, user.username change instantly but the database is not updating. I tried with adding a submit button, but still no luck.

Answer

Anoop picture Anoop · May 9, 2016

You should pass record id for updating existing UserInfo record.

from django.shortcuts import render
from society.models import UserInfo
from django.contrib.auth.models import User
from society.forms import Editform

def ProfileView(request):
    user_id = request.POST.get('user_id')
    user = UserInfo.objects.get(pk=user_id)
    if request.method == 'POST':
        form = Editform(request.POST, instance=user)
        if form.is_valid():
            form.save()
    else:
        form = Editform(instance=user)

    return render (request, 'profile_view.html', {'user':username, 'form':form})