Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django save() refuses to update an existing record
I've got the below model and a function that I call from view.py to update a field within that model called unread_count. However, it keeps trying to create a record rather than update the existing one and I get the error shown below. I've included 2 print statements to show the records exist. I've tried various things to get it working but I'm not making any progress (besides tearing my hair out). Any help would be appreciated. class RoomOccupier(TimeStampedModel): room = models.ForeignKey(Room, on_delete=models.CASCADE, db_index=True) occupier = models.ForeignKey(UserAccount, on_delete=models.CASCADE, related_name="+", db_index=True) unread_count = models.PositiveSmallIntegerField(default=0, blank=False) def __int__(self): # __unicode__ for Python 2 return self @database_sync_to_async def increment_unread(room_id): roomOccupiers = RoomOccupier.objects.filter(room_id=room_id) print(roomOccupiers) for roomOccupier in roomOccupiers: print(roomOccupier) roomOccupier.unread_count += 1 roomOccupier.save() return true <QuerySet [<RoomOccupier: RoomOccupier object (1)>, <RoomOccupier: RoomOccupier object (2)>]> RoomOccupier object (1) Exception inside application: NOT NULL constraint failed: chat_roomoccupier.created Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql, params) File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/django/db/backends/sqlite3/base.py", line 413, in execute return Database.Cursor.execute(self, query, params) sqlite3.IntegrityError: NOT NULL constraint failed: chat_roomoccupier.created The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/channels/staticfiles.py", line 44, in __call__ return await self.application...etc... -
Problem in comparing Arabic and persian texts in django Filter
The below model has a field that takes a name and searches it in an API. class Symbol(models.Model): name = models.CharField(max_length=20, unique=True, blank=False) sigma = models.FloatField(null=True) s = models.IntegerField(null=True) The problem is that the model name property is Persian and the API content is Arabic so Django filter can't find the model object. e.g: >> 'ي'=='ی' >> False # while it should be true >> Symbol.objects.get(name="آریا") #returns nothing while it exists I need something like localecompare() in javascript. p.s: model data is taken from other API so I can't enter the data manually in Arabic. -
How to create a list with checkbox values and return to request.POST
I want to get the values of checkbox and return it to request.POST {% for flow in data.flows %} <div style="margin-bottom:-27px"> <div class="w3-bar"> {% csrf_token %} <input type="checkbox" id="{{flow.0}}" name="precedent" value="{{flow.0}}"><label for="scales" > {{flow.0}} - {{flow.1}}</label> <br> <br> </div> </div> % endfor %} So I want to return all the values in a list to def create_flow_and_phases(request): ... Any suggestions? -
How to use a prop from an auth route to gain props from a different route? (Django/React)
I'm creating a profile page with Django and react. The idea is that once a user is signed in, they go to a profile page and it sends a get request to http://localhost:8000/users/auth/user and then uses the props to populate the page. However, since this is a Django-created route, I need to use maybe data.username to link a different route that displays all the other props i need (such as bio, location) and then populate the rest of the profile with this. Here is an example of the code: fetch('http://localhost:8000/users/auth/users', { method: 'GET', headers: { 'Content-Type': 'application/json', Authorization: `Token ${localStorage.getItem('token')}` } }) .then(data => { console.log(data) setUserName(data.username); And somehow use data.username to fetch another route that displays my other props not located in auth. How can I do this within the fetch/then format? Please let me know if further clarification is needed. Thank you! -
Django error 'ModuleNotFoundError: No module named 'ocore'
New to Django and have just started building out a new project following a tutorial. I have created a virtual environment as follows: pip install virtualenv virtualenv myproject_3_7_3 I then activate the virtual env and install Django as follows: cd myproject_3_7_3 source bin/activate pip install django This installs Django version 3.2.10 successfully, so then I activate the project, add some folder structure and create an app using the following commands: django-admin startproject myproject cd myproject mkdir apps mkdir apps/core python manage.py startapp core apps/core I then open VSCode and I can see the project and all of the default folders/files there. To start the app I run: python manage.py startapp core apps/core But I immediately get the following error in the terminal. Traceback (most recent call last): File "/Users/myuser/myproject_3_7_3/lib/python3.7/site-packages/django/apps/config.py", line 244, in create app_module = import_module(app_name) File "//anaconda3/lib/python3.7/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 965, in _find_and_load_unlocked ModuleNotFoundError: No module named 'ocore' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) … -
ValueError: Field 'id' expected a number but got string in Django Rest Framework
In DRF I am facing an issue, whenever I do a POST request on the endpoint, on the field "name" which is a text field I get an exception "Field 'id' expected a number but got 'TITLE'", but when I change the value of "name" to an integer the request is successful I don't understand it becauses name is TextField in model and why its mixing Id and Name field with each other. I have deleted the migration files from the Project and DB and re-run the Migrations, but still facing this issue. Following is my code: models.py class Project(models.Model): admin = models.ForeignKey(User, on_delete=models.CASCADE, related_name='project_crated_by') name = models.TextField(max_length=225, blank=False, null=False) project_members = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name='members', null=True, blank=True) created_on = models.DateField(default=timezone.now) tags = ArrayField(models.CharField(max_length=225, default=''), blank=True) def __str__(self): return self.name objects = models.Manager() views.py class ProjectView(viewsets.ViewSet): def create(self, request): project_name_exist = Project.verify_project_name(request.data['admin'], request.data['name']) if project_name_exist: return Response({'message': 'You already have a project with this name', 'status': status.HTTP_200_OK}) serialized_project = ProjectSerializer(data=request.data) if serialized_project.is_valid(): serialized_project.save() return Response({'message': 'Project Created Successfully', 'status': status.HTTP_201_CREATED}) else: return Response({'error': serialized_project.errors, 'status': status.HTTP_400_BAD_REQUEST}) serializer.py class ProjectSerializer(serializers.ModelSerializer): class Meta: model = Project fields = '__all__' -
django redirect update to detail view after ajax update
I want to redirect to detail view after an update that uses ajax form submission. Urls path('<uuid:pk>', concept_detail, name='concept_detail'), path('<uuid:pk>/update/', update_concept, name='update-concept'), Detail View def concept_detail(request, pk): context = {} context['concept'] = Concept.objects.get(id=pk) return render(request, 'concepts/concept_detail.html', context) Update View @login_required def update_concept(request, pk): if request.method == 'POST': try: ## I GET THE FORM DATA - I haven't included the querysets because I haven't figured it out yet, just want to get the redirect to work print(request.POST) ## THIS DOESN'T WORK, BUT IT WORKS BELOW concept = Concept.objects.filter(id=pk).first() return redirect(concept) except Exception as e: print(e) else: ## this populates the update form context = {} obj = get_object_or_404(Concept, pk=pk) context['concept'] = obj if (request.user == obj.user): return render(request, 'concepts/concept_update.html', context) else: ## If user didn't create the post but tried to go to update url, redirect to detail page - WORKS concept = Concept.objects.filter(id=pk).first() return redirect(concept) Response Codes Don't know why I'm getting 302 for update view -- don't get that for my create view, and the forms and ajax are basically the same. "POST /concepts/1241955d-1392-4f85-b8ed-e3e0b89b4e50/update/ HTTP/1.1" 302 0 "GET /concepts/1241955d-1392-4f85-b8ed-e3e0b89b4e50 HTTP/1.1" 200 7577 AJAX FORM SUBMIT The form is a lot more dynamic than this which is why I'm using … -
create() in Django gives me ValueError "Field 'width' expected a number but got 'NA'
I am trying to insert several rows from .csv file into SQLite in Django. I don't want to be using import_data(), because I wanted to have a more granular control for each insertion. My model is something like this: class Box(models.Model): name = models.CharField(max_length=30) color = models.CharField(max_length=30) size = LengthField(blank=True, null=True, default=None, decimal_places=2,validators=(MinValueValidator(0, field_type='Length'),MaxValueValidator(100, field_type='Length')))) Only name has a constraint to be unique. Now, when i am running get_or_create, and have a csv row that has a blank for size, i am getting an error "ValueError - Field 'size' expected a number but got 'NA'". (For the csv rows before that, everything is inserted correctly.) I find it strange because in the model i have blank=True and null=True for size. What could i be doing wrong and how i could fix that? Thank you in advance! -
Access to index of list field in django template
models.py class Keys(models.Model): CHOICES = (('a','a'),('b','b'),('c','c'),('d','d')) choice = MultiSelectField(choices=CHOICES,blank=True) My template: {% for k in m.choice %} {{????}} {% endfor %} How i can access to index of value in list fields? Sample Output: 0 1 2 3 -
Fields not rendering correctly when using Django UserCreation Form and AbstractUser
I'am extending the AbstractUser just adding some new fields, and extending UserCreationForm to render the fields. I don't know why the input fields looks like this (some fields are larger than others). Can't find a solution to this. My code: models.py from django.contrib.auth.models import AbstractUser from django.db import models from django.utils.translation import gettext_lazy as _ # Create your models here. class CustomUser(AbstractUser): WOMAN = "female" MAN = "male" GENDER = [(WOMAN, "Female"), (MAN, "Male")] gender = models.CharField(verbose_name=_("Gender"), choices=GENDER, max_length=10, null=True, blank=False,) phone = models.CharField(verbose_name=_("Phone"), max_length=20, null=True, blank=True,) form.py from django.contrib.auth.forms import UserCreationForm, UserChangeForm from django.utils.translation import gettext_lazy as _ from .models import CustomUser class CustomUserCreationForm(UserCreationForm): class Meta(UserCreationForm): model = CustomUser fields = ['email', 'gender', 'phone', 'first_name', 'last_name'] views.py class SignUpView(CreateView): """Signup View.""" form_class = CustomUserCreationForm success_url = reverse_lazy("home") template_name = "registration/signup.html" signup.html {% extends 'base.html' %} {% load static %} {% load i18n %} {% load crispy_forms_tags %} {% block content %} <section id="login" class="container secondary-page"> <div class="general general-results players"> <!-- LOGIN BOX --> <div class="top-score-title right-score col-md-6"> <h3>Register<span> Now</span><span class="point-int"> !</span></h3> <div class="col-md-12 login-page"> <form method="post" class="login-form"> {% csrf_token %} {{ form|crispy }} <button type="submit" class="btn btn-primary">Submit</button> </form> </div> </div> </div> </section> {% endblock content %} -
How do I make sure Docker django site is accessible via url even after extended period of inactivity on server?
I have deployed a Django REST API using Docker on AWS EC2 instance. Due to low traffic on site api sees the extended period of inactivity and it throughs 503 error (Service Unavailable). The aws logs are ok with no signs of throttle. How do I make sure my service is always available without me needing to manually restart the docker? -
Trying to add data to Postgresql database using psycopg2
I was able to create the script to add data straight into Postgresql table. The only problem is ManyToManyFields. While I'm able to add the data, I am not able to link to the ManyToMany. Here is my models.py class Category(MPTTModel): name = models.CharField(max_length=150, unique=True) parent = TreeForeignKey('self', on_delete=models.CASCADE, null=True, blank=True, related_name='children') class MPTTMeta: order_insertion_by = ['name'] def __str__(self): return self.name from django.urls import reverse class Listing(models.Model): name = models.CharField('Business Name', max_length=250) address = models.CharField('Address', max_length=300) phone_number = models.CharField('Phone Number', max_length=20) web = models.URLField('Website') category = models.ManyToManyField(Category) main_image = models.CharField('Image Link', max_length=500) LISTING_STATUS = ( ('a', 'Active'), ('e', 'Expired'), ('i', 'Inactive'), ('c', 'Claimed'), ) status = models.CharField( max_length=1, choices=LISTING_STATUS, blank=True, default='a', help_text='Listing Status', ) def get_cats(self): return ", ".join([str(p) for p in self.category.all()]) def __str__(self): return self.name def get_absolute_url(self): return reverse('listing-detail', args=[str(self.id)]) In another file, I created another code to add information into the database: def insert(name, address, phone_number, web, status, main_image, ): conn = psycopg2.connect("host=localhost dbname=augustalife user=postgres") cur = conn.cursor() cur.execute("INSERT INTO listings_listing (name, address, phone_number, web, status, main_image) VALUES (%s,%s,%s,%s,%s,%s);", (name, address, phone_number, web, status, main_image)) conn.commit() conn.close() I know that I can manually link items if I am using Django shell. But, is there a way to … -
Django: Forbidden (CSRF cookie not set.) on DELETE
At a high level, my GET, POST, and PUT requests are all working. When I try a DELETE request, I get a following error: Forbidden (CSRF cookie not set.): /department/1 I'm following the follow tutorial to build my first Angular/Python Django/SQLite app There have been a few discrepancies due to me using newer versions of Django. https://www.youtube.com/watch?v=1Hc7KlLiU9w https://github.com/ArtOfEngineer/PythonDjangoAngular10/tree/master/DjangoAPI I'm up to about ~31 minutes Here are my installations in my virtualEnv asgiref==3.4.1 Django==4.0 django-cors-headers==3.10.1 djangorestframework==3.12.4 pytz==2021.3 - the example I'm following didn't install this. I needed to though get it to run sqlparse==0.4.2 tzdata==2021.5 PracticeApp/views.py #PracticeApp/views.py from django.shortcuts import render from django.views.decorators.csrf import csrf_exempt from rest_framework.parsers import JSONParser from django.http.response import JsonResponse from PracticeApp.models import Departments, from PracticeApp.serializers import DepartmentSerializer @csrf_exempt def departmentApi(request, id=0): if request.method=='GET': departments = Departments.objects.all() departments_serializer = DepartmentSerializer(departments, many=True) return JsonResponse(departments_serializer.data, safe=False) elif request.method=='POST': department_data=JSONParser().parse(request) department_serializer = DepartmentSerializer(data=department_data) if department_serializer.is_valid(): department_serializer.save() return JsonResponse("Added Successfully!!" , safe=False) return JsonResponse("Failed to Add.",safe=False) elif request.method=='PUT': department_data = JSONParser().parse(request) department=Departments.objects.get(DepartmentId=department_data['DepartmentId']) department_serializer=DepartmentSerializer(department,data=department_data) if department_serializer.is_valid(): department_serializer.save() return JsonResponse("Updated Successfully!!", safe=False) return JsonResponse("Failed to Update.", safe=False) elif request.method=='DELETE': department=Departments.objects.get(DepartmentId=id) department.delete() return JsonResponse("Deleted Successfully!!", safe=False) in the urls.py you'll see that I'm using from django.urls import path instead of from django.conf.urls import url. Therefore … -
How to get user location using models in django
so I am looking a way to receive users location when user will submit the location and other fields from map then it should send the location in lng and lat so I can check the location of the user.... Like uber ola does -
How can I structure a Django REST API for a lot of similar online games?
I am very new to Django and the Django REST Framework and I want to implement an API for 4 relatively similar games. The most basic game consists of a player labelling an image and receiving points for this if they enter the same labels as their co-player for the same image. One game session consists of 3 rounds. What I have done so far is create a view for the game type, game session, game round, image to be shown and the labels, which will be divided into Taggings (a user has used this label as input) and Tags (more than one user has entered this very same label for the same picture). All of those views look similar to the Gametype and Tagging views below. """ API View that handles retrieving the correct type of a game """ serializer_class = GametypeSerializer def get_queryset(self): gametypes = Gametype.objects.all().order_by("name") return gametypes def get(self, request, *args, **kwargs): gametype = self.get_queryset() serializer = GametypeSerializer(gametype, many=True) return Response(serializer.data) class Tagging(APIView): """ API View to do everything to do with taggings """ serializer_class = TaggingSerializer def get_queryset(self): taggings = Tagging.objects.all().filter(resource=8225) return taggings def get(self, request, *args, **kwargs): tagging = self.get_queryset() serializer = TaggingSerializer(tagging, many=True) return … -
ModuleNotFoundError: No module named 'foo'
I´m trying to make a cron inside my django app with django-crontab==0.7.1,. Within my project settings installed apps, crontab app first, and then my app, both registered. In my cron.py: from .models import Url urls=Url.objects.values_list('url') def foo(url): if url not in urls: link= Url( url=url, ) link.save() foo('https://example.org') Also tried to put inside cron.py, but it doesn´t make sense since both are inside same app from foo.models import Url Also init.py inside app My models.py inside foo app, after migrations ran from django.db import models class Url(models.Model): url=models.URLField('url',blank=False,null=False) but still getting ModuleNotFoundError: No module named 'foo' Sorry if this has been asked before, but nothing watched yet gives me the answer Thank you -
date time model table for two models-OneToOne - django
I'm working on a project which has several models but two of them are Invoice and the other for Payment, in the both tables should have a field named next_payment for the loaners to determine when he/she should pay his/her loan class Payment(models.Model): admin = models.ForeignKey(User,on_delete=models.CASCADE) price = models.DecimalField(max_digits=20,decimal_places=3) #others class Invoice(models.Model): seller = models.ForeignKey(User,on_delete=models.PROTECT) customer = models.CharField(max_length=50) #others should i add new fields named next_payment for both two models or create a new model , something like this class NextPayment(models.Model): next_payment = models.DateTimeField() and add NextPayment has OneToOne connection for two both models ? which one is the most effective way please ? thank you in advance .. -
request.data empty when request is sent by Insomnia
I just want to update the "name" attribute via API, but when I make the request through Insomnia, data appears as an empty dictionary. Why "name" is not in request.data? Below is the Insomnia JSON request: (method = PATCH) { "name": "name_test" } Everything is working well, but when I access the data dictionary from request it's empty. See below in the image: Below is the code of backend API def partial_update(self, request, pk=None): try: flow = Flow.objects.get(pk=pk) if "name" in request.data and request.data["name"]: flow.name = request.data["name"] flow.save() return Response({"Response": "Object changed successfully"}) except Exception as e: return Response({"Response": str(e)}) Any suggestions about why data is empty? The JSON format is wrong? -
Add digicert certificate for django/python web app on Azure
A wild card cert has been purchased through Digicert for a domain and I'm currently trying to add this cert to a django/django-rest API hosted on Azure which will resided on a subdomain under that purchased custom domain. I have configured the web app to recognize the custom subdomain and at this point need to add the pfx file. I have received the pfx file from another who created it through Digicerts windows utility. NGINX was used as the server type, not sure if this is part of the issue or not. When creating a python/django web app on Azure it seems to make a Linux container which runs gunicorn.... When uploading the pfx file and supplying the password given, Azure Portal returns with an error either saying the file or password is incorrect. Tried multiple times with multiple recreations of the pfx file. Even tried taking a given crt file and using openssl locally to generate a pfx file with password and no luck. Thoughts & guidance? Do I need to use a Key Vault instead and link to Digicert? -
Django Admin Dropdown
I am trying to get the selected value from the dropdown in django admin model but unable to achieve it. Just want to select any of the value from the dropdown and when I click that Need that value should print in my console -
while loop not seeing dynamic created form fields
So everything looks good on the html and css where the dynamically created objects have the correct attributes. let $this = $("#id_variant_0") let $clone = $this.clone() let name = $clone.attr('name') let n = count name = 'variant_' + n count++ $clone.val('') $clone.attr('name', name) let new_id = "id_" + name $clone.attr('id', new_id) $clone.appendTo($this.parent()) $this.addClass('form-control') }) but I can't seem to get the while loop to work, it only sees the first one. variants = set() i = 0 field_name = 'variant_%s' % (i,) while self.cleaned_data.get(field_name): variant = self.cleaned_data[field_name] print("^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^") print(variant) if variant in variants: self.add_error(field_name, 'Duplicate') else: variants.add(variant) i += 1 field_name = 'variant_%s' % (i,) self.cleaned_data["variants"] = variants def get_variant_fields(self): for field_name in self.fields: if field_name.startswith('variant_'): yield self[field_name] What am I doing wrong here? -
Selenium tests in docker fails after 1st time
I am trying to run a selenium test in docker. The test runs for the first time when I deploy the application for the first time, but after that I get error in fetching page using self.driver.get(url). Fetch error Message: Reached error page: about:neterror?e=connectionFailure&u=https%3A//web.url.com/&c=UTF-8&d=Firefox%20can%E2%80%99t%20establish%20a%20connection%20to%20the%20server%20at%20web.url.com. Stacktrace: WebDriverError@chrome://remote/content/shared/webdriver/Errors.jsm:181:5 UnknownError@chrome://remote/content/shared/webdriver/Errors.jsm:488:5 checkReadyState@chrome://remote/content/marionette/navigate.js:64:24 onNavigation@chrome://remote/content/marionette/navigate.js:312:39 emit@resource://gre/modules/EventEmitter.jsm:160:20 receiveMessage@chrome://remote/content/marionette/actors/MarionetteEventsParent.jsm:42:25 I have tried code : options = Options() options.headless = True profile = webdriver.FirefoxProfile() profile.accept_untrusted_certs = True self.driver = webdriver.Firefox(firefox_profile=profile, options=options) Later used, self.driver.get(url) -
Display foreign key info within Django Detail View Template
As the title says I have a detailed view that I'm presenting via Django templates. I have a foreign key that I'd also like to present within that detailed view and I just can't get it to work. I've tried everything, but all I get is the basic detailed view template with no foreign key info. Any help would be greatly appreciated. Here's what I've got so far: Models: class Cust(models.Model): #this is the main model id = models.UUIDField( primary_key=True, default=uuid.uuid4, editable=False) email = models.CharField(max_length=200) firstName = models.CharField(max_length=200) lastName = models.CharField(max_length=200) watchmanSlug = models.CharField(max_length=200, unique=True) class Watchman(models.Model): group = models.ForeignKey(Cust, on_delete=models.CASCADE,to_field='watchmanSlug', related_name='watchman_group_slug') uid = models.CharField(max_length=500) computer_name = models.CharField(max_length=500) computer_url = models.CharField(max_length=500) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) Views class CustomerDetailView(DetailView): model = Cust template_name = 'cust/cust_detail.html' def get_context_data(self, ** kwargs): context = super(CustomerDetailView, self).get_context_data( ** kwargs) context['computer_name'] = Watchman.objects.all() return context Detail Template <tbody> <ul> {% for p in watchman_group_slug.all %} <li>{{ watchman.computer_name }}</li> {% endfor %} </ul> </tbody> -
Django, Gunicorn, Nginx redirect to local host
I am trying to configure a production server using gunicorn and nginx for my Django app. Currently I have gunicorn running but when I do a curl to my local host, I receive no output, so I think the issue is in my Django urls/views but I am not sure what to change as I am not referencing localhost anywhere. I also have nginx running. I am not using the nginx.conf file directly as I created a symlink and am using site-enabled. Here is my sites-available config: # /etc/nginx/sites-availible/msc_project.conf # HTTP to HTTPS redirect: server { listen 0.0.0.0:80; server_name mscentral.mysite.com; # Certbot Letsencrypt verification location /.well-known/acme-challenge { alias /home/mscentral/mscentral_project/static/.well-known/acme-challenge/; # } return 301 https://mscentral.mysite.com$request_uri; } # Virtual host for mscentral server { listen 0.0.0.0:443 ssl; server_name mscentral.mysite.com; ssl_certificate /etc/letsencrypt/live/mscentral.mysite.com/fullchain.pem; ssl_certificate_key /etc/letsencrypt/live/mscentral.mysite.com/privkey.pem; #static file handling location /static/ { alias /home/mscentral/mscentral_project/static/; } location /media/ { alias /home/mscentral/mscentral_project/media/; } #WSGI server location / { proxy_set_header X-Real-IP $remote_addr; proxy_pass http://localhost:8000/; } access_log /var/log/nginx/mscentral_project-access.log; error_log /var/log/nginx/mscentral_project-error.log; } here is my gunicorn service file: [Unit] Description=My Central Service for Gunicron After=network.target [Service] Type=simple # Another Type: forking User=mscentral_internal WorkingDirectory=/home/mscentral/mscentral_project ExecStart=/home/mscentral/venv/bin/gunicorn -b localhost:8000 mscentral_project.wsgi Restart=on-failure # Other restart options: always, on-abort, etc # The install section is … -
How do I inherit columns from a parent django-tables2 Table when model has different accessors?
I have the following models. class Foo(models.Models): X_CHOICES = ( ('abc','Display String for ABC'),) x = models.CharField(max_length=10, choices=X_CHOICES) class Bar(models.Models): foo = models.ForeignKey(Foo, on_delete=models.CASCADE) y = models.CharField(max_length=10) class BarRelative(models.Models): bar = models.ForeignKey(Bar, on_delete=models.CASCADE) z = models.CharField(max_length=10) I need to have two django-tables2 Tables as follows; one for Bar and one for BarRelative. class BarTable(tables.Table): foo = tables.Columns(accessor='foo') y = tables.Columns(accessor='y') class Meta: model = Bar def render_foo(self, record): return f'{record.foo.get_x_display()}' class BarRelativeTable(BarTable): # I don't want to have to redefine the foo column just to change the accessor # foo = tables.Column(accessor='bar__foo') # I just want to add the new column z z = tables.Column(accessor='z') class Meta(BarTable.Meta): model = BarRelative # I don't want to redefine render_foo() just to change the accessor like this... # def render_foo(self, record): # return f'{record.bar.foo.get_x_display()}' def render_z(self, record): return f'{record.z}' I tried using "multi-table" inheritance with my models, however this did not work because Bar to BarRelative is a one-to-many relationship. Multi-table inheritance only works for one-to-one, so I am forced to use a ForeignKey in my model. Next I tried annotating each Field in Bar in my QuerySet for BarRelative in a manager like this... class BarRelativeManager(models.Manager): def get_queryset(self): return super().get_queryset().annotate(foo = F(bar__foo)) …