Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
flask gateway equlivent in django
I'm setting up my Braintree web-hooks in Django, as Braintree docs says i have to add this method from flask import Flask, request, render_template, Response ... def webhook(): webhook_notification = gateway.webhook_notification.parse(str(request.form['bt_signature']), request.form['bt_payload']) # Example values for webhook notification properties print(webhook_notification.kind) print(webhook_notification.timestamp) return Response(status=200) everything is ok except i have no idea what gateway is, and I'm getting undefined name error my Django code @csrf_exempt def webhook(request): print("post:: ", request.POST) webhook_notification = gateway.webhook_notification.parse(str(request.form["bt_signature"]), request.form["bt_payload"]) print(webhook_notification.kind) print(webhook_notification.timestamp) return HttpResponse("Ok") -
django.db.utils.ProgrammingError: relation "xx" does not exist
I was trying to add a new column to a database table by using make migrations on Django, bit didn't work and I got some weird errors. Following advice on another SO post I used DROP TABLE to delete the table and start again. The problem is, now when I try to migrate the table it doesn't appear in my PostgreSQL database. When I check make migrations I don't get any changes to migrate suggesting it is synced. I have also run: python3 manage.py migrate --run-syncdb and still getting no luck. I'd appreciate any help. class UserVenue(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) venue = models.ForeignKey(mapCafes, on_delete=models.PROTECT) user_list = models.ForeignKey(UserList, on_delete=models.CASCADE) class Meta: unique_together = ['user_list','venue'] For some reason I can still see the table in Django Admin but then get this error: Environment: Request Method: GET Request URL: http://127.0.0.1:8000/admin/testingland/uservenue/ Django Version: 3.1.7 Python Version: 3.8.5 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.gis', 'testingland', 'rest_framework', 'bootstrap_modal_forms'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql, params) The above exception (relation "testingland_uservenue" does not exist LINE 1: SELECT COUNT(*) AS "__count" FROM "testingland_uservenue" ^ ) was the direct … -
How to pass object 1st Serializer to 2nd Serializer, 2nd Serializer to 3rd Serializer and 3rd to 4th
Hello everyone I'm new to the Django framework. I need to pass the 1st Serializer object to the 2nd Serializer, the 2nd Serializer to the 3rd, and the 3rd Serializer to the 4th Serializer. Here is my code URL : path('job/int:pk/sections/templates/', JobViewSet.as_view({'get': 'list'})) Here is the method **all_templates(self, request, *args, kwargs) inside this method I added JobDetailSerializer(job) and pass the job object. @action(detail=True, methods=["GET"], url_path='sections/templates') def all_templates(self, request, *args, **kwargs): job = self.get_object() serializer = JobDetailSerializer(job) return Response( { 'status': SUCCESS, 'message': 'Data Received Successfully', 'status_code': HTTP_200_OK, 'data': serializer.data } ) 1st Serializer: JobDetailSerializer class JobDetailSerializer(serializers.ModelSerializer): template = JobTemplateListAllSerializer() class Meta: model = Job fields = ('manufacturer', 'model', 'serial_number', 'registration', 'engine_designation', 'date', 'location', 'created_at', 'image', 'client', 'customer', 'technician', 'template') depth = 1 Up to above, it's working fine now. 2nd Serializer: JobTemplateListAllSerializer class JobTemplateListAllSerializer(serializers.ModelSerializer): sections = JobSectionStructureListAllSerializer(many=True) class Meta: model = JobTemplates fields = ['sections'] 3rd Serializer: JobSectionStructureListAllSerializer class JobSectionStructureListAllSerializer(serializers.ModelSerializer): id = serializers.IntegerField(required=False) templates = serializers.SerializerMethodField() class Meta: model = JobSectionStructure fields = ['id', 'access', 'section_master', 'templates'] read_only_fields = ('job_template',) depth = 1 def get_templates(self, obj): template_structures = JobTemplateStructure.objects.all().filter(job_section_id=obj.id, template_master__parent_id=0) new_template_structure = [] for template_structure in template_structures: job_template_structure = JobTemplateStructure.objects.all() sub_template_structures = job_template_structure.filter(job_section_id=obj.id, template_master__parent_id=template_structure.template_master.id) template_structure.sub_templates = JobTemplateStructureDataListAppSerializer(sub_template_structures, many=True).data new_template_structure.append(template_structure) return … -
Does django field update nullable columns if you add a default value?
Let's say I have a field: status = CharField(max_length=20, null=True, blank=True) Then, I change this field to: status = CharField(max_length=20, blank=True, default="GOOD") does that mean that every object existing in the table with status=None will be converted to status=GOOD? Does that mean I don't need to create an data migration file? -
how to find a dictionary element using Jinja
I have python dict object which I am passing to the template {'bla bla': 'lalala'}. I want to reach this object with Jinja {{ dict_name.'bla bla' }} or {{ dict_name.bla bla }} or {{ dict_name['bla bla'] }} but all this not working. What i need do? -
How to return a html code having text and image using Ajax?
I am working in Ajax, and I want to print a text and then print the image below of that text using ajax. In Ajax code, there is a live_image_update() function and I want it to return the value text <br> image on success. The Ajax code is: <script> var state = NaN $(document).ready(function(){ $("#contactForm").submit(function(e){ // prevent from normal form behaviour e.preventDefault(); // serialize the form data var serializedData = $(this).serialize(); $.ajax({ type : 'POST', url : "{% url 'BFS:contact_submit' %}", data : serializedData, success : function(response){ //reset the form after successful submit $("#contactForm")[0].reset(); // This will then call for the get request to update the id "myText" live_update(); live_image_update(); live_state_update() }, error : function(response){ console.log(response) } }); }); function live_image_update(){ $.ajax({ url: "{% url 'BFS:get_bfs_image_info' %}", type: 'get', // This is the default though, you don't actually need to always mention it success: function(data) { $(myimage).attr('src', data + '?' + new Date().getTime()); }, error: function() { alert('Got an error dude in live image'); } }); } function live_state_update(){ $.ajax({ url: "{% url 'BFS:get_bfs_state_info' %}", type: 'get', // This is the default though, you don't actually need to always mention it success: function(data) { state = data document.getElementById("mystate").innerHTML = state … -
Can anyone describe this error: inconsistent use of tabs and spaces in indentation and Syntax Error [duplicate]
This is the code that but I don't know why it's showing same errors every time. if response.method == "POST": if response.POST.get("save"): for item in ls.item_set.all(): if response.POST.get("C" + str(item.id)) == "clicked": item.complete = True else: item.complete = False item.save() elif response.POST.get("newItem"): txt = response.POST.get("new") if len(txt) > 2: ls.item_set.create(text=txt, complete = False) else: print("invalid") return render(response, "main/page.html", {"ls":ls}) -
Check if matching object exist with id and manytomany field in Django
I have model as shown below : class Product(AdcBaseModel): file_id = models.CharField(max_length=256, null=True, blank=True) channels = models.ManyToManyField(Channel, blank=True) While creating a new entry in this model, I wanted to check if entry already exist with the given file_id and channels. For ex. Suppose if I have entry in the Product as (Note:channels is ManytoMany field): id file_id channels 1 ID_1 [11,12] 2 ID_2 [13,14] 2 ID_2 [15,16] Now if again I enter the values iof file_id as ID_2 and channels as [15,16]. Then it should check if this entry already exist or not. For file_id I can do something like this.: Product.objects.filter(file_id="ID_2").exists() Anything by which I can check ManytoMany field in the same way? -
How to install MySQL-python package for my Django project?
I'm unable to install MySQL-python==1.2.5 version for python-2.7.10 for my Django(Django==1.11.5) project. So far Installed C++ compiler package for python(VCForPython27) and C++ Redistributable v-14.29. I even tried pip install mysqlclient, but I got the same error. The project was completed. So, I can't use new package instead of MySQL-python. DEPRECATION: Python 2.7 reached the end of its life on January 1st, 2020. Please upgrade your Python as Python 2.7 is no longer maintained. pip 21.0 will drop support for Python 2.7 in January 2021. More details about Python 2 support in pip can be found at https://pip.pypa.io/en/latest/development/release-process/#python-2-support pip 21.0 will remove support for this functionality. Collecting MySQL-python==1.2.5 Using cached MySQL-python-1.2.5.zip (108 kB) Building wheels for collected packages: MySQL-python Building wheel for MySQL-python (setup.py) ... error ERROR: Command errored out with exit status 1: command: 'D:\Work\VirtualEnv\archiver\Scripts\python.exe' -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'c:\\users\\nsew1\\appdata\\local\\temp\\pip-install-g08uwq\\mysql-python\\setup.py'"'"'; __file__='"'"'c:\\users\\nsew1\\appdata\\local\\temp\\pip-install-g08uwq\\mysql-python\\setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' bdist_wheel -d 'c:\users\nsew1\appdata\local\temp\pip-wheel-lpqnzn' cwd: c:\users\nsew1\appdata\local\temp\pip-install-g08uwq\mysql-python\ Complete output (29 lines): running bdist_wheel running build running build_py creating build creating build\lib.win-amd64-2.7 copying _mysql_exceptions.py -> build\lib.win-amd64-2.7 creating build\lib.win-amd64-2.7\MySQLdb copying MySQLdb\__init__.py -> build\lib.win-amd64-2.7\MySQLdb copying MySQLdb\converters.py -> build\lib.win-amd64-2.7\MySQLdb copying MySQLdb\connections.py -> build\lib.win-amd64-2.7\MySQLdb copying MySQLdb\cursors.py -> build\lib.win-amd64-2.7\MySQLdb copying MySQLdb\release.py -> build\lib.win-amd64-2.7\MySQLdb copying MySQLdb\times.py -> build\lib.win-amd64-2.7\MySQLdb creating … -
Create Docker Service for Autoplotter Python Library
I want to create a docker service for Autoplotter , and want to show its output in iframe which I can later show in my django templates ? Is it possible if yes please need guideline. Thank you -
Requests_html scraper calls async in django: 'There is no current event loop in thread %r.'
I'm totally new to coding and need some advise: I'm trying to implement requests_html scraping function in my django project and when it gets to the scraping part it runs an async function and raises en error: r.html.render(keep_page=True, scrolldown=1) … self.browser = self.session.browser # Automatically create a event loop and browser … self.loop = asyncio.get_event_loop() … raise RuntimeError('There is no current event loop in thread %r.' How should I go about this to make it work? Here's the scraper code: def biltema(url): session = HTMLSession() r = session.get(url) r.html.render(keep_page=True, scrolldown=1) price = r.html.find('.price__sum') get_price = price[0].text if ',-' in get_price: l = len(get_price) price = get_price[:l-2] else: rev_price = list(get_price[::-1]) rev_price.insert(2, '.') price = "".join(rev_price) price = price[::-1] return price and here's my view: class AddNewProduct(View): def get(self, request, *args, **kwargs): form = NewProductForm() return render(request, 'add_product_form.html', {'form': form}) def post(self, request, *args, **kwargs): form = NewProductForm(request.POST) if form.is_valid(): l = form.cleaned_data['link'] s = form.cleaned_data['shop'] c = form.cleaned_data['category'] n = form.cleaned_data['name'] p = biltema(l) Products.create(name=n, category=c, price=p, link=l, shop=s) messages.info(request, 'Produkt został dodany do bazy') return redirect('/products/') else: return render(request, 'add_product_form.html', {'form': form}) -
Fill table using others tables in Django
I got three table with Table A linked to Table B and Table B linked to Table C Table A : id code name 1 GFLA2021L AC2020 2 GFLB2021A PM2015 ... Table B : id code_A code 1 GFLA2021L GFLA2021L1 2 GFLA2021L GFLA2021L2 3 GFLB2021A GFLB2021A1 Table C : id code_B number 1 GFLA2021L1 12 2 GFLA2021L2 41 3 GFLA2021A1 9 And I want a new table fill with that data for example : Table expected : id name number 1 AC2020 53 <---- 12 + 41 2 PM2015 9 But, I don't know how to do it in Django ... If someone can explain me how to create that table auto fill with data from these 3 tables for having what I except. -
django loads page very slow
I have a django template that is generating a tree view using parent and child categories. The code is slow by generating 100+ sql queries and using django-debug-toolbar showing lots of duplicates. I am working on making this more efficient, but also I would like to get some guidance. Should I use template tags to generate every category children? {% for tc in tb_terminal_categories %} {% if not tc.parent %} <li class="mt-2"> <span class="tree-span"> <a href="{% url 'terminal-management' %}?category={{ tc.category_name }}">{{ tc.category_name }}</a> <a class="tree-child" data-toggle="modal" data-target="#terminal-category-modal"><i class="fas fa-plus"></i></a> <a class="tree-child" href="{% url 'tb-terminal-category-delete' tc.id %}"><i class="far fa-trash-alt"></i></a> </span> <ul> {% for tcc in tb_terminal_categories %} {% if tcc.parent == tc %} <li> <span class="tree-span"> <a href="{% url 'terminal-management' %}?category={{ tcc.category_name }}">{{ tcc.category_name }}</a> <a class="tree-child" data-toggle="modal" data-target="#terminal-category-modal"><i class="fas fa-plus"></i></a> <a class="tree-child" href="{% url 'tb-terminal-category-delete' tcc.id %}"><i class="far fa-trash-alt"></i></a> </span> </li> {% endif %} {% endfor %} </ul> </li> {% endif %} {% endfor %} -
Set different session expiry time for different users in Django
How can I set different session expiry time for different logged-in users? The scenario can be, admin can permit certain users some time(like 4 hrs in a day) to use the application. After that time limit is over the user is logged out of the system and cannot log in again until the admin permits again. Is there any way I can implement this in Django? -
Check if password matches to the current user's password in Django
I have to check if the inputted password matches the password of the current user. class UserPasswordMatchAPIView(APIView): """ Check password """ serializer_class = UserPasswordSerializer permission_classes = [IsAuthenticated] queryset = User.objects.all() def get(self, request, *args, **kwargs): user = self.request.user password = self.request.data.get("password") if user.check_password(password): return Response(data={"message": True}) else: return Response(data={"message": False}) class UserPasswordSerializer(serializers.ModelSerializer): class Meta: model = User fields = ("password",) When I try to run this in swagger, it shows that it has no parameters required. I have to input the password. Is there any way I can execute this? -
How do I display the date on the top of chat messages in django?
I am working on a chat application but I am struggling to figure out how to display the calendar date on the top of chat messag. As example, the first image in this post is exactly what I mean link of image The date is displayed on top of a fresh new batch of text messages. I would like to do the same, just for a batch of messages related to a specific date. Say if I have messages for October 19, it shows October 19 on top followed by messages for October 20 and so on... -
Filter the Staff name and display the staff list in frontend
I am trying to filter only staff users and show the list of staff into the frontend where normal users can choose the staff name and input the price. My views file for this function is quite big, so I am sharing the gist file here https://gist.github.com/TaufiqurRahman45/104b571873531d3d119295bb3c24b4fb[View.py][1] Can anyone help me to sort out this? Thank you model.py class DailyFood(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) date = models.DateTimeField(default=now) total = models.PositiveIntegerField() class PurchaseHistory(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='histories') date = models.DateTimeField(default=now) balance = models.PositiveIntegerField() hand_cash = models.PositiveIntegerField() HTML <form action="" method="post"> {% csrf_token %} <div class="modal-body"> <div class="modal-body"> <div class="form-group"> <label>Total price</label> <input type="number" name="price" class="form-control" placeholder="Enter price"> <label>Staff</label> <!-- #show staff list here--> </div> </div> </div> <div class="modal-footer"> <button type="submit" class="btn btn-success">Submit</button> <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button> </div> </form> -
How to filter for an object that has a foreign key field that is part of a query set in Django?
I have a chat application using Django API and one operation requires that it return a list of chats associated with the person requesting the chats. The chats are of two kinds - Individual chats and group chats. Both require different approaches to determine whether that chat belongs to the person or not. These are the models:- class Group(models.Model): name = models.CharField(max_length=50) description = models.CharField(max_length=250) institution = models.ForeignKey(Institution, on_delete=models.PROTECT) avatar = models.CharField( max_length=250, blank=True, null=True, default="https://i.imgur.com/hNdMk4c.png") searchField = models.CharField(max_length=400, blank=True, null=True) # Type Choices class TypeChoices(models.TextChoices): CLASS = "CL", _('Class') TEAM = "TE", _('Team') COORDINATiON = "CO", _('Coordination') # End of Type Choices group_type = models.CharField( max_length=2, choices=TypeChoices.choices, default=TypeChoices.TEAM) admins = models.ManyToManyField(User, related_name="adminInGroups", through="GroupAdmin", through_fields=( 'group', 'admin'), blank=True) members = models.ManyToManyField( User, related_name="memberInGroups", through='GroupMember', through_fields=('group', 'member'), blank=True) active = models.BooleanField(default=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return self.name class Chat(models.Model): group = models.OneToOneField( Group, on_delete=models.CASCADE, blank=True, null=True) individual_member_one = models.ForeignKey( User, related_name="chat_member_one", on_delete=models.CASCADE, blank=True, null=True) individual_member_two = models.ForeignKey( User, related_name="chat_member_two", on_delete=models.CASCADE, blank=True, null=True) # Type Choices class TypeChoices(models.TextChoices): INDIVIDUAL = "IL", _('Individual') GROUP = "GP", _('Group') # End of Type Choices chat_type = models.CharField( max_length=2, choices=TypeChoices.choices, default=TypeChoices.INDIVIDUAL) active = models.BooleanField(default=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): … -
Seperate djnago model field to another fields
I have a field called fullname that the data in it, is something like this first_name:Gholi;last_name:Sezavar Poor Asl Esfahani I want to seperate it first_name and last_name to seperated fields name first_name & last_name my models.py now is this: from django.db import models class Person(models.Model): fullname = models.CharField(max_length=250, null=True) information = models.CharField(max_length=350, null=True) first_name = models.CharField(max_length=30, null=True) last_name = models.CharField(max_length=50, null=True) id_code = models.CharField(max_length=10, null=True) born_in = models.CharField(max_length=30, null=True) birth_year = models.PositiveIntegerField(null=True) and I want to make custom migration for it and using annotate method or something else. How can I do this ??? -
Cron jobs show but are not executed in dockerized Django app
I have "django_crontab" in my installed apps. I have a cron job configured CRONJOBS = [ ('* * * * *', 'django.core.management.call_command',['dbbackup']), ] my YAML looks like this: web: build: . command: - /bin/bash - -c - | python manage.py migrate python manage.py crontab add python manage.py runserver 0.0.0.0:8000 build + up then I open the CLI: $ python manage.py crontab show Currently active jobs in crontab: efa8dfc6d4b0cf6963932a5dc3726b23 -> ('* * * * *', 'django.core.management.call_command', ['dbbackup']) Then I try that: $ python manage.py crontab run efa8dfc6d4b0cf6963932a5dc3726b23 Backing Up Database: postgres Writing file to default-858b61d9ccb6-2021-07-05-084119.psql All good, but the cronjob never gets executed. I don't new database dumps every minute as expected. -
Copy of a Slice from a DataFrame issue while running the script in Django
I am trying to apply multiple user-defined functions to a column of a dataframe one by one. This is the error it is giving me when I ran it in Django env. (.py3env) [root@---------]# python report_feedback_attribute.py runserver feedback_attribute.py:89: SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame. Try using .loc[row_indexer,col_indexer] = value instead See the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy data1['feedback_text'] = data1['feedback_text'].apply(clean_text) # the feedback_text column has been cleaned feedback_attribute.py:93: SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame. Try using .loc[row_indexer,col_indexer] = value instead See the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy data1['feedback_text'] = data1['feedback_text'].astype(str) feedback_attribute.py:103: SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame. Try using .loc[row_indexer,col_indexer] = value instead See the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy data1['feedback_text'] = data1['feedback_text'].apply(lambda x: tokenizer.tokenize(x.lower())) It is returning an empty dictionary. {'count': []} I have already tried creating a copy of my dataframe and then working on it. Still no result. I have also tried applying .loc in this way: data1.loc[:, 'feedback_text'] = data1['feedback_text'].apply(clean_text) (I did this change for every function that I defined and applied on … -
Django - query an existing database with no keys
New to Django. I have a database that I am connecting to using the multiple database configurations. There are no keys on the tables and I cannot change them. Lets say the tables are Orders and Customers and data can be returned by SQL: SELECT Orders.OrderID, Customers.CustomerName, Orders.OrderDate FROM Orders INNER JOIN Customers ON Orders.CustomerID=Customers.CustomerID; What is the best approach in Django to query tables where I need to specify a join? -
Django admin can add data but not user from site
hello friends i am not able to add user data in my database but i am able to do it in admin panel and there is no error plz help.there is no error can someone help view.py from django.shortcuts import render from keshavapp.models import Register # Create your views here. def index(request): return render(request,"index.html") def register(request): return render(request,"register.html") def connect(request): if request.method =="POST": fname=request.POST.get('fname') lname=request.POST.get('lname') email=request.POST.get('email') password=request.POST.get('password') address=request.POST.get('address') city=request.POST.get('city') state=request.POST.get('state') zip=request.POST.get('zip') connect=Register(fname=fname,lname=lname,email=email ,password=password,address=address ,city=city,state=state,zip=zip) connect.save() model.py- from django.db import models Create your models here. class Register(models.Model): fname = models.CharField(max_length=120) lname = models.CharField(max_length=120) email = models.CharField(max_length=120) password = models.CharField(max_length=20) address = models.CharField(max_length=120) city = models.CharField(max_length=120) state = models.CharField(max_length=120) zip = models.CharField(max_length=12) it display name in data base self.name def __str__(self): return self.fname -
NoReverseMatch at /home/ Reverse for 'detail' with arguments '(1, '')' not found. 1 pattern(s) tried: ['(?P<id>[0-9]+)/(?P<slug>[^/]+)/$']
I'm a newcomer in Django. I'm unable to point out exactly what's wrong. I get this error views.py class DetailPost(DetailView): model = Post template_name = 'blog/PostDetail.html' slug_field = 'slug' slug_url_kwarg = 'MySlug' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['post'] = Post.objects.filter(id=kwargs['id'], slug=kwargs['MySlug']) post = context['post'] context['comments'] = Comment.objects.filter(post=post).order_by('create_date__hour') return context urls.py urlpatterns = [ . . path('home/', Home.as_view(), name='Home'), path('<int:id>/<str:slug>/', DetailPost.as_view(), name='detail'), ] home.html <div id="latestp"> {% for item in newposts %} <article> <h1>{{ item.title }}</h1> {% if item.images.image1.url %} <img src="{{ item.images.image1.url }}" class="responsive-image" alt="Smiley face" title={{ item.description }}/> {% else %} <img src="{% static 'img/noimage.png' %}" class="responsive-image" alt="Null" title={{ item.description }}/> {% endif %} <p>{{ item.description|truncatewords:50 }}</p> <a href="{% url 'blog:detail' item.id item.slug %}" class="rm">Read More</a> </article> {% endfor %} </div> what's the matter? is my wrong in HTML code in a tag? -
Inlines for indirectly related models
I'd like to add an inline in the admin for two indirectly related models, more precisely, I wish to generate inlines for foreign keys to the same model. class Order(model.Model): ... class OrderAddress(models.Model): order = models.ForeignKey(Order, on_delete=models.PROTECT) class VendorOrder(models.Model): order = models.ForeignKey(Order, on_delete=models.PROTECT) What i want @admin.register(VendorOrder) class VendorOrderAdmin(admin.ModelAdmin): ... inlines = (OrderAddressInline, ) ... The closest I've come is django-nested-admin but that is used for nesting inline within inlines and not for sibling FKs. Can you point in the right direction on how to solve this?