Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Is there any way to display dxf in browser?? If not do I required any viewer to integrate it to my project?
At first I tried to convert dxf to svg but it is outputed in black and white color. So it didn't work. Now I am trying to render the dxf to the browser but couldnot. Is there any to do. It will be better if there is any way in python. -
How can I use a custom logging handler with django?
I'm trying to integrate logging with loki in my django app like this: handler = logging_loki.LokiHandler( url="http://localhost:3100/loki/api/v1/push", tags={"app": "django", "env": ENV}, version="1", ) LOGGING = { # some logging configs } What do I need to change so that django uses this custom handler? I tried just referencing the handler object in the logging dict but that didn't need to be the right approach. -
The form does not save the written address to database
I want to build a form that collects shipping addresses from users! There is views.py def is_valid_form(values): valid = True for field in values: if field == '': valid = False return valid class EnCheckoutView(View): def get(self, *args, **kwargs): try: order = Order.objects.get(user=self.request.user, ordered=False) form = CheckoutForm() context = { 'form': form, 'couponform': CouponForm(), 'order': order, 'DISPLAY_COUPON_FORM': True } shipping_address_qs = Address.objects.filter(user=self.request.user, address_type='S', default=True) if shipping_address_qs.exists(): context.update({ 'default_shipping_address': shipping_address_qs[0] }) return render(self.request, 'en-checkout-page.html', context) except ObjectDoesNotExist: messages.info(self.request, 'You do not have an active order.') return redirect('core:en-checkout') def post(self, *args, **kwargs): try: order = Order.objects.get(user=self.request.user, ordered=False) except ObjectDoesNotExist: messages.warning(self.request, 'You do not have an active order') return redirect('core:en-order-summary') form = CheckoutForm(self.request.POST or None) if form.is_valid(): use_default_shipping = form.cleaned_data.get("use_default_shipping") if use_default_shipping: print('Using the default shipping address') address_qs = Address.objects.filter(user=self.request.user, default=True) if address_qs.exists(): shipping_address = address_qs[0] order.shipping_address = shipping_address order.save() else: messages.info(self.request, 'No default shipping address available') return redirect('core:en-checkout') else: print('User is entering a new shipping address') customer_name = form.cleaned_data.get('customer_name') phone = form.cleaned_data.get('phone') email = form.cleaned_data.get('email') shipping_address1 = form.cleaned_data.get('shipping_address1') shipping_address2 = form.cleaned_data.get('shipping_address2') en_shipping_country = form.cleaned_data.get('en_shipping_country') shipping_zip = form.cleaned_data.get("shipping_zip") if is_valid_form([customer_name, phone, shipping_address1]): shipping_address = Address( user=self.request.user, customer_name=customer_name, phone=phone, email=email, street_address=shipping_address1, apartment_address=shipping_address2, country=en_shipping_country, zip=shipping_zip, address_type='S' ) shipping_address.save() order.shipping_address = shipping_address order.save() set_default_shipping = form.cleaned_data.get('set_default_shipping') … -
Migrate database columns with F() in Django
I have a db table 'UserSite' with User, Site and Group in it. A site is from a user and can put into just one group. Now I want a user to be able to add a site to multiple groups. Therefor I created a new db table UserSiteGroups to handle the many to many relation. So I need to migrate all the group keys from the old UserSite table to the new UserSiteGroups table. I want to do is by a migrations script. I already made a migration to create a new database table UserSiteGroups with user, site and group. Now I just need to copy the values. It should do something like this: get usersitegroup (from the old table) update the usersitegroup where user & site == I'm reading about doing this with F(). Because there are some queries to do I don't know how to start, anyone? This is what I got now.. from django.db import migrations, models import django.db.models.deletion from django.apps import apps from django.db.models import F def migrate_groups_data(): UserSiteGroup = apps.get_model("site", "UserSiteGroup") UserSiteGroup.objects.all().update(group=F("groups")) class Migration(migrations.Migration): dependencies = [("site", "0021_uusg")] operations = [ migrations.RunPython(migrate_groups_data), ] -
How to render ModelForm on a modal
def login_request(request): if request.method == "POST": form = AuthenticationForm(request, data=request.POST) if form.is_valid(): username = form.cleaned_data.get('username') password = form.cleaned_data.get('password') user = authenticate(username=username, password=password) if user is not None: login(request, user) return redirect("main:homepage") else: messages.error(request, "Invalid Username or Password!!") else: messages.error(request, "Invalid Username or Password!!") form = AuthenticationForm return render(request, "main/login.html", {"form": form}) I want to render 'form' on a modal for user login but as modal don't have their own URL, how can I render it, for above code I've taken 'main/login.html' as the template before using modal -
Better way to hook the app urls in django cms?
Here I created a new page with django cms and added some title and attached a template. Now in the this template I want to display the objects from database so I created a new app and write some models and views.With this process while creating the new page, django cms creates new url for this page and in order to work with my app/views I need to map this view to the exact url created by django-cms otherwise the views data doesn't displays in the template. So is there any solutions so that I can automatically match the app/urls.py to the django-cms urls. project/urls.py path('', include('myapp.urls')), myapp/urls.py app_name = 'myapp' urlpatterns = [ path('some-path/', views.views..., name='some_name'), app_cms_integration/cms_app.py from cms.app_base import CMSApp from cms.apphook_pool import apphook_pool @apphook_pool.register # register the application class MyApphook(CMSApp): app_name = "myapp" name = "My Application" def get_urls(self, page=None, language=None, **kwargs): return ['myapp.urls'] myapp/views.py def some_view(request): objs = Model.objects.all() return render(request, 'template', {'objs':objs}) -
Django datetimefield not showing datetimepicker widget for new inline form rows
In regards to the image below, when I click "add entry", the new entry row no longer has the datetimepicker widget. Which is odd because it has the right class. The +1 field represents the django form auto-added additional field. Which seems to work fine. It's only the fields that are added after the page has rendered which may be a key to the solution. I am using the flatpickr package as my datetimepicker widget. trade_form.html {% extends 'dashboard/base.html' %} {% load static %} {% block content %} <script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script> <script src="{% static 'js/formset/jquery.formset.js' %}"></script> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/flatpickr/dist/flatpickr.min.css"> <script src="https://cdn.jsdelivr.net/npm/flatpickr"></script> <!-- Page Heading --> <div class="d-sm-flex align-items-center justify-content-between mb-3"> <h2>New Trade</h2> </div> <div class="row"> <div class="col"> <form action="" method="post">{% csrf_token %} {{ form.media }} {{ form.as_p }} <table class="table"> {{ entries.management_form }} {% for form in entries.forms %} {% if forloop.first %} <thead> <tr> {% for field in form.visible_fields %} <th>{{ field.label|capfirst }}</th> {% endfor %} </tr> </thead> {% endif %} <tr class="{% cycle row1 row2 %} formset_row"> {% for field in form.visible_fields %} <td> {# Include the hidden fields in the form #} {% if forloop.first %} {% for hidden in form.hidden_fields %} {{ hidden }} {% endfor %} … -
Django mail send_mail uses host IP instead of hostname returned by getfqdn
According to the documentation, django default backend uses smtplib. I am using django email to send emails in the following manner: email = EmailMessage( 'Object', 'body', my_from_addr, args.emails, [], reply_to=['my_from_addr'], ) I need to set the helo/ehlo parameter to comply with the email server according to the sending server hostname. But django seems to be using the IP of the server instead of the hostname, until now my emails have been rejected with the error smtplib.SMTPRecipientsRefused: {'args.emails': (450, b'4.7.1 Client host rejected: cannot find your hostname, [192.168.1.5]')} The smtplib documentation declares If specified, local_hostname is used as the FQDN of the local host in the HELO/EHLO command. Otherwise, the local hostname is found using socket.getfqdn(). And this actually returns the proper hostname: python3 -c 'import socket; print(socket.getfqdn())' my_proper_hostname.lan Am I missing something? Why is django using the IP address instead of the real hostname? -
I'm working with trunofficial module in python and when we use this it shows error
import trunofficial response = input("Please enter the number : ") owner = trunofficial.search(response)#<- error occurs in this line -
Exporting to XML including values from models, using element tree (Django)
I'm relatively new to django, I'm trying to get the exact value for a field in the mmodels and concatenate and then export to xml and I'm getting all fields in character format views.py def my_serialize(request): data = serializers.serialize('xml', Advert.objects.all(), fields=('file')) m_config = ET.Element("m_config", path="C:\\Users\\tojeb\\Desktop\\play.xml") ok = "C:\\Users\\tojeb\\Desktop\\new-master\\media\\" tree = ET.parse('xml/vmoops.xml') root = tree.getroot() pat = os.path.join(ok, data) ET.SubElement(m_config, "file", name="0.0", path=pat) tree = ET.ElementTree(m_config) tree.write("xml/vmoops.xml") return HttpResponse("All done!") and this is result it's giving xml/vmoops.xml <m_config path="C:\Users\tojeb\Desktop\play.xml"> <file name="0.0" path="C:\Users\tojeb\Desktop\new-master\media\&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;&#10;&lt;django-objects version=&quot;1.0&quot;&gt;&lt;object model=&quot;scheduler.advert&quot; pk=&quot;2&quot;&gt;&lt;field name=&quot;file&quot; type=&quot;FileField&quot;&gt;SECONDS.mp4&lt;/field&gt;&lt;/object&gt;&lt;/django-objects&gt;" /> </m_config> whereas this is what I want to see <m_config path="C:\Users\tojeb\Desktop\play.xml"> <file name="0.0" path="C:\Users\tojeb\Desktop\new-master\media\SECONDS.mp4" /> </m_config> Regards. -
get data from multiple models in Django
I have 3 models Policy, CustomerAccount, CustomerAccountYourDetails Policy class Policy(models.Model): date = models.DateTimeField() customer_account = models.ForeignKey(CustomerAccount, on_delete=models.CASCADE) CustomerAccount class CustomerAccount(models.Model): username = models.EmailField("Email Address") date_first_registered = models.DateTimeField() CustomerAccountYourDetails class CustomerAccountYourDetails(models.Model): customer_account = models.ForeignKey(CustomerAccount, on_delete=models.CASCADE) first_name = models.CharField("First name", max_length = 30) dob = models.DateField("Date of Birth") In views.py function policies = Policy.objects.all() return render(request, 'html file name', 'policies':policies) in html template following works {% for policy in policies %} {{policy.date}} //gives the date as expected {{policy.customer_account.username}} //gives the username as expected {{need to get first name of customer here}} {{need to get dob of customer here}} {% endfor %} how can i get the first_name and dob from CustomerAccountYourDetails model which is my third model -
CSRF-attack using Django
I'm working on a Django project and I can make a CSRF-attack from an external url or file. How I can block it? The attack consist: I create a file with this content: <html> <body> <script>history.pushState('', '', '/')</script> <form action="https://XXXXXX.com/YYYYY/AAAAAA/LLLLLL"> <input type="submit" value="Submit request" /> </form> </body> </html> I login on my page I open the file in the same browser Submit the button The request is accepted and the action is executed. Thanks for everything :) -
Get value from dropdown list without having to click button
I need to know how can I get value from dropdown list after I selected it. But I don't need to click the button before pass the value. -
Why I get 503 error in amazon in Django unittest?
I write unittest for amazon. I've installed AMAZON_ACCESS_KEY, AMAZON_SECRET_KEY, AMAZON_ASSOC_TAG for my instance. The first day - everything worked well, but on the second day I constantly get a 503 error... When I run amazon = AmazonAPI(settings.AMAZON_ACCESS_KEY, settings.AMAZON_SECRET_KEY, settings.AMAZON_ASSOC_TAG) I get <amazon.api.AmazonAPI object at 0x7fe94d752128>. But when I run product = amazon.lookup(ItemId=asin, ResponseGroup=response_group) I get urllib.error.HTTPError: HTTP Error 503: Service Unavailable. Why it happens? On the first day, everything was fine. -
django rest searching data regardless of language
I am using django_filter for my project and searching the product via its name but the product name is in foreign language users may type only in English how can I handle this issue? class ProductSearchView(generics.ListAPIView): queryset = Product.objects.all() serializer_class = ProductSerializer filter_backends = (filters.SearchFilter,) search_fields = ['id', 'name'] here is my code, if the name is in English it works fine but it is in a foreign language. Is there any way to solve this problem? Thanks in advance! -
restarting gunicorn and nginx doesn't reflect changes after pull request
Recently I hosted a Django website on digitalocean. I then edited the content of website locally and pushed them to GitHub then pulled it to server and restarted nginx and gunicorn: sudo systemctl restart nginx sudo systemctl restart gunicorn Then changes didn't reflect back to live website, Just to check if I setup gnuicorn and nginx properly, I ran sudo systemctl status gunicorn.socket I get Failed to dump process list, ignoring: No such file or directory (venv) leptitoxadmin@ubuntu1:~/pyapps/leptx$ sudo systemctl status gunicorn.socket [sudo] password for leptxadmin: Failed to dump process list, ignoring: No such file or directory ● gunicorn.socket - gunicorn socket Loaded: loaded (/etc/systemd/system/gunicorn.socket; enabled; vendor preset: enabled) Active: active (running) since Wed 2020-02-12 05:57:58 UTC; 2h 42min ago Listen: /run/gunicorn.sock (Stream) CGroup: /system.slice/gunicorn.socket Feb 12 05:57:58 ubuntu1 systemd[1]: Listening on gunicorn socket. is this the reason, why the changes don't reflect to live website? How do I solve it? thanks -
how to get django-thumbnail image url from different container docker
so i was calling my location-content api using axios from node.js docker to django docker. and i get response { "id": 1, "name": "soeta", "description": null, "contents": [ { "id": 1, "title": "any", "image_raw": "http://inventory:8003/media/content/images/QWzcJDiseGbEAvyEa4aRZU.jpg", "is_featured": false, "location": 1 } ] } as you can see for the image_raw response got the wrong domain. it got docker external_link host alias (inventory) instead of localhost. i trying to parse the response to frontend, but frontend won't load the image because of the wrong domain image's url. it works load fine when i load the image http://localhost:8003/media/content/images/QWzcJDiseGbEAvyEa4aRZU.jpg so how to do it the right way for local and production? should i fix it in node.js service or django service? any help will be appreciate these are my code models.py class AirlinesLocation(models.Model): name = models.CharField(max_length=100) description = models.CharField(max_length=100, null=True, blank=True) tnc = ArrayField(models.CharField(max_length=100, null=True, blank=True)) file_requirement = ArrayField(models.CharField(max_length=100, null=True, blank=True)) class AirlinesLocationContent(FileAttributeLocatorMixin, models.Model): title = models.CharField(max_length=150, blank=True, null=True) image_raw = ImageField(upload_to='content/images', blank=True, null=True) is_featured = models.BooleanField(default=False) location = models.ForeignKey(AirlinesLocation, related_name='contents', on_delete=models.CASCADE, null=True) views.py class AirlinesLocationListCreate(generics.ListCreateAPIView): queryset = AirlinesLocation.objects.all() serializer_class = AirlinesLocationSerializer serializer.py class AirlinesLocationContentSerializer(serializers.ModelSerializer): id = serializers.IntegerField(required=False) class Meta: model = AirlinesLocationContent fields = '__all__' class AirlinesLocationSerializer(serializers.ModelSerializer): contents = AirlinesLocationContentSerializer(many=True, read_only=True) class Meta: … -
Error in getting key value from json in Django
I am trying to get the key value from json, but nothing comes out. When I just print all json, then everything is ok, and when I print items() there is empty... What could be the problem? Without ListView with simple function it works... My view: class TransactionView(CustomPermissionRequired, ListView): model = Transaction context_object_name = 'transactions' paginate_by = 20 login_url = '/' template_name = 'payments.html' search_fields = [ ('contractor_name', 'deal__service__contractor__name__icontains'), ('from_pay_date', 'payment_date__gte'), ('to_pay_date', 'payment_date__lte'), ('tr_id', 'id__icontains') ] def get_queryset(self): print('get_def') filter_kwargs = {} for sf in self.search_fields: if sf[0] is not None: sf_value = self.request.GET.get(sf[0]) print(sf_value) if sf_value: filter_kwargs[sf[1]] = sf_value return Transaction.objects.all().select_related('currency', 'payment_source__payment_type', 'deal__service__contractor' ).filter(**filter_kwargs).order_by('-id') def get_context_data(self, **kwargs): context1 = super(TransactionView, self).get_context_data(**kwargs) for sf in self.search_fields: if sf[0] is not None: context1[sf[0]] = self.request.GET.get(sf[0]) contractors = Contractors.objects.all() context1['contractors'] = contractors return context1 My model: class Transaction(models.Model): id = models.BigIntegerField(blank=True, null=False, primary_key=True) currency = models.ForeignKey(Currency, null=True, on_delete=models.CASCADE) deal = models.ForeignKey(Deal, null=True, on_delete=models.CASCADE) payment_source = models.ForeignKey(PayerPaymentSource, null=True, on_delete=models.CASCADE) payment_date = models.DateTimeField(blank=True, null=True) amount = models.IntegerField(blank=True, null=True) status = models.CharField(max_length=255, blank=True, null=True) context = models.TextField(blank=True, null=True) HTML: {% for payment in transactions %} <td>{{ payment.context.context.deal_data.amounts_data.body }} {{ payment.currency.iso_name }}</td> {% endfor %} JSON in context: { "id": 591877, "amount": 840, "status": "routing", "context": … -
` gunicorn --bind 0.0.0.0:8000 leptitox_pro.wsgi` takes too long to respond
I ran this gunicorn --bind 0.0.0.0:8000 leptitox_pro.wsgi code, I waited more than half hour: (venv) leptxadmin@ubuntu1:~/pyapps/Leptitox$ gunicorn --bind 0.0.0.0:8000 leptx_pro.wsgi [2020-02-12 07:01:23 +0000] [2103] [INFO] Starting gunicorn 20.0.4 [2020-02-12 07:01:23 +0000] [2103] [INFO] Listening at: http://0.0.0.0:8000 (2103) [2020-02-12 07:01:23 +0000] [2103] [INFO] Using worker: sync [2020-02-12 07:01:23 +0000] [2106] [INFO] Booting worker with pid: 2106 it didn't end but then canceled it. (venv) leptxadmin@ubuntu1:~/pyapps/Leptitox$ gunicorn --bind 0.0.0.0:8000 leptx_pro.wsgi [2020-02-12 07:01:23 +0000] [2103] [INFO] Starting gunicorn 20.0.4 [2020-02-12 07:01:23 +0000] [2103] [INFO] Listening at: http://0.0.0.0:8000 (2103) [2020-02-12 07:01:23 +0000] [2103] [INFO] Using worker: sync [2020-02-12 07:01:23 +0000] [2106] [INFO] Booting worker with pid: 2106 ^C[2020-02-12 08:17:24 +0000] [2103] [INFO] Handling signal: int [2020-02-12 08:17:25 +0000] [2106] [INFO] Worker exiting (pid: 2106) [2020-02-12 08:17:25 +0000] [2103] [INFO] Shutting down: Master Why is this taking too long? is it necessary to test gunicorn serve? -
Django server is not reflecting the changes made on views.py
I have created Django project and started app whereas when i run server the below message pops up again and again. Even when i changed the views and urls as to show some message in homepage the changes are not reflecting. The below message is static whenever i hit the server. Next, start your first app by running python manage.py startapp [app_label]. You're seeing this message because you have DEBUG = True in your Django settings file and you haven't configured any URLs. Get to work! I have done correct mapping of app URL with that of project URL but still can't able to find a solution please help -
Django Inconsistent Test after Patch
I get inconsistencies when getting results after patch. I am trying to compare the results after I patch. I want to store data in a variable before it is get deleted when I patch. When I try to print a data after it is patched, it gets the new and different result. Below, I want to store the old dogs in old. However after patch, it gets renewed to new values like new. My patch serializer deletes the old record when patching. #models.py class Owner(models.Model): owner = models.CharField() class Dog(models.Model): owner = models.ForeignKey(Owner,on_delete=models.CASCADE) name = models.CharField() #test.py class Update(APITestCase): def test_update_dog(self): old = Dog.objects.filter(owner=1).order_by('id') print(old) # <QuerySet [<Dog: Ben>, <Dog: Phoebe>]> data = { 'dogs': [ {'name': 'Ryan'}, {'name': 'Louis'} ] } response = self.client.post( '/admin/login/', {'username': 'admin', 'password': 'password123'}) response = self.client.patch('/app/dogs/1/', data=data, format='json') new = Dog.objects.filter(owner=1).order_by('id') print(new) # <QuerySet [<Dog: Ryan>, <Dog: Louis>]> print(old) # <QuerySet [<Dog: Ryan>, <Dog: Louis>]> self.assertNotEqual(old[0].name, new[0].name) self.assertNotEqual(old[1].name, new[1].name) -
Django + Python social auth: How to configure OAuth for GitHub Enterprise?
With Django and social-auth-app-django, I can authorize with https://github.com with social_core.backends.github.GithubOAuth2 backend. And I'm trying to switch it to our GitHub Enterprise based on this documentation; https://python-social-auth.readthedocs.io/en/latest/backends/github_enterprise.html#github-enterprise Here is my settings.py: INSTALLED_APPS = [ ... 'social_django', ] MIDDLEWARE = [ ... 'social_django.middleware.SocialAuthExceptionMiddleware', ] TEMPLATES = [ { ... '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', 'social_django.context_processors.backends', 'social_django.context_processors.login_redirect', ... ] SOCIAL_AUTH_GITHUB_ENTERPRISE_URL = 'https://github.mycompany.com/' SOCIAL_AUTH_GITHUB_ENTERPRISE_API_URL = 'https://github.mycompany.com/api/v3/' SOCIAL_AUTH_GITHUB_ENTERPRISE_KEY = '----' SOCIAL_AUTH_GITHUB_ENTERPRISE_SECRET = '----' AUTHENTICATION_BACKENDS = ( 'social_core.backends.github_enterprise.GithubEnterpriseOAuth2', 'django.contrib.auth.backends.ModelBackend', ) But it complains with below error: Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/social-auth/login/github/ Raised by: social_django.views.auth Backend not found I'm sure the class social_core.backends.github_enterprise.GithubEnterpriseOAuth2 is in /usr/local/lib/python3.8/site-packages/social_core/backends/github_enterprise.py. If I use the backend as social_core.backends.github.GithubOAuth2 it redirects to https://github.com/login/oauth/authorize? which is not desired. Could you please guide me how to setup backend for GitHub Enterprise? -
Auto set Csrf token between Django & React (Seperated)
I have built django rest framework and React on a separated folder. Means both of them are independent. For normal cases. (Django & React same stack) When React is up, a csrf token will inside the cookies because of session authentication For my cases. (Django & React separated) When browser React, csrf token is not set because it is not linked with django How should I link both of them together so that every time I open react frontend, a csrf token will be set inside the cookies? Really people to explain this to me, have seeking for answer in these few day. -
Delete entries from ManyToMany table using _raw_delete
I have a huge amount of data in my db. I cannot use .delete() method cause performance of Django ORM is insufficient in my case. _raw_delete() method suits me cause I can do it python instead using raw SQL. But I have problem I have no idead how can I delete relation tables using _raw_delete. They need to be deleted before models cause I have restrict in DB. Any ideas how can I achieve this? -
Django post form submission with AJAX
I am working on a forum website using Django version 1.11.4 and python 3.6.5. I made a landing page that redirect to forum page. In landing page the user will select the forum category and forum subcategory. In the forum page, there is a post form that user can post new thread to the same page . This is done through AJAX “ I am using jQuery 3.1.1. There are two models in Django one for the post and another one for images for that post. I gave the option for the user to upload as many field as he or she wants. This is done through foreign key The model are as follow: class ForumsPosts(models.Model): id = models.AutoField(primary_key=True) user = models.ForeignKey(MyUser, on_delete=models.CASCADE) category = models.ForeignKey(Post_Category, on_delete=models.CASCADE) sub_category = models.ForeignKey(Post_Sub_Category, on_delete=models.CASCADE) title = models.CharField(max_length=128) content = models.TextField(max_length=65536) date_created = models.DateTimeField(auto_now =False, auto_now_add=True) date_updated = models.DateTimeField(auto_now=True, auto_now_add=False) def forums_post_username(self): return self.user.username def forums_post_first_name(self): return self.user.first_name def forums_post_category_name(self): return self.category.category_name def forums_post_sub_category_name(self): return self.sub_category.sub_category_name def __str__(self): return "%s %s %s %s %s %s %s" % (self.id, self.category, self.sub_category, self.title, self.content, self.date_created, self.date_updated, ) class Meta: verbose_name_plural = "forumsPost" # Forums images class ForumsPostImages(models.Model): id = models.AutoField(primary_key=True) post = models.ForeignKey(ForumsPosts, on_delete=models.CASCADE) images = …