spidey677
spidey677

Reputation: 419

Django - Form Not Updating

I’m creating a profile page in my web application & I have a form to when the user makes a form submission I need the data from the form to update in admin from the current logged in user.

The data populates in the admin however new listings keep repeating every time the user submits a form. I need the the data to update only. Screenshot attached.

How do I execute this correctly with my current code?

The Custom User Model I’m using is located in from users.models import CustomUser if that helps.

Any help i gladly appreciated, Cheers

enter image description here

enter image description here

user_profile/models

from django.contrib import auth
from django.db import models
from django.urls import reverse
from django.contrib.auth.models import AbstractUser, UserManager
from django.contrib.auth.models import BaseUserManager
from django.contrib.auth.models import User
from django.db.models.signals import post_save
from django.dispatch import receiver
from django.conf import settings
from users.forms import CustomUserCreationForm, CustomUserChangeForm
from users.models import CustomUser

class Listing (models.Model):

    image = models.ImageField(default='default.jpg', upload_to='profile_pics')
    user = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, on_delete=models.CASCADE)
    created =  models.DateTimeField(auto_now_add=True, null=True)
    updated = models.DateTimeField(auto_now=True)
    name = models.CharField(max_length=100)
    address = models.CharField(max_length=100)
    zip_code = models.CharField(max_length=100)
    mobile_number = models.CharField(max_length=100)
#    cc_number = models.CharField(max_length=100)
#    cc_expiration = models.CharField(max_length=100)
#    cc_cvv = models.CharField(max_length=100)
#    objects = ListingManager()

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

post_save.connect(create_profile, sender=CustomUser)

user_profile/views.py

def change_view(request):
    form = HomeForm(request.POST or None, request.FILES or None)
    user_profile = Listing.objects.all
    user = request.user
    if request.method == "POST":  # checking if request is POST or Not
        # if its a post request, then its checking if the form is valid or not
        if form.is_valid():
            listing_instance = form.save(commit=False)  # "this will return the 'Listing' instance"
            listing_instance.user = user # assign 'user' instance
            listing_instance.save() # calling 'save()' method of model
            return redirect("myaccount")

    context = {
        'form': form, 'user_profile': user_profile 
    }

    return render(request, "myaccount.html", context)

user_profile/admin.py

from django.contrib import admin
from django.contrib.auth import get_user_model
from django.contrib.auth.admin import UserAdmin


from user_profile.forms import HomeForm
from users.forms import CustomUserCreationForm, CustomUserChangeForm

from user_profile.models import Listing
from users.models import CustomUser


# Register models here.
class UserProfileAdmin(admin.ModelAdmin):
    list_display = ['name', 'address', 'zip_code', 'mobile_number', 'created', 'updated', 'user']
    list_filter = ['name', 'zip_code', 'created', 'updated', 'user']

admin.site.register(Listing, UserProfileAdmin)

html

{% block content %}
<form role="form" action="" method="post" enctype="multipart/form-data">
{% csrf_token %}
{{ form.errors }}   
{{ form.name }}
{{ form.address }}
{{ form.zip_code }}
{{ form.mobile_number }}
{{ form.image }}
<button class="btn btn-primary btn-success btn-round btn-extend" type="submit" value="Submit"><i class="zmdi zmdi-favorite-outline6"></i>Submit</button>
</form>    
{% endblock content %}

user_profile/urls.py

from django.conf.urls import url
from . import views
from django.urls import path, include
from django.conf import settings

from .views import change_view

urlpatterns = [
    path('myaccount/', change_view, name='myaccount'),
]

settings

AUTH_USER_MODEL = 'users.CustomUser'

Upvotes: 1

Views: 3776

Answers (3)

 pass customer Id after request and use url path as mentioned below 

For View Function Change

def upload_data(request, pk):
    order = ModelName.objects.get(id=pk)
    form= FormName(instance=order)
    request.method == 'POST':
    form = FormName(request.POST, instance=order)
    if form.is_valid():
        form.save()
        return redirect('url/')
    return render(request, ' url/', {'form':form})


**For URLS.py**    

post('functionName/<str:pk>',views.functionName,name='Function Name'),

Upvotes: 1

ruddra
ruddra

Reputation: 52028

Actually I think the problem is that you are not differentiating the request types. You should handle the get and post request separately in your view. So the view should be like this:

def change_view(request):
    user = request.user
    user_profile = Listing.objects.filter(user=user).first()
    form = HomeForm(request.POST or None, request.FILES or None, instance=user_profile)
    if request.method == "POST":  # checking if request is POST or Not
        # if its a post request, then its checking if the form is valid or not
        if form.is_valid():
            listing_instance = form.save(commit=False)  # "this will return the 'Listing' instance"
            listing_instance.user = user # assign 'user' instance
            listing_instance.save() # calling 'save()' method of model
            return redirect("success-url-path")

    context = {
        'form': form
    }

    return render(request, "myaccount.html", context)

Upvotes: 0

shafikshaon
shafikshaon

Reputation: 6414

Change this line listing_instance = form.save() to

listing_instance = form.save(commit=False)

Upvotes: 0

Related Questions