Django: невозможно записать файл из ModelForm на Apache и Mod_wsgi - PullRequest
0 голосов
/ 10 апреля 2020

У меня есть сайт Django 3.0.3, работающий на RHEL 7 и Apache, использующий mod_wsgi. На моей машине разработки (Windows) я могу сохранить файл через тип поля FileField. Однако при развертывании в рабочей среде (RHEL 7 и Apache с использованием mod_wsgi) при попытке сохранить файл выдается ошибка «[ErrNo 13] Permission denied».

Я установил права доступа к папке для drwxrwxrwx. для папки MEDIA_ ROOT для пользователя apache с именем "apache" в моем случае (что подтверждается как вызовом getpass.getuser () внутри программы, так и настройками httpd conf. Это также имя, указанное в mod_wsgi.process_group на странице отладки Django.

Я включил свой соответствующий код и отладку:

Отладка

Environment:


Request Method: POST
Request URL: https://www.samplesite.com/samples/addpatient/

Django Version: 3.0.3
Python Version: 3.7.1
Installed Applications:
['samples.apps.SamplesConfig',
 'django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'bootstrap3',
 'django.contrib.staticfiles',
 'notifications']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
 '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']



Traceback (most recent call last):
  File "/opt/djangoproject/djangoprojectenv3/lib/python3.7/site-packages/django/core/handlers/exception.py", line 34, in inner
    response = get_response(request)
  File "/opt/djangoproject/djangoprojectenv3/lib/python3.7/site-packages/django/core/handlers/base.py", line 115, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "/opt/djangoproject/djangoprojectenv3/lib/python3.7/site-packages/django/core/handlers/base.py", line 113, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "/opt/djangoproject/djangoprojectenv3/lib/python3.7/site-packages/django/views/generic/base.py", line 71, in view
    return self.dispatch(request, *args, **kwargs)
  File "/opt/djangoproject/djangoprojectenv3/lib/python3.7/site-packages/django/contrib/auth/mixins.py", line 52, in dispatch
    return super().dispatch(request, *args, **kwargs)
  File "/opt/djangoproject/djangoprojectenv3/lib/python3.7/site-packages/django/views/generic/base.py", line 97, in dispatch
    return handler(request, *args, **kwargs)
  File "/opt/djangoproject/djangoprojectenv3/lib/python3.7/site-packages/django/views/generic/edit.py", line 172, in post
    return super().post(request, *args, **kwargs)
  File "/opt/djangoproject/djangoprojectenv3/lib/python3.7/site-packages/django/views/generic/edit.py", line 142, in post
    return self.form_valid(form)
  File "/opt/djangoproject/biomarker2/samples/views.py", line 315, in form_valid
    return super(PatientCreate, self).form_valid(form) #PatientCreate, self
  File "/opt/djangoproject/djangoprojectenv3/lib/python3.7/site-packages/django/views/generic/edit.py", line 125, in form_valid
    self.object = form.save()
  File "/opt/djangoproject/djangoprojectenv3/lib/python3.7/site-packages/django/forms/models.py", line 459, in save
    self.instance.save()
  File "/opt/djangoproject/djangoprojectenv3/lib/python3.7/site-packages/django/db/models/base.py", line 746, in save
    force_update=force_update, update_fields=update_fields)
  File "/opt/djangoproject/djangoprojectenv3/lib/python3.7/site-packages/django/db/models/base.py", line 784, in save_base
    force_update, using, update_fields,
  File "/opt/djangoproject/djangoprojectenv3/lib/python3.7/site-packages/django/db/models/base.py", line 887, in _save_table
    results = self._do_insert(cls._base_manager, using, fields, returning_fields, raw)
  File "/opt/djangoproject/djangoprojectenv3/lib/python3.7/site-packages/django/db/models/base.py", line 926, in _do_insert
    using=using, raw=raw,
  File "/opt/djangoproject/djangoprojectenv3/lib/python3.7/site-packages/django/db/models/manager.py", line 82, in manager_method
    return getattr(self.get_queryset(), name)(*args, **kwargs)
  File "/opt/djangoproject/djangoprojectenv3/lib/python3.7/site-packages/django/db/models/query.py", line 1204, in _insert
    return query.get_compiler(using=using).execute_sql(returning_fields)
  File "/opt/djangoproject/djangoprojectenv3/lib/python3.7/site-packages/django/db/models/sql/compiler.py", line 1383, in execute_sql
    for sql, params in self.as_sql():
  File "/opt/djangoproject/djangoprojectenv3/lib/python3.7/site-packages/django/db/models/sql/compiler.py", line 1328, in as_sql
    for obj in self.query.objs
  File "/opt/djangoproject/djangoprojectenv3/lib/python3.7/site-packages/django/db/models/sql/compiler.py", line 1328, in <listcomp>
    for obj in self.query.objs
  File "/opt/djangoproject/djangoprojectenv3/lib/python3.7/site-packages/django/db/models/sql/compiler.py", line 1327, in <listcomp>
    [self.prepare_value(field, self.pre_save_val(field, obj)) for field in fields]
  File "/opt/djangoproject/djangoprojectenv3/lib/python3.7/site-packages/django/db/models/sql/compiler.py", line 1278, in pre_save_val
    return field.pre_save(obj, add=True)
  File "/opt/djangoproject/djangoprojectenv3/lib/python3.7/site-packages/django/db/models/fields/files.py", line 288, in pre_save
    file.save(file.name, file.file, save=False)
  File "/opt/djangoproject/djangoprojectenv3/lib/python3.7/site-packages/django/db/models/fields/files.py", line 87, in save
    self.name = self.storage.save(name, content, max_length=self.field.max_length)
  File "/opt/djangoproject/djangoprojectenv3/lib/python3.7/site-packages/django/core/files/storage.py", line 52, in save
    return self._save(name, content)
  File "/opt/djangoproject/djangoprojectenv3/lib/python3.7/site-packages/django/core/files/storage.py", line 267, in _save
    fd = os.open(full_path, self.OS_OPEN_FLAGS, 0o666)

