Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to instantiate a Django ModelForm with pre-filled required fields?
I have a subclass of ModelForm, FamilyDemographicsForm, for which two ChoiceFields are required: point_of_contact and birth_parent. For example, the following tests pass: class FamilyDemographicsFormTest(TestCase): def test_empty_form_is_not_valid(self): '''The choice fields 'point_of_contact' and 'birth_parent' are the only two required fields of the form''' form = FamilyDemographicsForm(data={}) # The form is not valid because the required fields have not been provided self.assertFalse(form.is_valid()) self.assertEqual(form.errors, {'point_of_contact': ['This field is required.'], 'birth_parent': ['This field is required.']}) def test_form_with_required_fields_is_valid(self): '''The form's save() method constructs the expected family''' data = {'point_of_contact': Family.EMPLOYEE, 'birth_parent': Family.PARTNER} form = FamilyDemographicsForm(data=data) self.assertTrue(form.is_valid()) # The family returned by saving the form has the expected attributes family = form.save() self.assertEqual(family.point_of_contact, Family.EMPLOYEE) self.assertEqual(family.birth_parent, Family.PARTNER) # The family exists in the database self.assertTrue(Family.objects.filter(id=family.id).exists()) In the second test case, a new instance of Family is created upon form.save(). I'd like to try instead to update an existing family. To get me started, I tried the following: def test_update_existing_family(self): initial = {'point_of_contact': Family.EMPLOYEE, 'birth_parent': Family.PARTNER} data = {'employee_phone': '4151234567', 'employee_phone_type': Family.IPHONE, 'partner_phone': '4157654321', 'partner_phone_type': Family.ANDROID} form = FamilyDemographicsForm(data=data, initial=initial) import ipdb; ipdb.set_trace() However, when I dropped into the debugger, I noticed that form.is_valid() is False and form.errors indicates that the required fields are not provided: ipdb> form.errors {'point_of_contact': … -
Django: ModelForm not binding to request.POST
I have the following model: class Tracking(models.Model): person = models.ForeignKey(Person, on_delete=models.CASCADE) week = models.IntegerField(choices=settings.WEEK_CHOICES, blank=True) term = models.IntegerField(choices=settings.TERM_CHOICES, blank=True) year = models.IntegerField(choices=settings.YEAR_CHOICES, blank=True) target = models.CharField(max_length=256, blank=True) monday = models.IntegerField() tuesday = models.IntegerField() wednesday = models.IntegerField() thursday = models.IntegerField() friday = models.IntegerField() which is linked to this form: class AddTrackingForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(AddTrackingForm, self ).__init__(*args, **kwargs) class Meta: model = models.Tracking fields = '__all__' Once a user fills out the form, I want to save the instance to the database: class TrackingView(generic.TemplateView): template_name = "tracking.html" def get(self, request, *args, **kwargs): form = forms.AddTrackingForm() form.fields['person'].queryset = models.Person.objects.filter(active=True).order_by('-last_name', '-first_name') return render(request, self.template_name, {'form': form, }) def post(self, request, *args, **kwargs): form = forms.AddTrackingForm(request.POST) if form.is_valid(): model_instance = form.save(commit=False) model_instance.student = models.Person.objects.get(id=int(request.POST['person'])) model_instance.save() return redirect('/tracking') However, the form.is_valid() never returns True. Printing out the errors gives me blank for form.errors and: <bound method BaseForm.non_field_errors of <AddTrackingForm bound=False, valid=False, fields=(person;week;term;year;b1;b2;monday;tuesday;wednesday;thursday;friday)>> for form.non_field_errors. No matter what I try, I can't get the instance to bind. I thought it might be that the post data is received as strings and not being valid data for the model.IntegerField()'s, so I might need to override form.clean() and cast all relevant fields to ints. However, that didn't … -
GET not functioning on ElasticBeanStalk properly but working in local
I have a filter that only takes data from a particular city when a user is in that particular city and renders it in the html. Now on my local machine this is running perfectly and I am able to see only venues, events and users from that particular city. However when I try run the same filter settings on the EC2 server from AWS I get the error as below. For some reason its failing to recognise the key in the request.If remove the request.session['city-name']: from both the venue and the teacher section of the view then the page loads without and error BUT it shows me data from all the cities and it is absolutely imperative that I only have data from the one city. To Set and Get citysession (last section of the view) which uses GET is working just fine so its strange that when connecting GET to the filter it then doesn't work. Even more so when working on local. Is this a problem of how the database was setup for example or a problem with AWS integration or something? I've also added the working view from local below. Like how do I rectify this? … -
Angular Electron Set Cookie: CSRF/XSRF token not working
I'm running a Angular 5 web app on electron. My Angular websites is connecting to my Django Server. When I run my website in chrome it works fine and gives these headers as a response: Proper response and the cookie csrf is set to whatever the server responded with. When I run it Electron however, I get this response saying that the csrf token is missing or invalid. Invalid response I'm using Rest-Auth for Django; Angular supports CSRTF out of the box just fine it's just that in electron it acts weird. I suppose it might be because Electron runs from file:// and not localhost and thus has problems with Set-Cookie headers but I'd have no clue how to fix that. I also tried possibly every CORS setting in Django. -
How to test an UpdateView form using assertFormError
I'd like to test a form similar to the way described in Shane's answer to How should I write tests for Forms in Django?: from django.tests import TestCase class MyTests(TestCase): def test_forms(self): response = self.client.post("/my/form/", {'something':'something'}) self.assertFormError(response, 'form', 'something', 'This field is required.') where 'form' is the context variable name for the form, 'something' is the field name, and 'This field is required.' is the exact text of the expected validation error. The form subclasses Django's generic UpdateView and is similar to the following: class FamilyUpdate(UpdateView): template_name = 'families/edit.html' model = Family def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) return context_data The Family object has a couple of required fields, point_of_contact and birth_parent. Here is an example of a test using the form object directly which passes: def test_empty_form_is_not_valid(self): '''The choice fields 'point_of_contact' and 'birth_parent' are the only two required fields of the form''' form = FamilyDemographicsForm(data={}) # The form is not valid because the required fields have not been provided self.assertFalse(form.is_valid()) self.assertEqual(form.errors, {'point_of_contact': ['This field is required.'], 'birth_parent': ['This field is required.']}) I'd like to do a similar test with an actual POST request to the form's URL. I've tried the following: def test_post_empty_dictionary_returns_error(self): response = self.client.post(self.url, {}) self.assertFormError(response, 'form', … -
django coverage fails to include most py files
I have run coverage on a project that I set up with cookie cutter for django. In the report, coverage includes the py files in the user app that cookie cutter set up for me, and includes my html templates, but does not include any of my py files. I want coverage to include my several py files under each of my 6 apps. What must I do? I attach a screen shot of my coverage report. The percentages are not bad, but my numerous .py files are not on the report. I am using the (lightly modified) test settings file that cookie cutter generated for me, to whit: from .base import * # noqa # DEBUG # ------------------------------------------------------------------------------ # Turn debug off so tests run faster DEBUG = False # coverage throws error unless the following is set to True TEMPLATES[0]['OPTIONS']['debug'] = True # SECRET CONFIGURATION # ------------------------------------------------------------------------------ # See: https://docs.djangoproject.com/en/dev/ref/settings/#secret-key # Note: This key only used for development and testing. SECRET_KEY = env('DJANGO_SECRET_KEY', default='CHANGEME!!!') # Mail settings # ------------------------------------------------------------------------------ EMAIL_HOST = 'localhost' EMAIL_PORT = 1025 # In-memory email backend stores messages in django.core.mail.outbox # for unit testing purposes EMAIL_BACKEND = 'django.core.mail.backends.locmem.EmailBackend' # CACHING # ------------------------------------------------------------------------------ # Speed advantages … -
Auto delete old database records in heroku server, django
I want that on the heroku server old records in db were deleted automatically (for testing, I took an interval of 1 minute). I'm trying to use a clock process but there were problems. My clock.py is import django django.setup() from apscheduler.schedulers.blocking import BlockingScheduler from shortener.models import ShortURL from datetime import datetime, timedelta from django.utils import timezone # from url_shortener.settings import SHORT_URL_LIFE_TIME sched = BlockingScheduler() @sched.scheduled_job('interval', minutes=1) def timed_job(): ShortURL.objects.filter(creation_date__lte=timezone.now() - timedelta(minutes=1)).delete() sched.start() Initially, the following errors occurred(heroku logs): 2018-02-14T17:57:55.414258+00:00 app[clock.1]: django.core.exceptions. ImproperlyConfigured: Requested setting SHORTCODE_MIN, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. and 2018-02-14T18:04:09.135029+00:00 app[clock.1]: django.core.exceptions. AppRegistryNotReady: Apps aren't loaded yet. 2018-02-14T18:04:09.134985+00:00 app[clock.1]: raise AppRegistryNotReady("Apps aren't loaded yet.") Which I fixed by setting an environment variable: heroku config:set DJANGO_SETTINGS_MODULE=url_shortener.settings and adding the django import to the beginning of the clock.py import django django.setup() But now I have a message that the process was exited with code 143 and auto delete obvious don't work: 2018-02-14T19:13:02.608394+00:00 heroku[clock.1]: Idling 2018-02-14T19:13:02.610605+00:00 heroku[clock.1]: State changed from up to down 2018-02-14T19:13:02.628858+00:00 heroku[web.1]: Idling 2018-02-14T19:13:02.628858+00:00 heroku[web.1]: State changed from up to down 2018-02-14T19:13:03.601709+00:00 heroku[web.1]: Stopping all processes with SIGTERM 2018-02-14T19:13:03.702294+00:00 heroku[clock.1]: Stopping all processes … -
DRF - 'str' object has no attribute 'pk'
I've got a front-end that sends JSON to the back-end to switch the input of a digital audio stream, with an optional time component to schedule the switch for the future. Here are the components of making this work: from views.py: class SwitchStreamView(views.APIView): """ A custom endpoint for switching inputs of radio streams """ queryset = RadioStream.objects.all() def post(self, request, format=None): serializer = serializers.RadioSwitchSerializer(data=request.data, many=True) serializer.is_valid() for stream in serializer.data: if stream.schedule_time is None: tasks.switch_stream(stream.mnemonic, stream.current_input) else: tasks.schedule_switch(stream.mnemonic, stream.current_input, stream.schedule_time) return HttpResponse('') from serializers.py: class RadioSwitchSerializer(serializers.ModelSerializer): schedule_time = serializers.SerializerMethodField() def get_schedule_time(self, obj): return obj.get('schedule_time', None) class Meta: model = RadioStream fields = ('mnemonic', 'current_input', 'schedule_time') The issue I'm having is that however I try and send a test JSON snippet, I'm getting errors. With this setup, sending [ { "mnemonic": "TEST", "current_input": "TEST" } ] results in the error 'str' object has no attribute 'pk', but if I change RadioSwitchSerializer(data=request.data, many=True) to many=False, and send { "mnemonic": "TEST", "current_input": "TEST" } I get the response 'str' object has no attribute 'schedule_time' instead. My plan was to use mnemonic to identify the stream, and current_input to identify which input to switch it to. My questions are; Why is this not working, … -
How to get more than one datepicker in Django forms?
I am using django-bootstrap3 (pip install django-bootstrap3) third party application to render forms and I am using django-bootstrap-datepicker (pip install django-bootstrap-datepicker) application to apply widget calendar. In the following form, I have two fields: check_in and check_out which I want apply the date-picker to together from bootstrap_datepicker.widgets import DatePicker class DateInput(DatePicker): def __init__(self): DatePicker.__init__(self,format="%Y-%m-%d") def build_attrs(self, attrs, extra_attrs=None, **kwargs): attrs = dict(self.attrs, **kwargs) if extra_attrs: attrs.update(extra_attrs) return attrs class LodgingOfferForm(forms.ModelForm): class Meta: widgets = { 'check_in': DateInput(), 'check_out': DateInput(), } model = LodgingOffer fields = ('other fields', 'check_in', 'check_out', ) In my template html I am render the forms of this way, including form.media to accept js and css effects of bootstrap-datepicker: {% load bootstrap3 %} {% block body_content %} {% block extrahead %} {# Extra Resources Start #} {{ form.media }} {# Form required JS and CSS #} {% endblock %} {% bootstrap_field form.check_in %} {% bootstrap_field form.check_out %} {% endblock %} And when I render my form, the date-picker effect it's only apply to first field rendered in the form, this mean that the just check_in field have the date-picker effect and check_out field does not have it. Check in field Check out field I have been lookup … -
POST on static file (Django+gunicorn+nginx)
I'm working on a school project where I was given a folder with all front-end files of a webserver (index.html, css, javascript files...). I musn't modify these files, but I must recreate all the back-end part. I used the popular Django+gunicorn+nginx association to handle Ajax/CGI interactions. I put all the front-end files in the static folder, and the python scripts for CGI responses are in another folder (the urls are redirected as wanted by the javascript code). Static files are directly served by Nginx (configuration file below). But now I face an issue that I can't solve by myself (tried a lot a things, but I'm too lost). As I can tell thanks to Chrome Developer's tool, the javascript also make POST requests on the index.html (http://localhost/index.html?path=%5Capp%5Ccfg) in order to create/update files (with multipart/form-data). Theses requests happen without any problem (Status Code:200 OK) but the files aren't created. Because of that, the page won't load completely. Maybe there is a way to intercept these special POST requests, what do you think ? I hope I'm clear enough, don't hesitate to ask questions if needed. Nginx configuration file : upstream test_server { server unix:/var/www/test/run/gunicorn.sock fail_timeout=10s; } server { listen 80; server_name … -
How can I use Object from foreign Key in Django 1.11
I'd like to select the value of name from a Object. forms.py class ProjetoForm(BaseForm): preview = [f.name for f in Projeto._meta.get_fields()] fk_entidade_proponente = forms.ModelChoiceField(queryset=Entidade.objects.values('no_entidade'), widget=forms.Select(attrs={'class':'form-control'}), to_field_name="no_entidade") class Meta: model = Projeto fields = get_fields(model) views.py def handle_projeto(request, pk=None, pkdelete=None): return render(request, 'administracao/projeto2.html', { 'content_title': 'Manter Projeto', 'form': ProjetoForm() }) template <label for="name" class="control-label col-sm-2">Entidade Proponente</label> <div class="col-sm-10"> {{ form.fk_entidade_proponente}} <div class="help-block">{{ form.fk_entidade_proponente.errors }}</div> </div> Models.py fk_entidade_proponente = models.ForeignKey('Entidade', on_delete=models.CASCADE, related_name='proponente') B ut when I render in template I receive this key/value, but I'd like to select only value in view. Follow the image. I'd like to render only the name of Entidade, skdlsdk -
Passing the include tag via django admin (or database)
I have a template where most of the content is text based. I enter all the data, including the html formatting etc. by entering information into my database (PostGRESql). Within the template, I'm using |safe command so that the html commands are executed. Now, on some of the pages, I need to inherit another django template. I tried using {% include "snippet_template.html" with word="random_term" %} (thanks to a SO user, @bonidjukic). The problem I am running into is that the whole thing just gets printed as text. django is treating it as text, rather than treating it as code/command despite the use of {% %} and |safe. Any thoughts on how to move around this situation? Thanks so much, in advance. -
Custom column on django-tables2 that mix multiple foreignkeys
I am trying to make a custom column on django-tables2 with a function that returns the field that is not empty from 3 possibles foreign keys (just one can be not empty). Here is what I've done: Models.py class Sitiocancelado(models.Model): x = models.OneToOneField(X, on_delete=models.CASCADE, null=True,blank=True) y = models.OneToOneField(Y, on_delete=models.CASCADE, null=True, blank=True) z = models.OneToOneField(Z, on_delete=models.CASCADE, null=True, blank=True) fecha_de_cancelacion = models.DateField(null=True, blank=True) comentarios = models.TextField(max_length=200, null=True, blank=True) slug = models.SlugField(max_length=100, editable=False) def __str__(self): return self.z.y.x.nombre_del_sitio Tables.py class SitiocanceladoTable(tables.Table): def columna_combinada(table): if x == None: if y == None: return z else: return y else: return x Sitio = tables.Column(columna_combinada) class Meta: model = Sitiocancelado attrs = { 'class': 'table table-striped table-bordered', 'id': 'example', 'width' : '100%', } fields = ('Sitio',) exclude = ('id', 'slug','sitioproyecto', 'sitiocontratado', 'sitiooperando',) Does it make any sense? -
Pipenv packages not showing when I pip freeze, can't use the packages, but they're in pipfile.lock
At my desk, running Windows 10, I use pipenv to install django==1.11, and I can pip freeze, and see django listed. On my laptop, running Windows 7 Professional SP1, I use pipenv to install django==1.10, but pip freeze doesn't list django. When I check pipfile.lock, I see django in there. After uninstalling all pipenv packages and pip, updating both Python 2.7 and 3.4, reinstalling pip and pipenv, I started a new pipenv: Creating a virtualenv for this project. Using C:\Python27\python.exe to create virtualenv. Running virtualenv with interpreter C:\Python27\python.exe New python executable in C:\Project\Scri... xe Installing setuptools, pip, wheel...done. Virtualenv location: C:\Project\ Installing django==1.10. Collecting django==1.10 Using cached Django-1.10-py2.py3-none-any.whl Installing collected packages: django Successfully installed django-1.10 Adding django==1.10 to Pipfile's [packages]ÔǪ Locking [dev-packages] dependencies. Locking [packages] dependencies. Updated Pipfile.lock (93acb4)! PS C:\Projects> cat pipfile [[source]] url = "https://pypi.python.org/simple" verify_ssl = true name = "pypi" [dev-packages] [packages] django = "==1.10" PS C:\Project> cat pipfile.lock { "_meta": { "hash": { "sha256": "92bc94ea06d9cf8e2f7b9ed1628d1036db1bce0bb20f920009e9f6dba093acb4" }, "host-environment-markers": { "implementation_name": "cpython", "implementation_version": "0", "os_name": "nt", "platform_machine": "AMD64", "platform_python_implementation": "CPython", "platform_release": "7", "platform_system": "Windows", "platform_version": "6.1.7601", "python_full_version": "2.7.14", "python_version": "2.7", "sys_platform": "win32" }, "pipfile-spec": 6, "requires": {}, "sources": [ { "name": "pypi", "url": "https://pypi.python.org/simple", "verify_ssl": true } ] … -
Issue with django/postgresql when django started from cron
I have a fairly simple django (1.11) project using the rest_framework that works fine when I start it from the command line, typing nohup python manage.py runserver 0.0.0.0:4448 & on centos. Connects to a postgresql database, with DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'my_database', 'USER': 'my_user', #'PASSWORD': 'mypassword', 'HOST': '127.0.0.1', ' PORT': '5432', } } in my settings.py file. However if I set up the runserver command to run at boot time from a cron I get the following when I send a request to the application: ... lot of stuff django.db.utils.OperationalError: could not connect to server: Connection refused Is the server running on host "127.0.0.1" and accepting TCP/IP connections on port 5432? and in my pg_hba file I have IPv4 local connections: host all all 127.0.0.1/32 trust # local host host all all 10.2.11.53/32 trust host all my_user 0.0.0.0/0 trust and also I have netstat -plunt | grep post tcp 0 0 10.2.11.53:5432 0.0.0.0:* LISTEN 867/postmaster tcp 0 0 127.0.0.1:5432 0.0.0.0:* LISTEN 867/postmaster Any suggestion? Thanks, a -
Tag or inherit the same code in Django template with minor changes
I have a bunch of code that I will need to use repeatedly on a page, and on multiple pages. For example, here is a shorter version of the code: <a href="#" data-toggle="popover" title="{% for terms in s_terms %}{% if terms.slug == 'neuron' %}{{terms.title}}{% endif %}{% endfor %}" data-content="{% for terms in s_terms %}{% if terms.slug == 'neuron' %}{{terms.para_one}}{% endif %}{% endfor %}">Toggle popover</a> There is a lot more code in the block. Now, for obvious reasons I do not want to keep repeating such large chunks of code. I am a fan of the DRY approach. However, I can't figure out how to render this same piece of code repeatedly. The only thing that would change is the word = "neuron" in there. I thought of using template tags, but that didn't work. I tried saving the code as a separate file, and inherit it within my template, but then I can't change the keyword ('neuron'). I also tried creating a separate dynamic page, and include that in my Django template, but looks like the include tag only works for templates, and not for dynamic pages. Can anyone help, please? Thank you, in advance. -
Django many to many queryset trouble
I have 2 models class Service(models.Model): name = models.CharField(max_length=100) class ServiceType(models.Model): name = models.CharField(max_length=100) services = models.ManyToManyField(Service, related_name='service_types') Now i have a list of services and want to get ServiceType with only this services. If not exists, create it. I don't understand how to build this queryset threw Django ORM..... queryset like ServiceType.objects.filter(services__id__in=services.values_list('id', flat=True)).annotate(count=Count('services')).filter(count=services.count()) returns all ServiceTypes with needed services and not needed services... -
Adding database to Mezzanine project produces "sqlite3.OperationalError: no such table: django_site"
I'm trying to add a third-party database to a Mezzanine 4.2.3 project (it uses Django 1.10.8 according to requirements.txt). It's to be used by an app called food_crud. However, it produces this error: sqlite3.OperationalError: no such table: django_site. Most solutions I've read say to makemigrations and migrate. A few say to add django.contrib.sites to INSTALLED_APPS. I've tried both. Project directory layout: 180214 food - env_food - food __init__.py settings.py router.py urls.py views.py wsgi.py - food_crud - migrations __init__.py admin.py models.py tests.py views.py - static - theme __init__.py manage.py movie_data.sql The food_crud app is in INSTALLED_APPS. settings.py also contains the database details: DATABASES = { "default": { "ENGINE": "django.db.backends.postgresql_psycopg2", "NAME": "db_nate", "USER": "alex", "PASSWORD": "oh no you did not use password did you", "HOST": "localhost", "PORT": "", }, "movies": { "ENGINE": "django.db.backends.sqlite3", "NAME": "movie_data.sql", } } DATABASE_ROUTERS = ['food.router.FoodRouter'] Here's router.py, in the same folder as settings.py: from food_crud import models class FoodRouter(object): def db_for_read(self, model, **hints): model = models.Movies if model._meta.app_label == 'food_crud': return 'movies' return None models.py: from django.db import models class Movies(models.Model): id = models.AutoField(primary_key=True) adult = models.TextField() original_language = models.TextField() original_title = models.TextField() title = models.TextField() overview = models.TextField() release_date = models.DateField() genres = models.TextField() production_countries = … -
Connecting angular-firmly to Django
I am trying to create a web application using Angular-formly on the front end and a Django framework on the back end. Have a couple of questions regarding this: How do I send data from angular-firmly form to Django and there on to mysql database and vice versa? How do I create a file upload button using angular formly. Thank you -
Django Authentication and ReactJS Templates
I have an existing login template served by django templates and it has no react components at all. I have recently integrated ReactJS and have created some routes and components and pages that are completely react. Now I am wondering how to get a user to login through the django template and then be redirected to the ReactJS page afterwards and pass on all the authentication/user information to ReactJS as well. In Django, I am using the session authentication middleware. -
Creating Django project on server with nginx
We have a dev server with the internal hostname dev1.internal.blah.com running nginx. I'm trying to create a test Django project testproject from the Django tutorial on this server. I access this server by ssh-ing into it. So on this server I installed Django, created a new directory, issued django-admin startproject mysite within it, then issued python manage.py runserver 8765 and got the success message Starting development server at http://127.0.0.1:8765/ Now how would I access the http://127.0.0.1:8765 site from a browser? I tried using http://dev1.internal.blah.com:8765 but got a This site can't be reached error message. If I try curl http://127.0.0.1:8765 from the terminal, I see the correct html being rendered. The nginx www directory is located at /usr/share/nginx/html if it helps. -
Django Grappelli usergroup conditional dashboard
Working with Grappelli(2.11.1) in Django(1.11.10). I crafted small custom dashboard and look now for some method to variate appearance of elements. In particular I need to show some url-element self.children.append(modules.LinkList( _('e-mail'), column=2, css_class=('grp-collapse grp-closed'), children=[ { 'title': _('gmail'), 'url': 'gmail.com', 'external': True, }, ] )) only to users of specified group and to hide it to others. In regular way I would try to use auth.get_user(), but this depends on 'request'. Which is not available, or at least visible, for me. Any way to make this feature? Thanks anyway. -
Django: permissions on object level - django rules or guardian?
I am currently working on my first bigger project since the official tutorial. I want to set up a correct implementation of user permissions on the object level. While searching on the web how to implement such, I noticed that there are many ways with different advantages and disadvantages for different purposes. Now, I struggle which solution I should use: django Guardian or django rules? Both assign the problem of the permissions on object level and look well maintained. Please take a look at my case: A user can be part of one or many teams and a team contains one or more users(n:m). Furthermore, one or more users can be the team lead of one or more teams(n:m). You see, I need the permissions on the object level and a kind of a role for the team lead or team member. Or am I wrong? What do you think about the case and the suggested solutions(django guardian or django rules)? A few more information regarding my setup. I am using Django 1.11 with a custom user model extended with the well known profile pattern. I have planned to upgrade Django to version 2.0 shortly. Thanks in advance and kind … -
Extend Grappelli Templates in Django 1.11
I'm upgrading a Django project from 1.8 to 1.11. The app uses grappelli and grappelli dashboard, which I'm currently upgrading from 2.7.3 to 2.11.1. Previously, several of our templates extended grappelli templates with the following (for example): {% extends "grappelli:admin/object_history.html" %} Upgrading to 1.11, this returns a TemplateDoesNotExist for grappelli:admin/app_index.html For reference, the templates load fine when I reference extends "admin/object_history.html" instead. What's the proper namespace/template format for extending grappelli template like the above? Thank you! -
Add to Apache Path
I'm running apache, mod_wsgi, django, and mssql. I have the following line in my .bashrc: export PATH="$PATH:/opt/mssql-tools/bin" I had Django print the current value of os.environ['PATH'] to a template and it returned /usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin How do I add to whatever path Apache is using? I've already tried sys.path.append('/opt/mssql-tools/bin') in my wsgi.py file Thank you!