0

Basically I have set up a form to create organizations. When I hit the Save button, it simply renders the page again - the POST is not working.

See my code below:

models.py

from django.db import models
from accounts.models import User
from datetime import datetime, date

#// ------------ FUNCTIONS -------------//

# Generate Organisation IDs for each organisation
def org_id_generate():
    last_org = Organization.objects.all().order_by('org_id').last()
    if not last_org:
        return 'ORG_001'
    else:
        last_org_id = last_org.org_id
        number_in_id = int(last_org_id[4:7])
        new_number_in_id = number_in_id + 1
        new_org_id = 'ORG_' + str(new_number_in_id).zfill(3)
        return new_org_id

#// ------------ MODELS -------------//

class Organization(models.Model):

    org_id = models.CharField(primary_key=True, max_length=7, default=org_id_generate, editable=False)
    organization_code = models.CharField(max_length=20)
    company_name = models.CharField(verbose_name="Company Name", max_length=60)
    legal_name = models.CharField(verbose_name="Legal Name", max_length=100)
    industry_distribution = models.BooleanField(verbose_name="Distribution", default=False)
    industry_education = models.BooleanField(verbose_name="Education", default=False)
    industry_healthcare = models.BooleanField(verbose_name="Healthcare", default=False)
    industry_manufacturing = models.BooleanField(verbose_name="Manufacturing", default=False)
    industry_retail = models.BooleanField(verbose_name="Retail", default=False)
    industry_services = models.BooleanField(verbose_name="Services", default=False)
    business_registration_no = models.CharField(verbose_name="Business Registration Number", max_length=15, blank=True)
    vat_registration_no = models.CharField(verbose_name="VAT Registration Number", max_length=15, blank=True)
    created_date = models.DateTimeField(default=datetime.now)
    created_by = models.ForeignKey(User, on_delete=models.DO_NOTHING, related_name="Created_By", verbose_name="Created By")
    effective_start_date = models.DateField(auto_now_add=False)
    effective_end_date = models.DateField(auto_now_add=False, blank=True, null=True)
    update_date = models.DateTimeField(default=datetime.now)
    last_updated_by = models.ForeignKey(User, on_delete=models.DO_NOTHING, related_name="Last_Updated_By", verbose_name="Last Updated By")

    def __str__(self):
        return self.company_name

forms.py

from django import forms
from organizations.models import Organization

class OrganizationAddForm(forms.ModelForm):
    class Meta:
        model = Organization
        exclude = ['created_date', 'update_date', ]

views.py

from django.shortcuts import get_object_or_404, render, redirect
from organizations.models import Organization
from forms import OrganizationAddForm
from accounts.models import User
from django.contrib.auth.decorators import login_required

@login_required()
def settings(request):
    return render(request, 'settings/settings.html')

@login_required()
def organizations_settings(request):
    orgs = Organization.objects.all()

    context = {
        'orgs': orgs,
    }
    return render(request, 'settings/settings_organizations.html', context)

@login_required
def organization_add(request):
    if request.method == 'POST':
        user_email = request.user.email
        form = OrganizationAddForm(request.POST)
        if form.is_valid():
            form.organization_code = form.cleaned_data['organization_code']
            form.company_name = form.cleaned_data['company_name']
            form.legal_name = form.cleaned_data['legal_name']
            form.business_registration_no = form.cleaned_data['brn']
            form.vat_registration_no = form.cleaned_data['vat']
            form.industry_distribution = form.cleaned_data['industry_distribution']
            form.industry_education = form.cleaned_data['industry_education']
            form.industry_healthcare = form.cleaned_data['industry_healthcare']
            form.industry_manufacturing = form.cleaned_data['industry_manufacturing']
            form.industry_retail = forms.cleaned_data['industry_retail']
            form.industry_services = form.cleaned_data['industry_services']
            form.effective_start_date = form.cleaned_data['effective_start_date']
            form.effective_end_date = form.cleaned_data['effective_end_date']
            form.created_by = form.cleaned_data[user_email]
            form.last_updated_by = form.cleaned_data[user_email]

            form.save()
            return redirect('organizations_settings')

    else:
        form = OrganizationAddForm()

    return render(request, 'settings/add_organization.html', {'form': form})

urls.py

from django.urls import path
from . import views

urlpatterns = [
    path('', views.settings, name="settings"),
    path('organizations/', views.organizations_settings, name='organizations_settings'),
    path('organization_create', views.organization_create, name="organization_create"),
    path('organizations/add/', views.organization_add, name="organization_add"),
]

Page Source Code