Exception Type: PermissionError at /samples/addpatient/
Exception Value: [Errno 13] Permission denied: '/opt/djangoproject/biomarker2/samples/consents/Childrens/CTVI_-Statement_January_2019.pdf'

models.py

def user_directory_path(instance, filename):
    # file will be uploaded to MEDIA_ROOT/user_<id>/<filename>
    groupname = instance.submitting_group.name
    return '{0}/{1}'.format(''.join(filter(str.isalnum, groupname)), filename)
    #return '{0}/{1}'.format(groupname, filename)

class Patient(models.Model):
    consent = models.FileField(upload_to=user_directory_path, default='')

class PatientForm(ModelForm):
    #consent = forms.FileField() I commented out to make sure there wasn't a conflict between the two fields

    class Meta:
        model = Patient
        fields = ('consent')

views.py

class PatientCreate(LoginRequiredMixin, CreateView):  
    model = Patient
    form_class = PatientForm
    template_name = 'samples/patientadd.html'

   def form_valid(self, form):
        form.instance.submitting_user = self.request.user
        form.instance.submitting_group = self.request.user.groups.all()[0]
        form.instance.submitting_groupname = self.request.user.groups.all()[0].name
        #form.instance.nwewid = self.kwargs['pk']
        print(form.errors)
        #form.instance.immuno_used = json.dumps(form.cleaned_data['immuno_used'])
        #print(form.instance.immuno_used)
        #form.save()
        return super(PatientCreate, self).form_valid(form) #PatientCreate, self

settings.py

FILE_UPLOAD_DIRECTORY_PERMISSIONS = 775

STATIC_URL = '/static/'

MEDIA_ROOT = os.path.join(BASE_DIR,'consents')#this line is added and it serves as the root address of 
#uploaded file

MEDIA_URL = '/consents/'#this line is added and it creates a directory named media in your appfolder
#where the uploaded images will be stored
...