Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Get maximum value of a field in django
I have a model Foo in my models.py like this: class Foo(models.Model): transaction_no = models.IntegerField(default=0, blank=True, null=True) transaction_date = models.DateField(default=datetime.now) quantity = models.IntegerField(default=0, blank=True, null=True) I want to get the max quantity from the table. How can I get that? -
Python or django product management framework
I need product management system for django or python. For example Facebook have html pages for adding new products with graphAPI; Example html for facebook products <!DOCTYPE html><html> <head prefix= "og: http://ogp.me/ns# fb: http://ogp.me/ns/fb# product: http://ogp.me/ns/product#"> <meta property="og:type" content="og:product" /> <meta property="og:title" content="Friend Smash Coin" /> <meta property="og:image" content="http://www.friendsmash.com/images/coin_600.png" /> <meta property="og:description" content="Friend Smash Coins to purchase upgrades and items!" /> <meta property="og:url" content="http://www.friendsmash.com/og/coins.html" /> <meta property="product:plural_title" content="Friend Smash Coins" /> <meta property="product:price:amount" content="0.30"/> <meta property="product:price:currency" content="USD"/> <meta property="product:price:amount" content="0.20"/> <meta property="product:price:currency" content="GBP"/> </head> </html> I need to manage three store, "Facebook Store", "Google Play Store", "Apple Store products with my django application, So searched github etc. For any open-source project for managing that store products. I couldnt find it. -
UnicodeDecodeError python django framework
im a bit new with python and django framework. I already setup the project in my virtual env. It was working fine before i update my windows 10. as of now, i'm running into an error related to the this UnidecodeError In my virtual environment, i have already install these libraries. python 3.8.1 (32-bit) - installed locally. asgiref==3.2.3 certifi==2019.11.28 cffi==1.14.0 chardet==3.0.4 cryptography==2.8 Django==3.0.3 django-appconf==1.0.3 django-crispy-forms==1.8.1 django-cryptography==1.0 django-mssql-backend==2.7.0 idna==2.8 pycparser==2.19 -pyodbc==4.0.28 pytz==2019.3 requests==2.22.0 six==1.14.0 sqlparse==0.3.0 urllib3==1.25.8 django-adminlte3==0.1.2 The error started when i updated windows. Any idea how to solve this? Things that i've tried update using 64-bit python version update my system locale -
How to use FilerImageField in html template?
I want to know how to use FilerImageField in html tag. i tried <image src={{ instance.team_background_image_1.file.url }}> it display full image. but i want to use FilerImageField in many resolutions such as 300x300, 250x300 -
Render template by django templatetags
This is my .html file {% for date in field %} <div class="col-md-6"> <span class="input-group date datetimepicker" data-min-view="2" data-date-format="yyyy/mm/dd"> <span class="input-group-append"> <button class="btn btn-secondary"><i class="icon-th mdi mdi-calendar"></i></button> </span> {{ date }} </span> </div> {% endfor %} and print(field) is <input type="text" name="date_after" class="form-control" id="id_date_0" /> <input type="text" name="date_before" class="form-control" id="id_date_1" /> show in the template like https://imgur.com/1GQuCgj Can I render this two input tags separately? hope someone can help this, thx! -
Saving Nested Django Serializer
I have 3 models. Question, Choice, and Cover. Question can have many choices and each choice can have only 1 cover. I implemented the Question and Choice as serializers and it worked successfully, now i'm trying to add on the Cover. Here's what I have: class CreateQuestionSerializer(serializers.ModelSerializer): choice_set = ChoiceSerializer(many=True) class Meta: model = Question fields = ('user', 'status', 'choice_set') def create(self, validated_data): choices_validated_data = validated_data.pop('choice_set') question = Question.objects.create(**validated_data) choices_serializer = self.fields['choice_set'] for choice in choices_validated_data: choice['question'] = question choices_serializer.create(choices_validated_data) return question class ChoiceSerializer(serializers.ModelSerializer): choice_cover = ChoiceCoverSerializer(many=False) class Meta: model = Choice fields = ('choice', 'choice_cover') class ChoiceCoverSerializer(serializers.ModelSerializer): class Meta: model = ChoiceCover fields = ('cover',) When I try to save data like so: { "user": 179, "question": "Who will win the election?", "choice_set": [ { "choice": "Lorem", "choice_cover": "C4FF33" }, { "choice": "Ipsum", "choice_cover": "FF5733" } ] } I get the following error: { "choice_set": [ { "choice_cover": { "non_field_errors": [ "Invalid data. Expected a dictionary, but got str." ] } }, { "choice_cover": { "non_field_errors": [ "Invalid data. Expected a dictionary, but got str." ] } } ] } How can I fix this? -
Override Bootstrap Admin templates in Django
I'm using the Bootstrap admin library in order to use Bootstrap templates in admin. Now I want to override the Bootstrap admin templates. I followed the instructions given in their documentation: https://github.com/douglasmiranda/django-admin-bootstrap#branding---overriding-logo But it's not working. Here is my templates variable: TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'vspmschool/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', ], }, }, ] -
Django RF - How to insert into pivot table using name instead of id without querying the id?
For example I have the ff: models: class Store(models.Model): name = models.CharField(max_length = 20) class Product(models.Model): name = models.CharField(max_length = 20) class StoreProducts(models.Model): store = models.ForeignKey(Store) product = models.ForeignKey(Product) qty = models.IntegerField() serializer: class StoreProductsSerializer(serializers.ModelSerializer): class Meta: model = StoreProducts fields = ('store', 'product', 'qty') And defined values: Store (id, name): 1, store_1 2, store_2 Product (id, name): 1, product_1 2, product_2 Now in the views, I want to add into the StoreProducts from post request without querying the ids of Store and Product like this: data = { 'store': 'store_1', 'product': 'product_1', 'qty': 1 } serializer = RobotSerializer(data=data) if serializer.is_valid(): serializer.save() Is this possible and how? Thanks -
How to use Django url template tag with variable as url path
I encountered a No Reverse Match Error in trying to render a template. Can you explain what this No Reverse Match Error mean for easier understanding and how to solve the error? from django.contrib.sites.models import Site from django.contrib.gis.db import models from django.utils.crypto import get_random_string from django.contrib.gis.geos import GEOSGeometry,Point from django.contrib.auth.models import AbstractUser from django.shortcuts import render # Create your models here. class User(AbstractUser): pass geos_pnt=Point(4314498.56, 1003834.600,srid=3857) #pnt=GEOSGeometry('POINT(4314498.56, 1003834.600)').wkt class Apartment(models.Model): SUBCITY_CHOICES = ( ('ADK', 'Addis Ketema'), ('AKLTY', 'Akaki-Kality'), ('ARD', 'Arada'), ('BL', 'Bole'), ('GL', 'Gulele'), ('KLF', 'Kolfe-Keranio'), ('LDTA', 'Ledeta'), ('NFS', 'Nefas Silk'), ('YK', 'Yeka')) apt_id = models.CharField(str(SUBCITY_CHOICES)+"-"+get_random_string(length=4), max_length=8,primary_key=True) location = models.PointField(default=geos_pnt,extent=(4282586.10,996190.90,4346411.02,1011478.31), blank=True, null=True, srid=3857, help_text="Point(longitude latitude)") no_bedrooms= models.IntegerField(null=True) apt_area = models.IntegerField(default=0, null=True) apt_cost = models.IntegerField(default=0, null=True) apt_subcity = models.CharField(default='Nefas Silk',max_length=100, choices=SUBCITY_CHOICES,null=True) register_date = models.DateTimeField('Register Date',auto_now_add=True,null=True) slug = models.SlugField(unique=True) objects = models.Manager() sites =models.ManyToManyField(Site) #change points from apt_rent_db to kml def pointkml(self): points = Apartment.objects.kml() return render("placemarks.kml", {'places': points}) def get_absolute_url(self): return reverse('apartment_create', kwargs={'pk': self.pk, 'apt_id': self.apt_id.pk}) def save(self, *args, **kwargs): #self.Latitude = self..y #self.Longitude = self.location.x self.slug = slugify(self.apt_id) super(Apartment, self).save(*args, **kwargs) class Meta: # order of drop-down list items verbose_name = ("Apartment") verbose_name_plural = ("Apartments") ordering = ('apt_cost',) app_label = 'rent_app' def __unicode__(self): return self.apt_id the html: <html> <head> {% … -
How to solve ImproperlyConfigured error during setting AUTH_USER_MODEL
My app directory is something like this users(app name) |__models |__users.py and my users.py has the model User like this:- class User(BaseModel): first_name = models.CharField(max_length=30, null=False, blank=False) last_name = models.CharField(max_length=30, null=False, blank=False) email_id = models.EmailField(null=False, blank=False, unique=True) username = models.CharField(max_length=20, null=False, blank=False, unique=True) password = models.CharField(max_length=20, null=False, blank=False) class Meta: app_label = 'users' I am trying to set AUTH_USER_MODEL in my settigns.py as AUTH_USER_MODEL = 'users.User' But I am getting this error "django.core.exceptions.ImproperlyConfigured: AUTH_USER_MODEL refers to model 'users.User' that has not been installed" How can I solve it? -
Django - logout view customisation fail
I'm fairly new to Django and in order to pass in more context to logout view I tried 2 methods to customise the logout view: Method 1: from django.contrib.auth import views as auth_views from boutique.models import Category app_name = 'users' urlpatterns = [ ... path('logout/', auth_views.LogoutView.as_view(), {'categories': Category.objects.all()}), # I also tried this: # path('logout/', auth_views.LogoutView.as_view({'categories': Category.objects.all()}), # I also tried this: # path('logout-customised-url/, auth_views.LogoutView.as_view(), {'categories': Category.objects.all()}), # This is working tho it wouldn't be automatically redirect to this path when logged out Method 2: ... path('logout/', views.NewLogoutView.as_view()), # NewLogoutView code below: views.py from boutique.models import Category from django.contrib.auth.views import LogoutView class NewLogoutView(LogoutView): def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['categories'] = Category.objects.all() return context Still not working, I guess the two methods are trying to do exactly the same thing... Is there any workaround? Thanks! -
Rest Framework deserialize one field and serilize model object
Hi I want to deserialize only using 1 field. However, I want to serialize it as an object depending on the model. Suppose I have: #models.py class Product(models.Model): name = models.CharField() amount = models.IntegerField() description = models.TextField() class Query(models.Model): name = models.CharField() product = models.ForeignKey(Product) ... #serializers.py class ProductSerializer(serializers.ModelSerializer): class Meta: model = Product fields = '__all__' class QuerySerializer(serializers.ModelSerializer): product = ProductSerializer() class Meta: model = Query fields = '__all__' I want to POST/deserialize something like this on the QuerySerializer: { "name": "Query 1", "product": "Banana", ... } and I want something like this in return for serializer: { "name": "Query 1", "product": { "name": "Banana", "amount": 1, "description": "Banana description" } ... } I know a way is overriding to_internal_value but I do not like it since it messes up with ValidationErrrors. -
Add for loop inside a django view
this is my django view.What it basically does is, it gets the checked data from Html view.But I have to loop through each data in the view, or in template so that I can get not only the name of subtest but also it's fields.Subtest is the name of my model,and name is it's field def create_test_bills(request): if request.method == 'GET': selected = request.GET.getlist('selected') for i in range(0,len(selected)): a = selected [i] print(selected) print(a) sub_test = Subtest.objects.filter(name=a) return render(request,'report.html',{'sub_test':sub_test}) -
Access Django custom user profile field
I added a custom user profile field "role" with the following models.py. from django.contrib.auth.models import User from django.db import models from django.db.models.signals import post_save from django.dispatch import receiver class Profile(models.Model): ROLE_CHOICES = ( (792, 'Student'), (172, 'Teacher'), (864, 'Supervisor'), ) user = models.OneToOneField(User, on_delete=models.CASCADE) role = models.IntegerField(choices=ROLE_CHOICES, null=True, blank=True) def __str__(self): return self.user.username @receiver(post_save, sender=User) def create_or_update_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) instance.profile.save() What is the best way to return the int value assigned to the "role"? For example if the current logged in user is assigned the role of "Teacher", I want to be able to use the 172 value elsewhere like in views.py -
AH01630: client denied by server configuration issue
After I changed something in my file(s) in my Linux server, my whole layout in website collapsed. This is how it looks myawsdjapp.com And below is the error log. [Mon Feb 17 12:52:23.636400 2020] [authz_core:error] [pid 7845:tid 140639593273088] [client 121.131.97.11:49904] AH01630: client denied by server configuration: /home/djtu/django_project/staticblog, referer: https://www.myawsdjapp.com/ Weird thing is, I don't have folder named 'staticblog'. Here's my ls command result. $ ls -la /home/djtu/django_project/ total 228 drwxrwxr-x 8 djtu www-data 4096 Feb 16 19:58 . drwxr-xr-x 7 djtu djtu 4096 Feb 17 12:33 .. -rw-r--r-- 1 djtu djtu 6148 Feb 15 14:56 .DS_Store drwxr-xr-x 6 djtu djtu 4096 Feb 15 14:56 blog -rw-rw-r-- 1 djtu www-data 167936 Feb 16 19:58 db.sqlite3 drwxr-xr-x 3 djtu djtu 4096 Feb 17 11:59 django_project -rw-r--r-- 1 djtu djtu 634 Feb 15 14:56 manage.py drwxrwxr-x 3 djtu www-data 4096 Feb 15 14:56 media -rw-r--r-- 1 djtu djtu 13994 Feb 15 14:56 posts.json -rw-r--r-- 1 djtu djtu 624 Feb 15 14:56 requirements.txt drwxrwxr-x 4 djtu djtu 4096 Feb 16 20:22 static drwxr-xr-x 5 djtu djtu 4096 Feb 16 18:55 users drwxrwxr-x 5 djtu djtu 4096 Feb 15 16:58 venv And this is my virtual host setting file. I used certbot. <IfModule mod_ssl.c> <VirtualHost … -
putting finditer() output into an array
I'm trying to find the index of all "TRN" in a string, which I've done, but then i want to put all the indexes into an array, which I can't seem to do. import re string = 'a string with TRN, then another TRN' for match in re.finditer('TRN', string): spots = match.start() print(spots) Output is: 14 32 The output i want is: [14, 32] I've tried putting it into array and append the output like this, but the result is NONE NONE. import re into_array = [] string = 'a string with TRN, then another TRN' for match in re.finditer('TRN', string): spots = match.start() x = into_array.append(spots) print(x) Output is: None None any help would be greatly appreciated. -
Django - Handle Multiple different Level Nest Model
I have some question about django nested model. As i know, to handle nested data structure, i must de-serialize every data, then create the object that will connected with ForeignKeyField. I could handle this by override the .create() method by separate every nested data by .pop() and create each object model separately. Here is the example how i handle 2 level nested data (based on documentation: DRF Documentation) def create(self, validated_data): child_data = validated_data.pop('child_data') parent_obj = ParentModel.objects.create(**validated_data) for data in child_data: ChildModel.objects.create(parent_id=parent_obj, **data) return parent_obj I have some trouble here. I have multiple multi level data structure, maybe like data below: "data_a": [ { "data_a_1": [ { "data_a_1_1": [ { "data_a_1_1_1": "example_a_1_1_1", "data_a_1_1_2": "example_a_1_1_2" } ] }, { "data_a_1_2_1": "Example a-1-2-1", "data_a_1_2_2": "Example a-1-2-2" } ] "data_a_2": [ { "data_a_2_1": "Example a-2-1" }, { "data_a_2_2": "Example a-2-2" } ] } ] My question is: What is the best way to handle dynamic data structure like this? It will take a long hardcoded script to handle multiple multilevel data structure by override .create() as i mention above. Any other best practice to handle mentioned data-strucure? -
Wagtail-ModelTranslation Template Fragment Caching
I've implemented a multilingual site using wagtail and wagtail-modeltranslation but I'm having a problem with template fragment caching. The cache works but is not respecting the separate languages. Whichever language is accessed first after a save, is the one that will be served for all languages. I've tried two ways of setting the cache key to no avail. First from the django docs, second trying to explicitly include the language code in the template First: {% cache 604800 about_copy LANGUAGE_CODE %} ... HTML ... {% endcache %} Second: Using a simple template tag from django.utils.translation import get_language @register.simple_tag(takes_context=True) def get_lang(context, *args, **kwargs): return get_language() {% cache 604800 about_copy get_lang %} ... HTML ... {% endcache %} My save method is as follows: def save(self, *args, **kwargs): """Create a template fragment key. Then delete the key.""" key = make_template_fragment_key("about_copy") cache.delete(key) return super().save(*args, **kwargs) This does clear the correct fragment regardless of not including any language related arguments Any help would be greatly appreciated. Thanks! -
Why there is raise a mistake about {%endfor%} in line 9?
{% extends 'base.html' %} {% block title %}Последние статьи{% endblock %} {% block content %} {% if latest_articles_list %} {% for a in latest_artcles_list %} <a href="#">{{a.article_title}}</a> {% endfor %} {% else %} There are no latest articles {% endif %} {% endblock %} -
Python rq.worker not honoring Django's LOGGING config
I am trying to run a standalone script outside of a Django app that interfaces with a Redis queue and uses the Python rq module. Everything is working fine but somewhere in either upgrading to Python 3.8 (from 2.7) or upgrading from Django 2.2 (from 1.11) or from rq to 1.2.2 (from 0.13) rq stopped honoring the Django LOGGING config. Here is what my Django settings.py file looks like: LOGGING = { "version": 1, "disable_existing_loggers": False, "formatters": { "verbose": { "format": "%(asctime)s [%(process)d] [%(levelname)s] pathname=%(pathname)s lineno=%(lineno)s %(message)s", "datefmt": "%Y-%m-%d %H:%M:%S" }, "simple": { "format": "%(asctime)s [%(name)s] %(levelname)s - %(message)s" } }, "handlers": { "null": { "level": "DEBUG", "class": "logging.NullHandler" }, "console": { "level": "DEBUG", "class": "logging.StreamHandler", "formatter": "simple" } }, "loggers": { "django.request": { "handlers": ["console"], "level": "ERROR", "propagate": True }, "api": { "handlers": ["console"], "level": "DEBUG", "propagate": True }, "worker": { "handlers": ["console"], "level": "DEBUG", "propagate": True }, "rq.worker": { "handlers": ["console"], "level": "ERROR", "propagate": True } } } And here is what my worker.py looks like: import django django.setup() import os import logging import redis import multiprocessing from rq import Queue, Connection from rq.worker import HerokuWorker logger = logging.getLogger("worker") if __name__ == "__main__": redis_url = os.getenv("REDISTOGO_URL", None) if … -
Is it a security risk to place protected media beside public media in Django app?
First of all, this is not a duplicate, as all other related questions are outdated and do not answer this specific question. In my Django 2.2 app I need to store public media files, as well as private media files. I have researched all possible options, and have concluded that an easy option might be using the following media urls: (Base url, ‘/media/) Public: ‘media/public’ Private ‘media/private’ With the following Nginx location config: location: media/public Internal Alias: media/public Location: media/private Internal Alias: media/private With the following view config: Def publicView(request): // view config // [“x-send-redirect”] // etc.. @login_required() Def PrivateView(request): // view config // [“x-send-file”] //etc.. Is the above secure? Is having both public and private inside media a security issue? Is it frowned upon to place a path like ‘media/private’ in a location block in nginx? (Please ignore syntax errors, I am posting this from cellphone) Thank you. -
Bulk insert in Django Rest Framework JSONAPI
I'm implementing a DRFJSonAPI API: https://django-rest-framework-json-api.readthedocs.io/en/stable/index.html However, I got stuck on trying to implement a bulk insert, it seems that the JSONAPI specification doesn't mention anything about it I found only this referring to it as an experimental feature: https://springbot.github.io/json-api/extensions/bulk/ and it doesn't seem to be implemented by DRF JSONAPI I've tried several approaches, from the basic of having a new @action defined on my viewset, to even just adding the DRF api_view and going from there. But what it looks like is that my serializer doesn't understand correctly the data and returns an empty dictionary. My serializers: from rest_framework_json_api import serializers, relations, views class VideoScriptRowSerializer(serializers.ModelSerializer): included_serializers = { 'video': 'videos.serializers.VideoOnDemandSerializer', } class Meta: model = VideoScriptRow fields = ( 'video_id', 'index', 'character', 'guessed', 'is_locked', 'loop', 'text', 'time_start', ) class VideoOnDemandSerializer(serializers.ModelSerializer): script_rows = relations.ResourceRelatedField( queryset=VideoScriptRow.objects, # queryset argument is required required=False, many=True, ) included_serializers = { 'script_rows': 'videos.serializers.VideoScriptRowSerializer', } class Meta: model = VideoOnDemand fields = ( 'title', 'workflow_status', 'initial_offset', 'video_offset', 'video_input', 'thumbnail_url', 'transcript_uri', 'created_at', 'script_rows', ) read_only_fields = ('created_at', 'workflow_status') My views: from rest_framework_json_api.views import ModelViewSet, RelationshipView class VideoScriptRowViewSet(ModelViewSet): queryset = VideoScriptRow.objects.all() serializer_class = VideoScriptRowSerializer class VideoOnDemandViewSet(ModelViewSet): permission_classes = [IsAuthenticated] queryset = VideoOnDemand.objects.all() serializer_class = VideoOnDemandSerializer Based on DRF … -
Django Datepicker and Autocomplete not rendering when used together
i am using Django, bootstrap_datepicker_plus and django-autocomplete-light. I had no issues when i used the 2 libraries separately, but when i attempt to use them both in the same form, for some reason, only the autocomplete widget is working, while the datepicker widget is not. I am not sure why, maybe it is due to conflicting libraries, but are there any solutions for this issue? I tried to search online but could not find any solution that would help me. Any help is appreciated and welcomed! The code is below: forms.py class SalesTaskPlaceHolder(forms.ModelForm): class Meta: model = SalesTask fields = ['title', 'description', 'priority', 'status', 'rnd_project', 'salesExtra', 'rndExtra', 'start_date', 'due_date'] exclude = ['task_id'] widgets = { 'salesExtra': autocomplete.ModelSelect2Multiple(url='sales-extra-autocomplete'), 'rndExtra': autocomplete.ModelSelect2Multiple(url='rnd-extra-autocomplete'), 'start_date': DatePickerInput(), 'due_date': DatePickerInput(), } def __init__(self, *args, **kwargs): self.id = kwargs.pop('id',None) super(SalesTaskPlaceHolder, self).__init__(*args, **kwargs) self.fields['title'].widget.attrs['placeholder'] = 'Title of your task' self.fields['description'].widget.attrs['placeholder'] = 'What is this task about?' self.fields['status'].widget.attrs['placeholder'] = '0-100' self.fields['salesExtra'].label = 'Sales Personnel' self.fields['rndExtra'].label = 'RnD Personnel' self.fields['rnd_project'].queryset = RndProject.objects.filter(customerRequirement__sales_project=self.id) views.py class SalesExtraAutoComplete(autocomplete.Select2QuerySetView): def get_queryset(self): qs = SalesExtra.objects.all() if self.q: qs = qs.filter(user__username__istartswith=self.q) return qs class TaskCreateView(LoginRequiredMixin, CreateView): model = SalesTask form_class = SalesTaskPlaceHolder template_name = 'rnd/task_create.html' def get_form_kwargs(self): kwargs = super(TaskCreateView, self).get_form_kwargs() kwargs['id'] = self.kwargs['id'] return kwargs def … -
Api Post always has user as null even though there is a logged in user
I am trying to have an api for my answers app. When a post is created, the user is always set to null. I am not sure of why that is. How do I auto-add some fields to the saving object, like the authenticated user, user IP address? Here is my serializer: User = get_user_model() class UserPublicSerializer(serializers.ModelSerializer): class Meta: model = User fields = [ 'username', 'first_name', 'last_name', 'is_staff', 'photo_url' ] class AnswerCreateUpdateSerializer(ModelSerializer): user = UserPublicSerializer(read_only=True) class Meta: model = Answer fields = [ 'object_pk', 'content_type', 'answer', 'user' ] read_only_fields = ['user'] And the api create view: class AnswerCreateAPIView(CreateAPIView): queryset = Answer.objects.all() serializer_class = AnswerCreateUpdateSerializer And the model is: class AnswerAbstractModel(BaseAnswerAbstractModel): user = models.ForeignKey(settings.AUTH_USER_MODEL, verbose_name=_('user'), blank=True, null=True, related_name="%(class)s_answers", on_delete=models.SET_NULL) answer = FroalaField() submit_date = models.DateTimeField(_('date/time submitted'), default=None, db_index=True) ip_address = models.GenericIPAddressField(_('IP address'), unpack_ipv4=True, blank=True, null=True) class Answer(AnswerAbstractModel): class Meta(AnswerAbstractModel.Meta): db_table = "answers" I beg your pardon for my ignorance of the django world. I am trying hard to figure it out though. That said, what should be the approach here? -
Many-to-many relationship between Django User, Permissions, and another entity
Consider a Django web app for CompanyXYZ that provides goods and services to many organizations. Users of the app will be affiliated with one or more of those organizations, and have different roles (and be permitted access to different data) within each. So, imagine a schema like this: Users>---UserOrg---- Permissions relate to services provided by the company, and in general look like: “Can order X”, “Can view X orders”, “Can order Y”, “Can view Y orders”, “Can order Z”...etc. Users should be able to log on to CompanyXYZ’s site once, and then choose from among his/her affiliated organizations to view summary data and/or place orders, depending on his/her permissions at a given organization. From an admin perspective, I need to be able to create organizations, create users, assign users to organizations, and assign permissions to users for each organization. I’m fairly new to Django, so I'm not sure if this is even doable. How would I start?