<!-- Add Organization Form -->
<div class="container form-style">
    <a href="{% url 'organizations_settings' %}"><i class="fas fa-arrow-left"></i> Back</a>
    <div class="form-header">
        <h3>Add Organization</h3>
    </div>
    <form action="{% url 'organization_add' %}" method="POST">
        {% csrf_token %}

        <div class="container">

            <!-- Row 1 -->
            <div class="row">
                <div class="col-md-4">
                    <label for="organization_code">Organization Code<span class="star-red">*</span></label>
                    <input type="text" name="organization_code" class="form-control" required>
                </div>
                <div class="col-md-4">
                    <label for="company_name">Organization Name<span class="star-red">*</span></label>
                    <input type="text" name="company_name" class="form-control" required>
                </div>
                <div class="col-md-4">
                    <label for="legal_name">Legal Name<span class="star-red">*</span></label>
                    <input type="text" name="legal_name" class="form-control" required>
                </div>
            </div>

            <!-- Row 2 -->
            <div class="row mt-4">
                <!--                                <div class="col-md-4">
                    <label for="industry">Industry<span class="star-red">*</span></label>
                    <select name="industry" class="selectpicker">
                        <option value="distribution">Distribution</option>
                        <option value="education">Education</option>
                        <option value="healthcare">Healthcare</option>
                        <option value="manufacturing">Manufacturing</option>
                        <option value="retail">Retail</option>
                        <option value="services">Services</option>
                    </select>
                </div> -->
                <div class="col-md-6">
                    <label for="brn">Business Registration No.</label>
                    <input type="text" name="brn" class="form-control">
                </div>
                <div class="col-md-6">
                    <label for="vat">VAT Registration No.</label>
                    <input type="text" name="vat" class="form-control">
                </div>
            </div>

            <!-- Row 3 -->
            <h5 class="mt-4">Industry</h5>
            <div class="row">
                <div class="col-md-4">
                    <div class="form-check">
                        <input type="checkbox" name="industry_distribution" class="form-check-input">
                        <label for="industry_distribution" class="form-check-label">Distribution</label>
                    </div>
                </div>

                <div class="col-md-4">
                    <div class="form-check">
                        <input type="checkbox" name="industry_education" class="form-check-input">
                        <label for="industry_education" class="form-check-label">Education</label>
                    </div>
                </div>

                <div class="col-md-4">
                    <div class="form-check">
                        <input type="checkbox" name="industry_healthcare" class="form-check-input">
                        <label for="industry_healthcare" class="form-check-label">Healthcare</label>
                    </div>
                </div>
            </div>
            <div class="row mt-2">
                <div class="col-md-4">
                    <div class="form-check">
                        <input type="checkbox" name="industry_manufacturing" class="form-check-input">
                        <label for="industry_manufacturing" class="form-check-label">Manufacturing</label>
                    </div>
                </div>

                <div class="col-md-4">
                    <div class="form-check">
                        <input type="checkbox" name="industry_retail" class="form-check-input">
                        <label for="industry_retail" class="form-check-label">Retail</label>
                    </div>
                </div>

                <div class="col-md-4">
                    <div class="form-check">
                        <input type="checkbox" name="industry_services" class="form-check-input">
                        <label for="industry_services" class="form-check-label">Services</label>
                    </div>
                </div>
            </div>

            <!-- Row 4 -->
            <div class="row mt-4">
                <div class="col-md-6">
                    <label for="effective_start_date">Effective Start Date<span class="star-red">*</span></label>
                    <input type="date" name="effective_start_date" class="form-control" required>
                </div>
                <div class="col-md-6">
                    <label for="effective_end_date">Effective End Date:</label>
                    <input type="date" name="effective_end_date" class="form-control">
                </div>
            </div>

            <!-- Hidden Input - User -->
            <input type="hidden" name="user_email" />


            <div class="float-right mt-3">
                <button type="submit" class="btn btn-custom save">Save and Close</button>
            </div>

        </div>

    </form>

</div>

Any help would be greatly appreciated. If you need any additional info, let me know and I will edit the post.

pH4nT0M
  • 175
  • 2
  • 10

2 Answers2

0

I did not find any code to show the errors in html. According to the function in views, if the form is not valid, then it renders the page with the form. Try to add {{form.errors}} to you the html file to see if it has errors?

Mas Zero
  • 503
  • 3
  • 16
  • Hi thank you for your reply! When I do that, I get the following created_by This field is required. last_updated_by This field is required. – pH4nT0M Sep 14 '20 at 07:45
  • @pH4nT0MThose are just the errors of the form because you defined `created_by` and `last_updated_by` fields in your model. so they are required. – Mas Zero Sep 14 '20 at 08:45
  • Yes indeed thank you very much! I managed to solve it! – pH4nT0M Sep 14 '20 at 09:55
0

I managed to solve it.

views.py

@login_required
def organization_add(request):
    if request.method == 'POST':
        form = OrganizationAddForm(request.POST)
        if form.is_valid():
            form.organization_code = form.cleaned_data['organization_code']
            form.company_name = form.cleaned_data['company_name']
            form.legal_name = form.cleaned_data['legal_name']
            form.business_registration_no = form.cleaned_data['business_registration_no']
            form.vat_registration_no = form.cleaned_data['vat_registration_no']
            form.industry_distribution = form.cleaned_data['industry_distribution']
            form.industry_education = form.cleaned_data['industry_education']
            form.industry_healthcare = form.cleaned_data['industry_healthcare']
            form.industry_manufacturing = form.cleaned_data['industry_manufacturing']
            form.industry_retail = form.cleaned_data['industry_retail']
            form.industry_services = form.cleaned_data['industry_services']
            form.effective_start_date = form.cleaned_data['effective_start_date']
            form.effective_end_date = form.cleaned_data['effective_end_date']
            
            org = form.save(commit=False)

            org.created_by = request.user
            org.last_updated_by = request.user

            org.save()
            return redirect('organizations_settings')

    else:
        form = OrganizationAddForm()

    return render(request, 'settings/add_organization.html', {'form': form})

The issue was that it was not able to capture the user email for the Created By and Last Updated By fields.

This is resolved by using:

org = form.save(commit=False)

org.created_by = request.user
org.last_updated_by = request.user

Note that the following two posts helped me:

Using request.user with Django ModelForm

Cannot assign "42": "Event.user_id" must be a "User" instance

pH4nT0M
  • 175
  • 2
  • 10