简体   繁体   中英

django form not saving on postgresql but does save to sqlite

I've deployed the project to Heroku. I'm using postgresql for my database.

The job is attached to a customer table using acct_no as the foreign key. I'm able to create customers using postgresql but I can't create a job.

I'm able to create a job using sqlite but when i attempt to use the postgresql database, the createview does not create a job and redirects me to my homepage. I'm fairly new to django and I've tried looking for similiar questions on here but have not been able to find a solution.

models.py

class Jobs(models.Model):
    id = models.IntegerField(db_column='ID', primary_key=True)  # Field name made lowercase.
    acct_no = models.ForeignKey(Customers, on_delete=models.CASCADE, default=1000000, db_column='ACCT_NO')  # Field name made lowercase.
    foreman = models.CharField(db_column='FOREMAN', max_length=45, blank=True, null=True)  
    comments = models.CharField(db_column='COMMENTS', max_length=255, blank=True, null=True)  # Field name made lowercase.

views.py

class JobCreateView(CreateView):
    model = Jobs
    template_name = 'new_job.html'
    form_class = JobForm


    def get_initial(self):
        initial = super(JobCreateView, self).get_initial()
        initial['acct_no'] = Customers.objects.get(pk = self.kwargs['pk'])
        return initial


    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        customer = Customers.objects.get(pk = self.kwargs['pk'])
        context["customer"] = customer
        return context


    def get_success_url(self):
        return reverse_lazy('CustomerView', kwargs = {'pk':self.kwargs['pk']})

forms.py

class JobForm(forms.ModelForm):
    class Meta:
        model = Jobs
        fields = ['acct_no', 'job_type', 'estimatedate', 'estimatetime', 'vacant', 'year_built', 'comments']

        labels = {
            'job_type' : 'Job Type* ',
            'estimatedate' : 'Estimate Date', 
            'estimatetime' : 'Estimate Time'
        }

        widgets = {
            'acct_no' : forms.HiddenInput(attrs={'class' : 'form-control form-select' }), # foreign key
            'job_type' : forms.Select(choices = JOBS, attrs={'class' : 'form-control form-select' }),
            'estimatedate' : widgets.DateInput(attrs={'type' : 'date', 'class' : 'form-control'}),
            'estimatetime' : widgets.TimeInput(attrs={'type' : 'time', 'class' : 'form-control'}),
            'vacant' : forms.Select(choices = CHOICES,attrs={'class' : 'form-control form-select' }),
            'year_built' : forms.Select(choices = YEAR_LIST, attrs={'class' : 'form-control form-select' }),
            'comments' : forms.Textarea(attrs={'class' : 'form-control'})
        }

urls.py

path('new_job/<pk>', my_login_required(JobCreateView.as_view()), name = 'new_job'),

**edit

settings.py

import os
from pathlib import Path
import django_js_reverse


BASE_DIR = Path(__file__).resolve().parent.parent

SECRET_KEY = '***'

DEBUG = False

ALLOWED_HOSTS = ['***', 'localhost']

INSTALLED_APPS = [

    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'core',
    'customers',
    'jobs',
    'django_js_reverse',
    'simplejson',
    'rest_framework'
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'whitenoise.middleware.WhiteNoiseMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django_session_timeout.middleware.SessionTimeoutMiddleware'
]

ROOT_URLCONF = '***'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [BASE_DIR / 'templates'],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',

            ],
        },
    },
]

WSGI_APPLICATION = '***'


DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'NAME': '***',
        'USER': '***',
        'PASSWORD': '***',
        'HOST': '***',
        'PORT': '***',
    }
}

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]


This the first question I've asked on here so if I didnt provide enough info, let me know and I'll add whatever is needed. Thanks for any help or ideas!

I believe your settings.py file might be missing what Heroku needs in order to connect to the database. This is assuming your Heroku database credentials match up with the values you've hidden ("***") in the database configuration.

    DATABASES = {
        'default': {
            ...
            'CONN_MAX_AGE': 500
            ...

or

    import dj_database_url
    DATABASES['default'] = dj_database_url.config(conn_max_age=600, ssl_require=True)

If you're using the dj-database-url .

Source: Heroku

Edit:

Try removing 'acct_no' from the JobForm, since it's a hidden input. Then instead of the get_initial method try using form_valid:

    def form_valid(self, form):
        customer = Customers.objects.get(pk = self.kwargs['pk'])
        form.instance.acct_no = customer
        return super(JobCreateView. self).form_valid(form)

Source: Django CreateView get_initial Foreign Key

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