how to look over all form fields provided and updating the model

时间:2015-11-12 11:12:38

标签: django database forms modelform

I've created a Django view that does 2 things:

  1. Create a new account
  2. Modify a account

Works: Creating new account and submitting the HTML form data to the database. Also works: showing a prefilled HTML form if user wants to modify an account with the account data that is known in the database.

Doesnt work: When the user submits his/her form to update an account (user modified the info in the form), nothing is updated in the database.

I know how to update one single static value in the database like so:

        a = accounts.objects.filter(pk=account_id).update(name='static value here')

but I don't know how to update the database with all the form data that the user submits when using Django Modelforms. Does anyone knows how to update the database with the submitted form data?

Code

    @login_required(login_url='/dashboard/')
def dashboard_accounts_new_modify(request, account_id=None):

    if request.method == 'POST':

        # POST DETECTED

        form = MyModelForm(request.POST, request.FILES)

        if account_id:

            # POST DETECTED
            # ACCOUNT ID FOUND
            # USER WANTS TO MODIFY A ACCOUNT

            # WITH THIS QUERY I CAN UPDATE 1 STATIC VALUE IN THE DATABASE
            # HOW DO I UPDATE THE VALUES FROM THE FORM IN THE DATABASE?? :(
            a = accounts.objects.filter(pk=account_id).update(name='static value here')

            return HttpResponseRedirect('/dashboard/accounts/')

        else:

            # POST DETECTED
            # ACCOUNT ID NOT FOUND
            # USER WANTS TO CREATE A NEW ACCOUNT

            if form.is_valid():

                if request.POST.get("name").lower() == 'new':
                    raise Http404("New account name may not be named NEW.")

                # DATAHASE QUERY: ADD NEW ACCOUNT TO DATABASE
                form.save()

                # REDIRECT
                return HttpResponseRedirect('/dashboard/accounts/')

    elif account_id:

        # NO POST DETECTED
        # ACCOUNT ID FOUND
        # PREFILL FORM WITH DATA 

        try:
            from django.forms.models import model_to_dict
            a = accounts.objects.get(pk=account_id)
            form = MyModelForm(initial=model_to_dict(a))
        except:
            raise Http404("Account not found.")
    else:
        # NO POST DETECTED
        # MODIFICATION IS NOT DETECTED
        # LOAD EMPTY FORM

        form = MyModelForm()

    return render(request, 'backend/base_accounts_new.html', {'Title': 'Accounts', 'form' : form})

Model

# Clientdatabase
class accounts(models.Model):
    name = models.CharField(max_length=200)
    url = models.CharField(max_length=200)
    website_title = models.CharField(max_length=200)    
    website_h1_text = models.CharField(max_length=200)
    website_h2_text = models.CharField(max_length=200)
    website_search_text = models.CharField(max_length=200)
    website_font = models.CharField(max_length=200) 
    website_footer_left = models.CharField(max_length=600)
    website_footer_right = models.CharField(max_length=600)
    website_color_code_search_button = models.CharField(max_length=200)
    website_color_code_banner = models.CharField(max_length=200)
    website_logo_height_pixels = models.PositiveIntegerField()
    website_logo_width_pixels = models.PositiveIntegerField()
    filepath_favicon = models.FileField()
    filepath_logo_vector = models.FileField()
    filepath_logo_normal = models.FileField()
    filepath_background_1 = models.FileField()
    filepath_background_2 = models.FileField(blank=True, null=True)
    filepath_background_3 = models.FileField(blank=True, null=True)
    filepath_background_4 = models.FileField(blank=True, null=True)
    setting_background_1_active = models.BooleanField()
    setting_background_2_active = models.BooleanField()
    setting_background_3_active = models.BooleanField()
    setting_background_4_active = models.BooleanField()

    def __str__(self):
        return self.name

class AccountsForm(ModelForm):
    class Meta:
        model = accounts
        fields = '__all__'

1 个答案:

答案 0 :(得分:1)

You can do like:

from django.shortcuts import get_object_or_404

if request.method == 'POST':
    if account_id::
        account = get_object_or_404(accounts, pk=account_id)
        form = MyModelForm(request.POST,request.FILES, instance=account)
        if form.is_valid():
            ...
            form.save()
            return HttpResponseRedirect('/dashboard/accounts/')
    else:
        form = MyModelForm(request.POST, request.FILES)
        if form.is_valid():
            if request.POST.get("name").lower() == 'new':
                raise Http404("New account name may not be named NEW.")
            form.save()

Learn more about forms here

相关问题