Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
ImportError: No module named 'auth'
In the the urls.py I have from django.contrib import auth urlpatterns = [ path('accounts/',include('auth.urls')), ] ImportError: No module named 'auth' But the following works urlpatterns = [ path('accounts/',include('django.contrib.auth.urls')), ] Why am I not able to former method? -
Is it possible to use Redis Cloud in Django Channel
Currently I am trying to create DRF (Django REST Framework) project and deploying it on Heroku. Now recently I thought of adding Django channel and see how well it works so for that I did all the local configuration but at the same time I am planning to deploy it on Heroku. My DRF project is already deployed but for Django Channel I need to add 1 configuration which is Redis but now Heroku is asking for Credit Card info to add it. I know it's not a big of a deal but for me as a student I can't afford that right now. So my question is that, is it possible to have different Redis service hosted at different place and then I can provide the URL in my settings.py as: CHANNEL_LAYERS = { 'default': { 'BACKEND': 'channels_redis.core.RedisChannelLayer', 'CONFIG': { "hosts": [('redis://:' + config('REDIS_PASSWORD') + '@<redis-url>', 17566)], }, }, } I thought I can do something from here by using Redis Cloud Host feature. I am not well knowledgeable on how these technology works that's why I am trying my best to understand it. Sorry if it sounds stupid -
how to integrate django app model with variables in other python file?
I am new in making RESTful API, the goal is to make a RESTful API using django that can be access with flutter, the information that will be converted into JSON format by serializer.py is from variables that are processed in other script in python. how to add the variable into the API? is it added in model.py? or maybe using POST method? I don't have any clue, because I just found the tutorial about GET method -
Volume to share files from docker container to host in elastic beanstalk single container
I'm trying to share the static files from my container to the host so that nginx can serve them. This is on AWS elastic beanstalk using the Docker single container platform. I have verified that the static files have been generated in the container, however the files are not found in the host directory. The project is otherwise working fine, deployed with eb deploy. Can someone tell me where did I go wrong? Thanks! Dockerrun.aws.json: { "AWSEBDockerrunVersion": "1", "Volumes": [ { "HostDirectory": "/var/www/static", "ContainerDirectory": "/code/my_app/static" } ] } Dockerfile: FROM python:3.6 ENV PYTHONUNBUFFERED 1 ARG requirements=requirements/production.txt ENV DJANGO_SETTINGS_MODULE=my_app.settings.production RUN mkdir /code WORKDIR /code COPY requirements/ /code/requirements/ RUN pip install --upgrade pip RUN pip install -r $requirements STOPSIGNAL SIGINT ADD . /code/ EXPOSE 8000 COPY ./entrypoint_prod.sh / ENTRYPOINT ["/entrypoint_prod.sh"] entrypoint_prod.sh python manage.py collectstatic --no-input gunicorn my_app.wsgi:application --bind 0.0.0.0:8000 python manage.py process_tasks -
How to use database2 when database1 is locked in django?
I am using sqlite3 databases(Multiple Databases)in Django2. When database1 is locked is there any way to use database2? Hee is my database settings DATABASES = { 'default': { 'NAME': 'customers_data', 'ENGINE': 'django.db.backends.mysql', 'USER': '', 'PASSWORD': '' }, 'users': { 'NAME': 'user_data', 'ENGINE': 'django.db.backends.mysql', 'USER': '', 'PASSWORD': '' } } Thanks in advance for your answers. -
IntegrityError at /new_topic/ NOT NULL constraint failed: learning_logs_topic.owner_id
I am setting topics to have its user owner. But I wonder can I add a new_topic that does not have an owner by setting Null=True to some field? class Topic(models.Model): text = models.CharField(max_length=200) date_added = models.DateTimeField(auto_now_add=True) owner = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.text @login_required def new_topic(request): if request.method != 'POST': form = TopicForm() else: form = TopicForm(request.POST) if form.is_valid(): form.save() The error said: Not NULL constraint failed. I know the solution as I changed form.save() to the following by set the new_topic with an owner: new_topic = form.save(commit=False) new_topic.owner = request.user new_topic.save() I cleaned all codes snippets having .owner suffix. I was guessing the problem is because as I Forignkey topic owner with User class, the User class now has a topic attribute(field) that sets Null = False by default So any new_topic should have a user as its owner. Here's what I did: class Topic(models.Model): text = models.CharField(max_length=200) date_added = models.DateTimeField(auto_now_add=True) owner = models.ForeignKey(User, on_delete=models.CASCADE, null=True) def __str__(self): return self.text However, I still get the same error.. I guess that because ForeignKey field dose not support Null = True? or I wonder should I change User's topic field rather than Topic's owner field? if so How should … -
Django 2.1.5 on Windows. After runserver: System check identified no issues (0 silenced)
This message showed after I executed runserver command: System check identified no issues (0 silenced) I have referenced this solution, but it didn't work for me(I start my mysql server by the command "C:\Program Files\MySQL\MySQL Server 8.0\bin\mysqld" ). Here is the background information(the "pip list" command): (DjangoEnv) D:\pythonproject\DjangoEnv\loginoutonly>pip list Package Version Django 2.1.5 mysqlclient 1.3.13 pip 18.1 PyMySQL 0.9.3 pytz 2018.9 setuptools 40.6.3 wheel 0.32.3 -
SyntaxError: invalid syntax for COLLECTSTATIC (PYTHON)
I am following a tutorial on youtube for deploying a django app on DigitalOcean. I type in: python3 manage.py collectstatic This is the error message I get: Traceback (most recent call last): File "manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "/home/mochimoko/django_project/venv/lib/python3.5/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/home/mochimoko/django_project/venv/lib/python3.5/site-packages/django/core/management/__init__.py", line 357, in execute django.setup() File "/home/mochimoko/django_project/venv/lib/python3.5/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/home/mochimoko/django_project/venv/lib/python3.5/site-packages/django/apps/registry.py", line 112, in populate app_config.import_models() File "/home/mochimoko/django_project/venv/lib/python3.5/site-packages/django/apps/config.py", line 198, in import_models self.models_module = import_module(models_module_name) File "/usr/lib/python3.5/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 986, in _gcd_import File "<frozen importlib._bootstrap>", line 969, in _find_and_load File "<frozen importlib._bootstrap>", line 958, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 673, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 661, in exec_module File "<frozen importlib._bootstrap_external>", line 767, in get_code File "<frozen importlib._bootstrap_external>", line 727, in source_to_code File "<frozen importlib._bootstrap>", line 222, in _call_with_frames_removed File "/home/mochimoko/django_project/users/models.py", line 11 return f'{self.user.username} Profile' I know the code is right cause I got in straight from GitHub. I am a complete beginner at this. I know that indentation could be the issue here but everything looks fine to me. Here is the code for the manage.py file: from django.db import models from django.contrib.auth.models import User … -
ansible.cfg file hijack my django project log file output path
I have a strange django log file output problem, I use the ansible 2.5.0 module in my django 1.11.11 project like this from ansible.plugins.callback import CallbackBase, and the log_path setting in the /etc/ansible/ansible.cfg file actually takes effect for my django project log file output, like a hijack. # logging is off by default unless this path is defined # if so defined, consider logrotate log_path = /var/log/ansible.log All my django log output to the /var/log/ansible.log which is quite odd. 2019-01-07 17:49:22,271 django.server "GET /docs/ HTTP/1.1" 200 1391207 2019-01-07 17:49:23,262 django.server "GET /docs/schema.js HTTP/1.1" 200 111440 I did set up the LOGGING in my django settings, the django setting takes effect too, and the output is like this: "GET /docs/ HTTP/1.1" 200 1391207 "GET /docs/schema.js HTTP/1.1" 200 111440 It will be two log files for the same django project in same log level I defined in the django settings: LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'handlers': { 'file': { 'level': 'INFO', 'class': 'logging.FileHandler', 'filename': '/var/log/django_debug.log', }, }, 'loggers': { 'django': { 'handlers': ['file'], 'level': 'INFO', 'propagate': True, }, }, } -
How comment_set.all is used to get data from model where it doen't exist?
In the HTML comment_set.all is used to get data from model where it doesn't exist. What is the concept behind this. post_detail.html {% extends "base.html" %} ... <div> {{ instance.comment_set.all }} </div> ... OUTPUT [<Comment: User_Name >] Codes that supporting this Comments app model is given below comments/models.py from django.conf import settings from django.db import models # Create your models here. from posts.models import Post class Comment(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, default=1) post = models.ForeignKey(Post) content = models.TextField() timestamp = models.DateTimeField(auto_now_add=True) def __str__(self): return str(self.user.username) posts/models.py ... class Post(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, default=1) title = models.CharField(max_length=120) slug = models.SlugField(unique=True) image = models.ImageField(upload_to=upload_location, null=True, blank=True, width_field="width_field", height_field="height_field") height_field = models.IntegerField(default=0) width_field = models.IntegerField(default=0) content = models.TextField() draft = models.BooleanField(default=False) publish = models.DateField(auto_now=False, auto_now_add=False) updated = models.DateTimeField(auto_now=True, auto_now_add=False) timestamp = models.DateTimeField(auto_now=False, auto_now_add=True) objects = PostManager() def __str__(self): return self.title def get_absolute_url(self): return reverse("posts:detail", kwargs={"slug": self.slug}) class Meta: ordering = ["-timestamp", "-updated"] def get_markdown(self): content = self.content markdown_text = markdown(content) return mark_safe(markdown_text) ... posts/views.py ... def post_detail(request, slug=None): instance = get_object_or_404(Post, slug=slug) if instance.publish > timezone.now().date() or instance.draft: if not request.user.is_staff or not request.user.is_superuser: raise Http404 share_string = quote_plus(instance.content) context = { "title": instance.title, "instance": instance, "share_string": share_string, } return render(request, "post_detail.html", context) ... … -
Uploading multiple files using Dropzone.js and Django, file uploading not working
Uploading a single file is working with Dropzone.js and Django but when I set uploadMultiple to true, it even cannot upload files. How can I handle this? In models, file = models.FileField(upload_to='upload/'); In forms, file = forms.FileField(widget=forms.ClearableFileInput(attrs={'multiple': True})) The errors are arising.. if request.method == 'POST': files = request.FILES.getlist('file') print(files) <-- prints [] ,not any files form = PostForm(request.POST, request.FILES) if form.is_valid(): <-- not valid It worked with the single upload case, even it looked like sending multiple files but it processed each file one by one. With the uploadMultiple set, not working. Any sugestions? -
How to return JSON response in Django's HttpResponseServerError?
I am writing a python Django application where I am returning error HttpResponseServerError. I also need to return some json data that i can get a message from and show to the user in my front end. So I am doing like this: from django.http import HttpResponseServerError def my_test_500_view(request): return HttpResponseServerError(json.dumps({'error': 'An error occured'}, content_type="application/json") But in my front end, I can seem to get the value for 'error. In my front end Ajax, I am doing like this: $("#input_submit").click(function () { var input = $("#input").val(); $.ajax({ url: 'my_url', data: { 'input': input, }, dataType: 'json', success: function (data) { console.log(data); }, error: function (data) { console.log(data.error); } }); }); Where console.log(data.error); returns undefined. Any idea what am I doing wrong here? -
Is there a way to convert strings containing numbers to integers in Python? [duplicate]
This question already has an answer here: Python: Extract numbers from a string 13 answers I have a Postgres 10 database with a column I need to execute queries against in Django. This column age_data, is of the charField type and the raw data is either an empty string i.e. '' or in the pattern 'XX Years'. Ultimately I'd like to return records based on conditions where a user's age is greater/less than the values in column age_data but I can't compare them numerically because age_data is formatted as a string data type. Basically I need the first two digits isolated, any ideas for this? Thanks for any help! I've tried converting the first two digits of age_data to a substring then an integer like below but received the error: "int() argument must be a string, a bytes-like object or a number, not 'Substr'" I've tried casting age_data as an integer with no avail either. Sample code of the method I was testing. Test = Substr('65 Years', 1, 2) print int(Test) I expected the output of the above to be 65 so I could use numerical conditional statements afterwards. -
Is there any technology similar to wordpress sensei for django?
I want to create a video tutoring platform and and I found sensei for wordpress but did not find anything for django. Exist any alternative to django? -
Dropzone.js and Django file uploading - form.save works but no files showing
I am using Dropzone.js to upload files and process them in Django. The files are showing in views.py but not being saved to the media root. def post(request): if request.method == 'POST': form = PostForm(request.POST, request.FILES) if form.is_valid(): print(request.FILES.getlist('file')) form.save() In models.py, def upload_directory(instance, filename): print(filename) return 'uploads/{0}'.format(filename) file = models.FileField(upload_to=upload_directory); In the forms, a FileField is set as below, file = forms.FileField(widget=forms.ClearableFileInput(attrs={'multiple': True})) So, it displays the files from the request, but it is not saved to the directory and it seems the upload_directory is not being called as it doesn't display any filename in print(filename). What is happening here? -
Django: How do I pass in a context of a model nested within another via a ForeignKey?
I have the following models: class Crisis(models.Model): general = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) name = models.CharField(max_length=30) class Plan(models.Model): description = models.CharField(max_length=30) engage = models.BooleanField(default=True) crisis = models.ForeignKey(Crisis, on_delete=models.CASCADE) What I would like to do is display all the Crisis, filtering by some query, and all the Plan with the same Crisis underneath. So somehow to pass in a CrisisList context such that I could do as follows (please excuse the pseudo-Django): {% if CrisisList %} {% for crisis in CrisisList %} {{ crisis.name }} {% for plan in CrisisList.PlanList %} {{ plan.description }} {{ plan.engage }} {% endfor %} {% endfor %} {% endif %} What might work in another setting is create a QuerySet from Plans (or maybe in this one?), but for UI reasons I want all the Plans with the same Crisis ForeignKey to be displayed together (say under a <div class="container">). Cheers -
Contenttype Django + Angular 4
I use Django Framework + Django REST Framework + Angular 4. I have polymorphic links that are implemented through the contenttype. API comes the following data: /api/v1/products/ { "id": 3, "treaty_number": "asda", "days_left": null, "days_left_before_the_next_payment": null, "contact": "", "additional_information": "", "no_prolongation": false, "improving_conditions": "", "redundancy": null, "is_general": false, "insurant": { "id": 1, "object_id": 1, "content_type": 35 <--- HERE MODEL ID (artifical_persons) }, "insurer": null, "executor": null, "status": null, "dates": null, "subagent": null, "broker": null }, I need to determine the corresponding entry by content_type_id and object_id and output its name in mat-select: <mat-form-field> <mat-select placeholder="Insurants"> <mat-option *ngFor="let insurant of insurants [value]="insurant.value"> {{insurant.name}} </mat-option> </mat-select> </mat-form-field> /api/v1/artifical_persons/ [ { "id": 1, <--- HERE OBJECT_ID "name": "Test", "id_holdings": null } ] I would be grateful for any help. My thoughts are that I need to write a function that will accept two arguments (content_type_id, object_id) over HTTP and return the insurant name. model.py class Insurants(models.Model): id = models.AutoField(primary_key=True) # insurant_id = models.CharField(max_length=512) content_type = models.ForeignKey(ContentType) object_id = models.PositiveIntegerField() content_object = GenericForeignKey('content_type', 'object_id') class Products(models.Model): id = models.AutoField(primary_key=True) treaty_number = models.CharField(max_length=512) .... insurant = models.ForeignKey(Insurants, null=True, blank=True) .... class Meta: db_table = 'products' def __str__(self): return '{} '.format(self.treaty_number) serializers.py class InsurantsSerializer(serializers.ModelSerializer): class Meta: … -
My Django Site is not loading in Elasticbeanstalk due to settings.py not being found.
I can't get my Django website to load. These are my error messages from the logs: get_wsgi_application [Mon Jan 07 23:38:51.699497 2019] [:error] [pid 6456] [remote 74.71.99.135:244] django.setup(set_prefix=False) [Mon Jan 07 23:38:51.699503 2019] [:error] [pid 6456] [remote 74.71.99.135:244] File "/opt/python/run/venv/local/lib/python3.6/site-packages/django/__init__.py", line 22, in setup [Mon Jan 07 23:38:51.699507 2019] [:error] [pid 6456] [remote 74.71.99.135:244] configure_logging(settings.LOGGING_CONFIG, settings.LOGGING) [Mon Jan 07 23:38:51.699512 2019] [:error] [pid 6456] [remote 74.71.99.135:244] File "/opt/python/run/venv/local/lib/python3.6/site-packages/django/conf/__init__.py", line 56, in __getattr__ [Mon Jan 07 23:38:51.699515 2019] [:error] [pid 6456] [remote 74.71.99.135:244] self._setup(name) [Mon Jan 07 23:38:51.699520 2019] [:error] [pid 6456] [remote 74.71.99.135:244] File "/opt/python/run/venv/local/lib/python3.6/site-packages/django/conf/__init__.py", line 41, in _setup [Mon Jan 07 23:38:51.699523 2019] [:error] [pid 6456] [remote 74.71.99.135:244] self._wrapped = Settings(settings_module) [Mon Jan 07 23:38:51.699528 2019] [:error] [pid 6456] [remote 74.71.99.135:244] File "/opt/python/run/venv/local/lib/python3.6/site-packages/django/conf/__init__.py", line 110, in __init__ [Mon Jan 07 23:38:51.699530 2019] [:error] [pid 6456] [remote 74.71.99.135:244] mod = importlib.import_module(self.SETTINGS_MODULE) [Mon Jan 07 23:38:51.699535 2019] [:error] [pid 6456] [remote 74.71.99.135:244] File "/opt/python/run/venv/lib64/python3.6/importlib/__init__.py", line 126, in import_module [Mon Jan 07 23:38:51.699538 2019] [:error] [pid 6456] [remote 74.71.99.135:244] return _bootstrap._gcd_import(name[level:], package, level) [Mon Jan 07 23:38:51.699543 2019] [:error] [pid 6456] [remote 74.71.99.135:244] File "<frozen importlib._bootstrap>", line 994, in _gcd_import [Mon Jan 07 23:38:51.699548 2019] [:error] [pid 6456] [remote 74.71.99.135:244] File "<frozen … -
Reverse for 'account_inactive' not found. 'account_inactive' is not a valid view function or pattern name
I try user rest-auth after adding new user i tru change is_active status to False by signals class MyRegisterSerializer(serializers.Serializer): email = serializers.EmailField(required=settings.EMAIL_REQUIRED) contract = serializers.CharField(required=False, write_only=False) tole = serializers.CharField(required=False, write_only=False) # is_active= serializers.CharField(required=True, write_only=True) password1 = serializers.CharField(required=True, write_only=True) password2 = serializers.CharField(required=True, write_only=True) def validate_email(self, email): email = get_adapter().clean_email(email) if settings.UNIQUE_EMAIL: if email and email_address_exists(email): raise serializers.ValidationError( _("Этот email уже занят")) return email def validate_password1(self, password): return get_adapter().clean_password(password) def validate(self, data): if data['contract']: try: ContractModel.objects.get(number=data['contract']) except ContractModel.DoesNotExist: raise serializers.ValidationError( _("Договора '" + data['contract'] + "' не существует.")) # if data['role']: # try: # ContractModel.objects.get(number=data['contract']) # except ContractModel.DoesNotExist: # raise serializers.ValidationError( # _("Договора '" + data['contract'] + "' не существует.")) if data['password1'] != data['password2']: raise serializers.ValidationError( _("Пароли не совпадают.")) return data def get_cleaned_data(self): return { 'is_active': False, # 'email': self.validated_data.get('email', ''), 'contract': self.validated_data.get('contract', ''), 'password1': self.validated_data.get('password1', ''), 'email': self.validated_data.get('email', ''), } def save(self, request): adapter = get_adapter() user = adapter.new_user(request) self.cleaned_data = self.get_cleaned_data() adapter.save_user(request, user, self) setup_user_email(request, user, []) user.profile.save() return user @receiver(pre_save, sender=User) def set_new_user_inactive(sender, instance, **kwargs): if instance._state.adding is True: instance.is_active = False -
are PermissionsMixin and PermissionRequiredMixin the same thing in Django 2.0?
I want to know if PermissionsMixin has the same function as PermissionRequiredMixin. from django.contrib.auth.models import PermissionMixin from django.contrib.auth.mixins import PermissionRequiredMixin -
Best approach for django-celery-twisted powered GPS tracking system
I'm currently working on developing a GPS tracking system and my configuration is the following: React for the web display. Django with django-rest-framework for the api to query the database. Twisted to listen to TCP port and receive GPS data. Celery to save the data from twisted to DB asynchronously. Redis to transfer data from Twisted to Celery. I have always work with python so, as you can see, that is my primary choise. This approach is kinda working but I'm affraid that maybe it will not going to be scalable. Already got 5 GPS but only one is reporting, I'm trying to find out the reason, but that not the question. Does somebody know a better approach using python? It's this a common pattern? I'm worried about the "Twisted - Redis - Celery" part. -
Count(Jsonb(expression) in Django error TypeError: unhashable type: 'list'
Let's go to the error, I mounted my query in postgresql and it works normally, but when I pass to the Django ORM query, the code returns me that error bellow. I noticed that this only occurs when I try to use Count and that ORM always tries to group_by all fields in my table, but if it does the query with all fields, this will not work, i just need the group_by with this 2 fields, does anyone know how to solve it? error: Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x000001D6FE3BB2F0> Traceback (most recent call last): File "C:\Python35\lib\site-packages\django\utils\autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "C:\Python35\lib\site-packages\django\core\management\commands\runserver.py", line 117, in inner_run self.check(display_num_errors=True) File "C:\Python35\lib\site-packages\django\core\management\base.py", line 379, in check include_deployment_checks=include_deployment_checks, File "C:\Python35\lib\site-packages\django\core\management\base.py", line 366, in _run_checks return checks.run_checks(**kwargs) File "C:\Python35\lib\site-packages\django\core\checks\registry.py", line 71, in run_checks new_errors = check(app_configs=app_configs) File "C:\Python35\lib\site-packages\django\core\checks\urls.py", line 40, in check_url_namespaces_unique all_namespaces = _load_all_namespaces(resolver) File "C:\Python35\lib\site-packages\django\core\checks\urls.py", line 57, in _load_all_namespaces url_patterns = getattr(resolver, 'url_patterns', []) File "C:\Python35\lib\site-packages\django\utils\functional.py", line 37, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\Python35\lib\site-packages\django\urls\resolvers.py", line 533, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "C:\Python35\lib\site-packages\django\utils\functional.py", line 37, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\Python35\lib\site-packages\django\urls\resolvers.py", line 526, in urlconf_module return import_module(self.urlconf_name) … -
Display side-by-side fields in django form
I'm working on a djano application and I want to display some fields in my form side-by-side. The following template code is : <div class="panel-body"> <form method="POST" enctype="multipart/form-data"> {% csrf_token %} {% bootstrap_form extraform %} <button type="submit" name ="a_button" class="btn btn-pink">add</button> </form> </div> What I want is : displaying two input fields that I have in extraform and the button side by side. -
What is a good DRF Serializer design for flexibility
I've read a lot of similar topics and I know there are a number of ways that would accomplish the goal, but I'm wondering if anybody has an opinion on this one. Problem Statement My application has two primarily types of users. Customers and Staff members. When retrieving data from an endpoint, it is not uncommon for customers to see viewer fields than staff. In addition, data from a list view generally has fewer fields than that of a retrieve. Solution? Create a serializer for each method, as well for each user type. For example, in an /orders endpoint I may have up to 8 different serializers OrdersListStaffSerializer OrdersListCustSerializer OrdersRetrieveStaffSerializer.... etc Then I can simply choose the proper serializer for the condition. PROS Seems like good flexibility in being able to control exactly who can see what, and also what data they are allowed to write. CONS Feels like there could be a lot of duplication of effort. Lacks the ability to have a finer grain control of data based on permissions. Wondering if anybody has had any experience following this type of design and if it has worked well or become too cumbersome to maintain. Thanks! -
Passing model data to urlpatterns in Django's urls.py
I am trying to write a generic urlpatterns entry in urls.py that would replace hardcoded entries, as below: path('apple/', RedirectView.as_view(url='/apple/abc/'), name='apple_redirect'), path('orange/', RedirectView.as_view(url='/orange/def/'), name='orange_redirect'), path('banana/', RedirectView.as_view(url='/banana/ghi/'), name='banana_redirect'), The model called fruits holds the following data: name = 'apple' url = 'apple/abc/' name = 'orange' url = '/orange/def/' name = 'banana' url = '/banana/ghi/' I would like to avoid the need for manual addition of another path in case new entry in fruits model is added.