简体   繁体   English

django 表单不保存在 postgresql 但确实保存到 sqlite

[英]django form not saving on postgresql but does save to sqlite

I've deployed the project to Heroku.我已将项目部署到 Heroku。 I'm using postgresql for my database.我正在为我的数据库使用 postgresql。

The job is attached to a customer table using acct_no as the foreign key.该作业使用 acct_no 作为外键附加到客户表。 I'm able to create customers using postgresql but I can't create a job.我可以使用 postgresql 创建客户,但无法创建工作。

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.我可以使用 sqlite 创建作业,但是当我尝试使用 postgresql 数据库时,createview 不会创建作业并将我重定向到我的主页。 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.我对 django 相当陌生,我尝试在这里寻找类似的问题,但未能找到解决方案。

models.py模型.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视图.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 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网址.py

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

**edit **编辑

settings.py设置.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.我相信您的 settings.py 文件可能缺少 Heroku 连接数据库所需的内容。 This is assuming your Heroku database credentials match up with the values you've hidden ("***") in the database configuration.这是假设您的 Heroku 数据库凭据与您在数据库配置中隐藏的值(“***”)匹配。

    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 .如果您使用的是dj-database-url

Source: Heroku来源: Heroku

Edit:编辑:

Try removing 'acct_no' from the JobForm, since it's a hidden input.尝试从 JobForm 中删除 'acct_no',因为它是隐藏的输入。 Then instead of the get_initial method try using form_valid:然后尝试使用 form_valid 代替 get_initial 方法:

    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来源: Django CreateView get_initial 外键

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM