Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Diaz Canel Singao
I have these problem, I need to generate a col-md-4 from Django-Admin, the trouble is that I want to show other col-md-4 just if the previous col-md-4 get 10 items. Please help me, is my tesis <div class="col-lg-4"> <div class="single-price" style="border-radius: 8px;"> <ul class="price-list"> {% for doc in Documento %} {% if 10 >= forloop.counter %} <li class="d-flex align-items-center"><a href="{{ doc.documento.url }}" download="" target="_blank" rel="noopener noreferrer"> <img src="{{ doc.ícono.url }}" alt="" style="width: 40px; margin-right: 10px;"> </a> <span style="text-align: left;">{{ doc.nombre }}</span> <!-- <a href="/static/descargables/Ctto-Marco-MAR-2022-.docx" download="true" class="price-btn">Descargar</a> --> </li> {% endif %} {% endfor %} </ul> </div> </div> {% endfor %} -
clone django model with copy function
I have a model and I want to copy all of my data when copy function called and it make a copy of my books with new datetime I wrote this: class Book(models.Model): name = models.CharField(max_length=255) created_date = models.DateTimeField(auto_now_add=True) author = models.ForeignKey('Author', on_delete=models.CASCADE) def copy(self): new_book = Book() new_book.name = self.name new_book.created_date = models.DateTimeField(auto_now_add=True) new_book.author = self.author new_book.save() class Author(models.Model): name = models.CharField(max_length=255) but author won't copied well -
Resolve UUID to DangoObjectNode in Subquery
I've got a database with an simple Employee model and node in Django. I´m using Graphene to create an API around this that allows a user to retrieve the right data. class Employee(models.Model): id = models.UUIDField(primary_key=True, unique=True, ) name = models.CharField(max_length=128) class EmployeeNode(DjangoObjectType): class Meta: model = Employee fields = "__all__" interfaces = (graphene.relay.Node, ) Now in addition to this, I have a query that finds a "buddy" for every Employee, which is another Employee (ID) in the database, and a function (details irrelevant here) that finds the correct "buddy" in the database using some not further specified Django query. class EmployeeNodeWithBuddy(DjangoObjectType): buddy_id = graphene.UUID() class Meta: model = Employee fields = "__all__" interfaces = (graphene.relay.Node, ) @classmethod def get_queryset(cls, queryset, info): set_with_buddy_annotation = queryset.annotate( buddy_id=ExpressionWrapper(Subquery( ### Omitting the details of this query ### ).only('id')[:1], output_field=models.UUIDField() ), output_field=models.UUIDField()) ) return set_with_buddy_annotation This works ok, but what I actually want is not the ID of the buddy, but the actual EmployeeNode. I can´t figure out if there is a good way to annotate/add info to this query to make it return the thing I want. It would look like: class EmployeeNodeWithBuddy(DjangoObjectType): buddy_id = graphene.UUID() buddy = graphene.Field(EmployeeNode) # Field with EmployeeNode … -
Django - i cant migrate my model "prestamo"
this is my model https://i.stack.imgur.com/XqonC.jpg} and this is my error https://i.stack.imgur.com/qVa5M.jpg i dont know how to solve it -
Nginx 502 gateway error with AWS RDS Aurora, Django, and Daphne
I am trying to run an open source cloud project described here. I want to use an AWS RDS Aurora instance, instead of the project's default database, so I followed their instructions to do that here. However, when I reload the server: bash ~/cloud_station_deployment/reload_server.sh and go to my website's URL, I get a 502 Bad Gateway error with Nginx: How should I solve this error? This is what I tried to find the cause of the problem: sudo systemctl status nginx output: ● nginx.service - A high performance web server and a reverse proxy server Loaded: loaded (/lib/systemd/system/nginx.service; enabled; vendor preset: enabled) Active: active (running) since Fri 2022-09-30 19:32:21 UTC; 2h 23min ago Docs: man:nginx(8) Main PID: 2532 (nginx) Tasks: 2 (limit: 1140) CGroup: /system.slice/nginx.service ├─2532 nginx: master process /usr/sbin/nginx -g daemon on; master_process on; └─3174 nginx: worker process Sep 30 19:32:20 ip-172-31-83-16 systemd[1]: Stopped A high performance web server and a reverse proxy server. Sep 30 19:32:20 ip-172-31-83-16 systemd[1]: Starting A high performance web server and a reverse proxy server... Sep 30 19:32:21 ip-172-31-83-16 systemd[1]: nginx.service: Failed to parse PID from file /run/nginx.pid: Invalid argument Sep 30 19:32:21 ip-172-31-83-16 systemd[1]: Started A high performance web server and a reverse … -
Why is my JavaScript function adding increasingly more rows?
I have a document with many buttons, all of which contain onclick="myFunction()" inside the button tag. When I click the 1st button, 1 row is added to my table, as desired. However, as I click the 2nd button, 2 rows are added to my table, and so on, i.e. i rows are added on the ith button click. How can I fix my JavaScript function to only add 1 row for each new button click? function myFunction() { table_body = document.getElementById("t_body"); document.addEventListener('click', (e) => { let element = e.target; if(element.tagName == "BUTTON") { row = table_body.insertRow() cell1 = row.insertCell(); cell1.innerHTML = element; cell2 = row.insertCell(); cell2.innerHTML = element.id; cell3 = row.insertCell(); cell3.innerHTML = element.id; cell4 = row.insertCell(); cell4.innerHTML = element.id; element.style.backgroundColor = '#004d00'; element.style.color = 'white'; } }); } -
How update the CheckboxSelectMultiple from django in html
I was using this tutorial in my code, to have an update page in my work, but I'm having a hard time showing the information of a CheckboxSelectMultiple on this update page. How do I do this? -
Django POST method is not receiving all input fields from HTML
please I would like to ask for help. I'm creating a web-based application and I'm having a hard time when I try to get the data from the HTML form and receive it through the POST method in Django. It's pulling data only from one field and I really appreciate your help in figuring out why it's not pulling information from the other fields only from the location field. Thank you very much! HTML = create-request.html <form action="{% url 'save_request' %}" id="checklistForm" name="checklistForm" enctype="multipart/form-data" method="POST"> {% csrf_token %} <section id="step-1" class="form-step"> <div class="mt-3"> {% include 'home/1_resource-request.html' %} </div> </section> </form> HTML = home/1_resource-request.html {% block stylesheets %}{% endblock stylesheets %} {% block content %} <div class="pcoded-content"> <div class="pcoded-inner-content"> <div class="main-body"> <div class="page-wrapper"> <div class="row"> <div class="col-sm-12"> <div class="card"> <div class="card-header"> <h5>Resource Request</h5> </div> <div class="card-body"> <div class="row"> <div class="col-md-6"> <form> <div class="form-group"> <label for="checklistID">Checklist Number</label> <input type="text" class="form-control" id="checklistID" name="checklistnum" placeholder="123456" disabled/> </div> <div class="form-group"> <label for="location_ID">CMPA Location</label> <select class="form-control" id="location_ID" name="location"> <option selected>Select</option> <option>Brazil</option> <option>Canada</option> <option>Mexico</option> <option>SSA</option> <option>United States</option> </select> </div> </form> </div> <div class="col-md-6"> <form> <div class="form-group"> <label for="support_id">CMPA Support Needed</label> <select class="form-control" id="support_id" name="support"> <option selected>Select</option> <option>Both</option> <option>PMA - Financial Management</option> <option>PMO - Project Administration</option> </select> </div> … -
Django: prefetch_related in nested serializers does not reduce thousands of db queries, and can even introduce more
I have a strange situation. I've done so much reading on avoiding the N+1 problem and have tried prefetching but to no avail. My setup is like this: Models: class A(models.Model): # some stuff class B(models.Model): a = models.ForeignKey(A, on_delete=models.CASCADE, related_name="b_objs") class C(models.Model): somefield1 = models.CharField(max_length=100) somefield2 = models.CharField(max_length=100) # Assume that classes Y and Z exist. We don't care about them. # In the serializer, the fields don't include 'y' and 'z' y = models.ForeignKey(Y, on_delete=models.CASCADE) z = models.ForeignKey(Z, on_delete=models.CASCADE) class D(models.Model) b = models.ForeignKey(B, on_delete=models.CASCADE, related_name="d_objs") c = models.ForeignKey(C, on_delete=models.CASCADE) Visually: D --> B --> A D --> C --> Y and Z (Again, we don't care about C's FKs to Y and Z) There is 1 A object, 8 B objects pointing to A, 188 C objects, and 1291 D objects pointing to some combination of those 8 Bs and 188 Cs. When I serialize an A object, it propagates down and serializes all of these objects. The serializers are like so: class CSerializer(serializers.ModelSerializer): class Meta: model = C fields = ['somefield1', 'somefield1'] class DSerializer(serializers.ModelSerializer): c = CSerializer() class Meta: model = D fields = '__all__' class BSerializer(serializers.ModelSerializer): d_objects = serializers.SerializerMethodField(method_name='get_d_objects') class Meta: model = B fields … -
Django No Module Named... when calling a function in another folder
I have a Django application and in my views.py file I am trying to call a function that is located in another file in another folder, still in the same app. My folder structure looks like: .administraion ├── background_tasks │ ├── magic_update_set.py ├── migrations │ ├── __init__.py ├── __init__.py ├── admin.py ├── config.py ├── models.py ├── tests.pu ├── urls.py └── views.py In the magic_update_set.py file I have the following function: def magic_set_update_bg_task(options): ... In my vioews.py I have: from background_tasks.magic_update_set import magic_set_update_bg_task ... def update_magic_set_function_queue(request): options = { 'code': request.POST['code'], } magic_set_update_bg_task(options, verbose_name='Set Update') return HttpResponse(status=200) Error: Traceback (most recent call last): File "C:\Users\rossw\Documents\Projects\card_companion\manage.py", line 22, in <module> main() File "C:\Users\rossw\Documents\Projects\card_companion\manage.py", line 19, in main execute_from_command_line(sys.argv) File "C:\Users\rossw\Documents\Projects\card_companion\card_companion_venv\lib\site-packages\django\core\management\__init__.py", line 419, in execute_from_command_line utility.execute() File "C:\Users\rossw\Documents\Projects\card_companion\card_companion_venv\lib\site-packages\django\core\management\__init__.py", line 413, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\rossw\Documents\Projects\card_companion\card_companion_venv\lib\site-packages\django\core\management\base.py", line 354, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\rossw\Documents\Projects\card_companion\card_companion_venv\lib\site-packages\django\core\management\base.py", line 393, in execute self.check() File "C:\Users\rossw\Documents\Projects\card_companion\card_companion_venv\lib\site-packages\django\core\management\base.py", line 419, in check all_issues = checks.run_checks( File "C:\Users\rossw\Documents\Projects\card_companion\card_companion_venv\lib\site-packages\django\core\checks\registry.py", line 76, in run_checks new_errors = check(app_configs=app_configs, databases=databases) File "C:\Users\rossw\Documents\Projects\card_companion\card_companion_venv\lib\site-packages\django\core\checks\urls.py", line 13, in check_url_config return check_resolver(resolver) File "C:\Users\rossw\Documents\Projects\card_companion\card_companion_venv\lib\site-packages\django\core\checks\urls.py", line 23, in check_resolver return check_method() File "C:\Users\rossw\Documents\Projects\card_companion\card_companion_venv\lib\site-packages\django\urls\resolvers.py", line 416, in check for pattern in self.url_patterns: File "C:\Users\rossw\Documents\Projects\card_companion\card_companion_venv\lib\site-packages\django\utils\functional.py", line 48, in __get__ res = instance.__dict__[self.name] = … -
Django, sqlite in memory in production
I did this in settings.py 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3' }, 'in_memory_db': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': ":memory:" } I have a small amount of data that I would like to store in a database in memory, but I have a problem. Everything works well in the default database, but in "in memory" it is not possible to save any record, the error `no such table comes out. As a result, I don't quite understand how to work with such a database, it seems to me that it is deleted after the migration. How to work with it, handle it? What are your ideas? I just need to migrate one table, write data there, then read and delete them as in the default database. -
Django ListView: how to show few entry and protect the other
I have a model with few entries. I'd like to show only few of them and protect the others... example: class Squadra(models.Model): ... tipo = models.IntegerField(choices=TIPO_SQUADRA, default=1) ... Then I have a ListView which return only few Squadra objects using a filter: all_squadre = Squadra.objects.filter(tipo=3) and a url file including this: path('squadra_table/<int:squadra>/', views.SquadraTableListView.as_view() ), My problem is that someone could get to the Squadra page and then he could try to change randomly the ID <int:squadra> in the url and access other entries which I'd like to keep protected... How can I do that? Thanks for helping Attilio -
Removing data in a Django Template Forloop
I have a for loop in a Django Project as following: {% for i in active_session.log.values %} {% if i.log_order == b.order and i.log_exercise == e.name %} <button type="submit" id="submitlog" class="......"> <i class="fa-solid fa-check"></i> </button> {% else %} <button type="submit" id="submitlog" class="......"> <i class="fa-solid fa-x"></i> </button> {% endif %} {% endfor %} This is the current outcome: My question: How can I get rid of the X in the and only keep the check buttons I have tried the following but did not work: {% if active_session.log.log_order == b.order and active_session.log.log_exercise == e.name %} this is the required outcome: -
Django how to check if a table is being used as a foreignkey of another table
So, I have two models, Order and Orders, and for each item that I have in my session(cart) Im creating an Order_object(saving in database) and after each item is saved I want to do a check for every Order telling which ones are not a foreign key in Orders, if not, create an Orders_object than add each Order who is not a foreign key of Orders And I wish that each Orders have multiple Order Models.py class Order(models.Model): ----fields--- class Orders(models.Model): order = models.ManyToManyField(Order) ----other fields ------ I want to dosomething like this but I dont know if it will work, can somebody confirm if this works?: Note: even if this code that I wish to test works, im not adding multiple Order_object in Orders_object, im just creating an Orders_object containing only one Order_object for order_object in Order: check_if_doesnt_have_foreign_key = True for orders in Orders: if orders.order == order_object check_if_doesnt_have_foreign_key = False break: if check_if_doesnt_have_foreign_key == True: orders = Orders(order=order_object) orders.save() -
Django ModelViewSet returning full HTML 500 error on duplicate field set to unique=true
I have been trying to fix this all morning but can't seem to find the issue. I have a specific API returning an IntegrityError duplicate key error in the form of the Django HTML error traceback instead of returning a detail error on the form field. Exception Type: IntegrityError at /api/chats/ Exception Value: duplicate key value violates unique constraint "chats_chat_title_853c3234_uniq" DETAIL: Key (title)=(New Chat) already exists. Model with a title field set to unique: class Chat(TimestampedModel): """ A chat between multiple users. """ uuid = models.UUIDField(default=uuid4, null=False) title = models.CharField( max_length=255, null=False, unique=True, blank=False) Serializer for the chat: class ChatSerializer(serializers.ModelSerializer): title = serializers.CharField(max_length=255) def create(self, validated_data): """ Creates a new Chat and adds the m2m employees to it """ user = self.context['request'].user title = validated_data['title'] # Add the user to the chat employee_ids = validated_data.pop("employee_ids") employee_ids.append(user.id) # Create and save the chat # Add the employees to the chat # Add the sender to the chat chat = Chat.objects.create(created_by=user, title=title) chat.employees.set(employee_ids) chat.employees.add(user) chat.save() return chat And the ViewSet: class ChatViewSet(MixedPermissionModelViewSet): lookup_field = 'uuid' queryset = Chat.objects.all() serializer_class = ChatSerializer permission_classes_by_action = { 'list': [IsAuthenticated], 'create': [IsAuthenticated], 'update': [IsAuthenticated], 'retrieve': [IsAuthenticated], 'partial_update': [IsAuthenticated], 'destroy': [IsAuthenticated] } def add_user_has_viewed(self, chat): if self.request.user … -
Inserting POINT Geometry from DJANGO to POSTGIS database error
Hello I try to use DJANGO to insert point clicked on Leaflet in a POSTGIS database. During the import I receive the following error : "function st_geomfromewkb(bytea) does not exist" My understanding is that the ST_GeomFromEWKB is used to insert binary representation od geometry, and this is quite weird here because what I intend to do is inserting a wkb object. my view is defined as bellow: from django.contrib.gis.geos import Point def add_site(request): if(request.method == 'POST'): site_name = request.POST.get('site_name') customer_name = request.POST.get('customer_name') lat = str(request.POST.get('lat')) lng = str(request.POST.get('lng')) point = Point(lng,lat,srid=4326).wkb logger.info(type(point)) insert = customers_sites(site_name=site_name,customer_name=customer_name,geom=point) insert.save() Any idea of what is wrong here ?? Thank you for your help ! -
Grouping django "choices" dropdowns with ForeignKey?
I have a "delivery website" and I want to give it some styling. The order statuses are listed like this: ORDER_STATUS = ( ('Incoming',( ('PENDING', 'Pending'), )), ('Delivery',( ('OFD', 'Out for Delivery'), )), ('Finished',( ('CAN','Cancelled'), ('FIN','Delivered'), )) ) which, if you pass it to the "choices" for a charfield, makes a good looking grouped dropdown to select from. Is it possible to do the same, but with other Models(/classes)? I was thinking making a "TopStatus" and a "SubStatus" model, so I can give a "TopStatus" to every "SubStatus" (e.g. top status: 'incoming', sub status: 'pending'), but I have no idea on how I could nest these to look like the tuple above. If there's something similar in the original documentation, I'm sorry for missing that part! -
Sorting of search result items
How can I sort the search result so that when sorting by price, the program does not sort all the elements, but only the search result? (in views.py(#sort by price) I implemented price sorting, but it sorts all the items) views.py def filters(request): #search search_post = request.GET.get('search') if search_post: all = Product.objects.filter(Q(title__icontains=search_post) & Q(content__icontains=search_post)) else: all = Product.objects.all() #sort by price sort_by = request.GET.get("sort", "l2h") if sort_by == "l2h": all = Product.objects.all().order_by("price") elif sort_by == "h2l": all = Product.objects.all().order_by("-price") filters = IndexFilter(request.GET, queryset=all) context = { 'filters': filters } return render(request, 'index.html', context) filters.py import django_filters from .models import * class IndexFilter(django_filters.FilterSet): class Meta: model = Product fields = {'brand'} models.py class Product(models.Model): BRAND = [ ('apple', 'apple'), ('samsung', 'samsung'), ('huawei', 'huawei'), ('nokia', 'nokia'), ] img = models.URLField(default='https://omsk.imperiya-pola.ru/img/nophoto.jpg') title = models.CharField(max_length=80) brand = models.CharField(max_length=20, choices=BRAND) content = models.TextField() price = models.FloatField(default=1.0) def __str__(self): return self.title -
Why does a django gunicorn process call import on first API request?
Noticed if I do a print statement on a global level in the django level, it'll be called on the first API request, is there a way to run all global declarations before the first API? -
How to save MultipleChoiceField data using Django ModelForm
I'm trying to save data from a ModelForm that has MultipleChoiceFields. I want the user to be able to select multiple timeframes and have that data saved to the database. So far, when submitting the form using the MultipleChoiceField, I get nothing returned. Here's my models.py: class InfoFormModel(models.Model): YES_NO = ( ('yes', 'Yes'), ('no', 'No'), ) TIMEFRAME = ( ('1_weeks', '1 Week'), ('2_weeks', '2 Weeks'), ('3_weeks', '3 Weeks'), ('4_weeks_plus', '4 Weeks+'), ) PAGES_NEEDED = ( ('about_page', 'About Page'), ('contact_page', 'Contact Page'), ('blog_page', 'Blog Page'), ('map_page', 'Map Page'), ('ecommerce_page', 'Ecommerce Page'), ) brand_name = models.CharField( blank=False, null=False, max_length=500, default='') logo = models.CharField(choices=YES_NO, blank=False, null=False, max_length=500, default='no') what_is_the_service = models.TextField( blank=False, null=False, max_length=5000, default='') contact_number = models.BigIntegerField(blank=True, null=True, default='') email = models.EmailField(blank=True, null=True, max_length=300, default='') timeframe = models.CharField( choices=TIMEFRAME, max_length=100, blank=False, null=False, default='') aim = models.TextField(blank=False, null=False, max_length=5000, default='') products_product_images = models.CharField( choices=YES_NO, blank=False, max_length=500, null=False, default='') products_info = models.CharField( choices=YES_NO, blank=False, null=False, max_length=500, default='') pages_needed = models.CharField( choices=PAGES_NEEDED, blank=True, null=True, max_length=500, default='') def __str__(self): return self.brand_name forms.py: class InfoForm(forms.ModelForm): YES_NO = ( ('yes', 'Yes'), ('no', 'No'), ) TIMEFRAME = ( ('1_weeks', '1 Week'), ('2_weeks', '2 Weeks'), ('3_weeks', '3 Weeks'), ('4_weeks_plus', '4 Weeks+'), ) PAGES_NEEDED = ( ('about_page', 'About Page'), ('contact_page', 'Contact … -
Use request.session as the success_url in django
I have a CBV that I need to pass a request.session variable to as the success_url. I have not been able to implement this. May somebody help, please. class UpdateTeacherIssueView(LoginRequiredMixin,UpdateView): model = TeacherIssue form_class = UpdateTeacherIssueForm template_name = 'crud_forms/edit_teacher_issue.html' success_url =reverse_lazy('all', path = selected_item>) In function based views it would be, selected_item = request.session.get('item') How is the same possible in CBV? -
django-rest-knox - how to authenticate token for email verification?
I am trying to set-up email verification using django-rest-knox. The link is being sent out. When I use the following: from knox.auth import TokenAuthentication class VerifyEmailAPI(generics.GenericAPIView): def get(self, request): # Get the token from request # token = request.GET.get('token') # print(token) user = TokenAuthentication.authenticate(request, self) print(user) return Response({'message': 'Just testing for now'}) The url: http://127.0.0.1:8000/api/auth/email-verify/?token=58cab01ad07801dbe5e6c4fc5c6c7ef060bf7912cb723dc70e4c5fb677fbbf1e I get this error: AttributeError: 'VerifyEmailAPI' object has no attribute 'META' Complete traceback: Traceback (most recent call last): File "/Users/sid/eb-virt/lib/python3.8/site-packages/django/core/handlers/exception.py", line 55, in inner response = get_response(request) File "/Users/sid/eb-virt/lib/python3.8/site-packages/django/core/handlers/base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Users/sid/eb-virt/lib/python3.8/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "/Users/sid/eb-virt/lib/python3.8/site-packages/django/views/generic/base.py", line 84, in view return self.dispatch(request, *args, **kwargs) File "/Users/sid/eb-virt/lib/python3.8/site-packages/rest_framework/views.py", line 509, in dispatch response = self.handle_exception(exc) File "/Users/sid/eb-virt/lib/python3.8/site-packages/rest_framework/views.py", line 469, in handle_exception self.raise_uncaught_exception(exc) File "/Users/sid/eb-virt/lib/python3.8/site-packages/rest_framework/views.py", line 480, in raise_uncaught_exception raise exc File "/Users/sid/eb-virt/lib/python3.8/site-packages/rest_framework/views.py", line 506, in dispatch response = handler(request, *args, **kwargs) File "/Volumes/coding/fort_dev/accounts/api.py", line 75, in get user = TokenAuthentication.authenticate(request, self) File "/Users/sid/eb-virt/lib/python3.8/site-packages/knox/auth.py", line 37, in authenticate auth = get_authorization_header(request).split() File "/Users/sid/eb-virt/lib/python3.8/site-packages/rest_framework/authentication.py", line 20, in get_authorization_header auth = request.META.get('HTTP_AUTHORIZATION', b'') AttributeError: 'VerifyEmailAPI' object has no attribute 'META' Am I doing something fundamentally wrong when using the django-rest-knox function? -
How to fetch data remotely for displaying into admin/index.html in django adminlte v3
I want to make api call and show data into django adminLTE home page. How can I achieve it? -
How to implement OneToTwo relation in django?
I want to implement a case where model A has exactly two B instances and model B has exactly one A instance. What is the best way to implement this? class A(Model): b1 = OneToOneField(B) b2 = OneToOneField(B) If I use this I have to provide two different related names to b1 and b2 fields. I want be able to simply say b.a_set.first() and get the object since I want B to have single A. And this is not really oneToTwo I think, b1 and b2 could point to the same B object. class B(Model): a = ForeignKey(A) If I use this then it is OneToMany, I want to be explicit about relation, and be able to use a.b1 and a.b2 What would be a good way to implement this? -
how to escape stretched-link in html block content
I am developing an app with Django and using bootstrap for the front end. Do you know how I can a "escape" a stretched-link in bootstrap ? In fact I like the behavior of having the total card being the link but the problem is that inside the card I have some tag that I want to be as link but it is like my stretched-link is covering all links in the card. Below is the snippet from bootstrap adapted to my needs <div class="row gx-5"> {% for post in post_list %} <div class="col-lg-4 mb-5"> <div class="card h-100 shadow border-0"> <img class="card-img-top" src="https://dummyimage.com/600x350/6c757d/343a40" alt="..." /> <div class="card-body p-4"> <a class="text-decoration-none link-dark stretched-link" href="{% url 'post-detail' post.id %}"><div class="h5 card-title mb-3">{{post.title}}</div></a> <p class="card-text mb-0">{{post.content}}</p> </div> <div class="card-footer p-4 pt-0 bg-transparent border-top-0"> <div class="d-flex align-items-end justify-content-between"> <div class="d-flex align-items-center"> <div class="small"> {% for tag in post.tag.all %} <a class="badge bg-secondary text-decoration-none link-light" href="{% url 'blog-index-tag' tag.tag_name %}">{{tag}}</a> {% endfor %} <div class="text-muted">April 2, 2022</div> </div> </div> </div> </div> </div> </div> {% endfor %} </div>