Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
DRF serializer validation - discard failed items, keep successful ones?
I have an endpoint (POST, APIView) which expects larger chunks of data that needs to be validated using serializers. However, for many reasons there are times where I'd like to discard a few of them that fail validation. The rest, I still want to add. E.g I'd like to run : serializer = ListingSerializer(data=request.data, many=True) if serializer.is_valid(): serializer.save() Lets say we have a table of listings which has a foreign key to a company table. Therefore I have a nested company serializer as a field. A company only has a name. In order to save some performance I fetch all companies in the init method so is_valid() only makes one query (similar to a select_related). The problem here is that if a single company did not exist, the entire is_valid() will fail and thus I cant run serializer.save(). Is there any elegant way to solve this by discarding the individual items that fail is_valid() so that I can run serializer.save()? class CompanyStringSerializer(serializers.ModelSerializer): class Meta: model = Company fields = ("name",) class ListingSerializer(): company = CompanyStringSerializer() def __init__(self, *args, **kwargs): """ This is executed when the serializer initializes (meaning the query will only run once) """ self.companies = Company.objects.filter(enabled=True) super().__init__(*args, **kwargs) … -
Get current Logged in User in django Rest Framework
I am trying to get current logged in user and upload/send information to frontend. I am new to Rest Framework so forgive my basic level question. I have tried fetching user with request.user and request.auth in my views but I am not able to simply get user. This is my views.py from rest_framework.authtoken.models import Token def get_User (request): # current_user = request.user # context = {"user": current_user} # print(request.user.username) user_id = Token.objects.get(key=request.auth.key).user_id print(request.auth) # Response(context) I am using a custom user model to store data. Every time I am running request.auth or request.user i can see in my django terminal that it keeps going to /verify-auth-token/ URL. How do I get user printed also sent to frontend in React to display in app as well. Any help is appreciated. -
Disable has_changed check in django form
When an entry is saved in results list in django admin site I need it to end up in save_model regardless of whether it has changes or not. With default behaviour it will just present the same page if there are no changes. What is the canonical way of disabling it? Currently I came up with this quick and dirty snippet. It works, but I suspect it's ugly:) def get_changelist_form(self, request, **kwargs): res=super().get_changelist_form(request, **kwargs) # Ugly? res.has_changed=lambda *args, **kwargs: True return res -
Celery beat not resuming scheduled tasks django
I have used celery & django celery beat to run a predefined scheduled task. When I first run celery worker & then celery beat worker, everything is fine, the task is added to database, and also sent to queue by celery beat worker continuously. But when I stop beat worker and start it again, it no longer works, even though the task is defined in database. What should I do? This is my code for django: # Set the default Django settings module for the 'celery' program. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'proj.settings') app = Celery('proj') # Using a string here means the worker doesn't have to serialize # the configuration object to child processes. # - namespace='CELERY' means all celery-related configuration keys # should have a `CELERY_` prefix. app.config_from_object('django.conf:settings', namespace='CELERY') # Load task modules from all registered Django apps. app.autodiscover_tasks() @app.task def test(arg): print(arg) @app.on_after_configure.connect def setup_periodic_tasks(sender, **kwargs): # Calls test('hello') every 10 seconds. sender.add_periodic_task(10.0, test.s('hello'), name='say hello every 10 secs') app.conf.beat_schedule = { 'add-every-12-seconds': { 'task': 'tasks.test', 'schedule': 12.0, # 'args': () }, } and this is how I start celery worker & beat worker: celery -A proj worker -l info celery -A proj beat -l INFO --scheduler django_celery_beat.schedulers:DatabaseScheduler Would appreciate a … -
Access django database on postgresql from independent python script
I have a website built with django and postgresql. each user (user in django Auth system) on the website have many account models (and other models) . An app running on windows-python based need to access (read/write) data from the database. Each app is associated with a specific user. my questions: can an app access only specific user data? the account model have an attribute of user so it filter based on that, how can it restrict external app access? what is the proper way to read / write from database? can I somehow use the django models as the website do? -
Getting systemd to use user ENV configs
I am trying to create an LXC container to run a specific Django Application automatically at start. The issue I am having is that getting the Django side of things starting up with systemd was fairly easy, however the application checks ENV variables as well as relies on some Ruby Gems to function. The LXC Template is based on Debian 11. Due to the specific requirements, I run pyenv and rbenv to manage the installed versions for the specific user (django for the purposes of this example). I can get systemd to start the Gunicorn server well enough, but am having an issue that it seems to not pull ENV variables (Not sure yet), nor does it get access to the required Ruby Gems (Confirmed). My gunicorn.service file looks like this: [Unit] Description=Start Gunicorn to run Django App After=network.target [Service] Type=notify # the specific user that our service will run as User=django Group=django RuntimeDirectory=/home/django/.pyenv/shims WorkingDirectory=/home/django/application ExecStartPre=/home/django/.pyenv/shims/python /home/django/app/manage.py migrate ExecStart=/home/django/.pyenv/shims/gunicorn --chdir /home/django/app app.wsgi:application -k=gevent -t 600 --certfile=/home/django/app/server.crt --keyfile=/home/django/app/server.key -b=0.0.0.0:8000 -w=4 --forwarded-allow-ips=* --proxy-allow-from=* ExecReload=/bin/kill -s HUP $MAINPID KillMode=mixed TimeoutStopSec=5 PrivateTmp=true [Install] WantedBy=multi-user.target How can I get systemd to run the gunicorn.service wherein the ENV variables specified in home/django/.bashrc will be honored, and … -
get 2 objects in updateview django
I have have a template where i want to make update on 2 different models, the first one is the order model , and teh second is the customer model. In the template i've got the 2 forms, but the problem is that i cant get informations about the customer in the customer form models.py class Customer(models.Model): full_name = models.CharField(max_length=150) address = models.CharField(max_length=1500, null=True) phone = models.CharField(max_length=20) city = models.CharField(max_length=100) email = models.EmailField(null=True) def __str__(self): return self.full_name class Order (models.Model): product = models.ManyToManyField(Product, through='OrderProduct') customer = models.ForeignKey(Customer, on_delete=models.CASCADE,) quantity = models.IntegerField(default=1) status = models.TextField(choices=ORDER_STATUS, default='Pending') def __str__(self): return 'Order n°: ' + str(self.id) views.py class OrderUpdateView(LoginRequiredMixin, RedirectToPreviousMixin, UpdateView): model = Order form_class = OrderManageForm second_form_class = CustomerForm template_name = 'dashboard/order_details.html' login_url = '/login/' def get_object(self): return Order.objects.get(id=self.kwargs['order_id']) def get_context_data(self, **kwargs): context = super(OrderUpdateView, self).get_context_data(**kwargs) if 'form' not in context: context['form'] = self.form_class() if 'customer' not in context: context['customer'] = self.second_form_class() return context How could i get the customer object ? -
django-table2: get row primary key to access row extra details
I am trying to get list of products to be displayed as a django table and I am trying to create one column that would be a see more link to the details page for that one product. I cannot get the syntax correct for that one specific field and been banging my head off the wall for hours. here is what I got for tables.py class ProductsTable(tables.Table): Details = tables.TemplateColumn('<a href="{% url 'woppa_product_details' pk= record.pk %}">See more</a>') class Meta: model = Products fields = ( 'ProductCode', 'ProductName', 'ProductCategory', ) template_name = "django_tables2/bootstrap4.html" here is my views.py def ProductsView(request): table = ProductsTable(Products.objects.all()) return render(request, 'woppa_inventory_list.html',{'table':table}) and here is urls py urlpatterns = [ path('woppa_inventory_list', ProductsView, name='woppa_inventory_list'), path('woppa_product_details/<str:pk>', ProductDetailsView, name="woppa_product_details"), ] No clue what else to try at this point -
Confusion when importing Django' generic class based views
While exploring the reference documentation and some tutorials I have seen the import for Django's generic class based views used in multiple ways: from django.views.generic import TemplateView, ListView Or: from django.views.generic.base import TemplateView from django.views.generic.list.ListView I have tried experimenting with both tactis and they both seem to work, yet the first option seems less correct. Do all the generic CBVs also exist within the generic module a well as the submodules? Can Python import classes from submodules by only importing a higher module? What is actually happening here? Any help would be greatly appreciated! -
i need to uild reservation meeting rooms systems
i am fresh software developer at django reset framework and i want to develop a reservation meeting rooms web application and i create below model and form meeting room reservations (select meeting room with date and time if conflict with another date of reserve error message (this room is reserved by employee name) below my model : model.py: class MeetingRooms(models.Model): """Model representing a project.""" room_name = models.CharField(max_length=100) description = models.TextField(max_length=1000, help_text='Enter a brief description of the project') room_number = models.IntegerField() def __str__(self): """String for representing the Model object.""" return f'{self.room_name}' def get_absolute_url(self): """Returns the url to access a detail record for this project.""" return reverse('meetingrooms-detail', args=[str(self.id)]) from django.core.exceptions import ValidationError class ReservationMeetingRooms(models.Model): """Model representing a project.""" meeting_room = models.ForeignKey(MeetingRooms, on_delete=models.SET_NULL, null=True, blank=False) reservation_date = models.DateField(null=True, blank=False) reservation_from_time = models.TimeField(auto_now=False, auto_now_add=False) reservation_to_time = models.TimeField(auto_now=False, auto_now_add=False) teams = models.ManyToManyField(Employee) #models.ForeignKey(Employee, on_delete=models.SET_NULL, null=True, blank=False) def clean_reservation_date(self): date = self.cleaned_date['reservation_date'] # Check if a date is not in the past. if date < datetime.date.today(): raise ValidationError(_('Invalid date - Date cannot be in the past')) return date def __str__(self): """String for representing the Model object.""" return f'{self.meeting_room}' return f'{self.teams}' def get_absolute_url(self): """Returns the url to access a detail record for this project.""" return reverse('reservationmeetingrooms-detail', args=[str(self.id)]) … -
Conditional rendering (of different sections) in Django Template
I wrote this code (inside a view) to generate some flags # when to show bidding form? # - current user is logged in # - listing is active # - listing isn't created by current user show_bidding_form = ( request.user.is_authenticated and listing.is_active and listing.owner != request.user ) # when to show #bids and close listing form? # - current user is logged in # - listing is active # - current user is listing owner show_bids_count = ( request.user.is_authenticated and listing.is_active and listing.owner == request.user ) that control showing different sections (inside a template) {% if show_bidding_form %} <!-- some div ->> {% elif can_close_listing %} <!-- some other div --> {% endif %} my question is: is this the best way to do such filtering? or there's some other "official" way. I am thinking of moving both code and markup into a inclusion tag instead. But then the view the originally contained code would be empty and I will have no clue of what's going on inside template it renders.. -
Django, HttpResponse, HTML
I have checkboxes after selecting several queries and the page is generated according to the selected checkboxes. question: to use HttpResponse and to make the page in parts, whether it is possible to use a template? -
Getting database error while using django-paypal
Im using Mongodb (djongo engine) for the database for my django project, I can't work out I always get this error when paypal posts to my website: [13/Dec/2021 15:59:44] "POST /paypal/ HTTP/1.1" 500 28196 Internal Server Error: /paypal/ Traceback (most recent call last): File "C:\Users\user\Documents\Building systems\VintageWebsite\.venv\lib\site-packages\djongo\sql2mongo\query.py", line 857, in parse return handler(self, statement) File "C:\Users\user\Documents\Building systems\VintageWebsite\.venv\lib\site-packages\djongo\sql2mongo\query.py", line 933, in _select return SelectQuery(self.db, self.connection_properties, sm, self._params) File "C:\Users\user\Documents\Building systems\VintageWebsite\.venv\lib\site-packages\djongo\sql2mongo\query.py", line 116, in __init__ super().__init__(*args) File "C:\Users\user\Documents\Building systems\VintageWebsite\.venv\lib\site-packages\djongo\sql2mongo\query.py", line 62, in __init__ self.parse() File "C:\Users\user\Documents\Building systems\VintageWebsite\.venv\lib\site-packages\djongo\sql2mongo\query.py", line 152, in parse self.where = WhereConverter(self, statement) File "C:\Users\user\Documents\Building systems\VintageWebsite\.venv\lib\site-packages\djongo\sql2mongo\converters.py", line 27, in __init__ self.parse() File "C:\Users\user\Documents\Building systems\VintageWebsite\.venv\lib\site-packages\djongo\sql2mongo\converters.py", line 119, in parse self.op = WhereOp( File "C:\Users\user\Documents\Building systems\VintageWebsite\.venv\lib\site-packages\djongo\sql2mongo\operators.py", line 475, in __init__ self._statement2ops() File "C:\Users\user\Documents\Building systems\VintageWebsite\.venv\lib\site-packages\djongo\sql2mongo\operators.py", line 428, in _statement2ops op = self._token2op(tok, statement) File "C:\Users\user\Documents\Building systems\VintageWebsite\.venv\lib\site-packages\djongo\sql2mongo\operators.py", line 405, in _token2op op = ParenthesisOp(SQLStatement(tok), self.query) File "C:\Users\user\Documents\Building systems\VintageWebsite\.venv\lib\site-packages\djongo\sql2mongo\operators.py", line 493, in __init__ self._statement2ops() File "C:\Users\user\Documents\Building systems\VintageWebsite\.venv\lib\site-packages\djongo\sql2mongo\operators.py", line 428, in _statement2ops op = self._token2op(tok, statement) File "C:\Users\user\Documents\Building systems\VintageWebsite\.venv\lib\site-packages\djongo\sql2mongo\operators.py", line 405, in _token2op op = ParenthesisOp(SQLStatement(tok), self.query) File "C:\Users\user\Documents\Building systems\VintageWebsite\.venv\lib\site-packages\djongo\sql2mongo\operators.py", line 493, in __init__ self._statement2ops() File "C:\Users\user\Documents\Building systems\VintageWebsite\.venv\lib\site-packages\djongo\sql2mongo\operators.py", line 438, in _statement2ops if prev_op.lhs is None: AttributeError: 'NoneType' object has no attribute 'lhs' The above exception was … -
Generator expression must be parenthesized if not sole argument: using join
I'm getting following exception while run the server:- SyntaxError: Generator expression must be parenthesized if not sole argument to the following line: return '\n'.join(' | '.join(value.rjust(width) for value, width in row, widths) for row in table I'm using a Python 3 version. I also tried to upgrade the django but still it returns same exception. Can anyone help me to solve this problem? Thanks in advance. -
404 error : no comment matches the given query
I've searched enough about this problem, but haven't been able to find a solution. Please help me. View.py class comment_delete(DeleteView): model = Comment success_url = reverse_lazy('board_list.html') urls.py path('', views.home, name="home"), path('board/', views.board.as_view(), name="board"), path('board/<int:pk>/', views.board_detail.as_view(), name="board_detail"), path('board_write/', views.board_write, name="board_write"), path('board_insert', views.board_insert.as_view(), name="board_insert"), path('board_edit/', views.board_edit, name="board_edit"), path('board_update/', views.board_update, name="board_update"), path('board_delete/', views.board_delete, name="board_delete"), ####### comment ######### path('board/comment/update/', views.comment_update, name="comment_update"), path('board/<int:pk>/comment/<int:id>/delete/', views.comment_delete.as_view(), name="comment_delete") comment.html <form action="{% url 'comment_delete' pk=i.Board_id id=i.id %}" method='POST'> -
Django save request.POST to JSONField picks last item from list instead of saving the list
I have a view that receives a post request from client.post() data = { "token": create_hash(customer_name), "images": [image_1, image_2], "name": customer_name, "email": "test@email.com", "phone": "0612345678", "product": "product-sku0", "font_family": "Helvetica", "font_size": 12, "colors_used": ( "#AAAAAA|White D", "#FFFFFF|Black C" ) } I am trying to save the post request as a whole to a model.JSONfield(). The post request key-value pair looks like this: 'colors_used': ['#AAAAAA|White D', '#FFFFFF|Black C'] When I save and later retrieve the value it looks like this: 'colors_used': '#FFFFFF|Black C' Instead of saving the nested list in the JSONfield it only saved the last value. I am using SQLite. -
How to properly override get_queryset in a modelviewset without breaking the query by pk?
I have a ModelViewSet: class OrderViewSet(viewsets.ModelViewSet): serializer_class = OrderSerializer pagination_class = DefaultPagination queryset = Order.objects.all() def get_queryset(self): userId = self.request.query_params.get('userId') if userId is not None: query = Order.objects.filter(owner__id=userId).order_by('-createdAt') else: query = Order.objects.order_by('-createdAt') return query Here is the url registration router = routers.DefaultRouter() router.register('api/v1/order', OrderViewSet, basename='order') I found that after overriding the get_queryset, I can no longer query by one order id like the following anymore: /api/v1/order/1,it just returns detail: not found I do see django saying it supports: ^api/v1/order/$ [name='order-list'] ^api/v1/order\.(?P<format>[a-z0-9]+)/?$ [name='order-list'] ^api/v1/order/(?P<pk>[^/.]+)/$ [name='order-detail'] ^api/v1/order/(?P<pk>[^/.]+)\.(?P<format>[a-z0-9]+)/?$ [name='order-detail'] what should be the correct way to do this? Thanks! -
Django/React 415 (Unsupported Media Type)
I'm getting POST http://localhost:8000/api/reports/ 415 (Unsupported Media Type) when I try to submit the form from React and I don't understand what's the problem. Here's the code. models.py class Report(models.Model): category = models.ForeignKey(Category, on_delete=models.PROTECT) description = models.TextField() address = models.CharField(max_length=500) reporter_first_name = models.CharField(max_length=250) reporter_last_name = models.CharField(max_length=250) reporter_email = models.CharField(max_length=250) reporter_phone = models.CharField(max_length=250) report_image_1 = models.ImageField(_("Image"), upload_to=upload_to, null=True, blank=True) report_image_2 = models.ImageField(_("Image"), upload_to=upload_to, null=True, blank=True) report_image_3 = models.ImageField(_("Image"), upload_to=upload_to, null=True, blank=True) date = models.DateTimeField(default=timezone.now) class Meta: ordering = ('-date',) def __str__(self): return self.description I also tried to put default values for images, but I still get the error. serializers.py class ReportSerializer(serializers.ModelSerializer): categoryName = CategorySerializer(many=False, read_only=True, source='category') class Meta: model = Report fields = '__all__' views.py class ManageReports(viewsets.ModelViewSet): serializer_class = ReportSerializer parser_classes = [MultiPartParser, FormParser] def get_object(self, queryset=None, **kwargs): id = self.kwargs.get('pk') return get_object_or_404(Report, id=id) def get_queryset(self): return Report.objects.all() This is the code responsible for the submit. report.js const initialPostData = Object.freeze({ category: '', address: '', description: '', reporter_first_name: '', reporter_last_name: '', reporter_email: '', reporter_phone: '', }); const [postData, updatePostData] = useState(initialPostData); const [postImage1, setPostImage1] = useState({image: null}); const [postImage2, setPostImage2] = useState({image: null}); const [postImage3, setPostImage3] = useState({image: null}); const handleChange = (e) => { if([e.target.name] == 'reporter_image_1') { setPostImage1({ image: … -
Creating a chart from sentiments of user tweets using chart.js
I’m new to Django. I’m currently doing sentiment analysis on real-time user tweets via Twitter API. I have managed to do the analysis and display the sentiments. Now, I want to visualize the sentiments using charts in my Django app (perhaps bar chart or pie chart) but I’m not sure how. I was thinking of using Chart.js to make it responsive but most of the examples are using static data so I wasn’t successful in integrating my data where I extracted from Twitter API with chart.js. This is a screenshot of my web page. The table was the extracted tweets with their corresponding sentiments. The bar chart however is just static data. I don't know how to convert it into json. enter image description here this is my views.py from django.http.response import JsonResponse from django.shortcuts import render, redirect, HttpResponse from .forms import Sentiment_Typed_Tweet_analyse_form from .sentiment_analysis_code import sentiment_analysis_code from .forms import Sentiment_Imported_Tweet_analyse_form from .tweepy_sentiment import Import_tweet_sentiment from django.contrib.auth.decorators import login_required from django.contrib import messages def sentiment_analysis_import(request): if request.method == 'POST': form = Sentiment_Imported_Tweet_analyse_form(request.POST) tweet_text = Import_tweet_sentiment() analyse = sentiment_analysis_code() if form.is_valid(): handle = form.cleaned_data['sentiment_imported_tweet'] # messages.info(request, 'It might take a while to load the data.') if handle[0]!='#': list_of_tweets = tweet_text.get_hashtag(handle) list_of_tweets_and_sentiments … -
why showing error page is not found while using /<pk>/?
urls.py I tryed allot but can not fond why this happened when I apply or it is always showing the same error from django.contrib import admin from django.urls import path from . import views urlpatterns = [ path('nature', views.nature, name ='nature'), path('', views.index, name ='index'), path('footer', views.footer, name ='footer'), path('navebar', views.navebar, name ='navebar'), path('form', views.form, name ='form'), path('venue', views.venue, name ='venue'), path('db/<db_id>/', views.db, name ='db'), views.py from django.shortcuts import render def db(request, db_id): all = Task.objects.get(pk= db_id) return render(request,'MYapp/db.html',{'all': all}) -
Duplicate Django model with nested children
I have a model with nested children and want to duplicate it, I tried some solutions but couldn't solve my problem! here are my models to show the relationships between them: class Form(models.Model): form_id = models.UUIDField(primary_key=True, default=uuid4, editable=False) form_title = models.CharField(max_length=100) class Page(models.Model): page_id = models.UUIDField(primary_key=True, default=uuid4, editable=False) page_title = models.CharField(max_length=100) form = models.ForeignKey(Form, related_name='pages') class Section(models.Model): section_id = models.UUIDField(primary_key=True, default=uuid4, editable=False) section_title = models.CharField(max_length=100) page = models.ForeignKey(Page, related_name='sections') class Question(models.Model): question_id = models.UUIDField(primary_key=True, default=uuid4, editable=False) question_title = models.CharField(max_length=100) section = models.ForeignKey(Section, related_name='questions') class Answer(models.Model): answer_id = models.UUIDField(primary_key=True, default=uuid4, editable=False) answer_value = models.TextField(blank=True) question = models.OneToOneField(Question, related_name="question") I used this solution, I could duplicate the form and pages but couldn't go next for duplicating other children! class DuplicateFormAPI(views.APIView): def get(self, request, form_id): form = Form.objects.filter(form_id=form_id).first() form.form_id = None form.save() duplicated_form_id = FormSerializer(form).data.get('form_id') pages = Page.objects.filter(form_id=form_id).all() for page in pages: page.page_id = None page.form_id = duplicated_form_id page.save() return Response({ "status": status.HTTP_200_OK, "message": "Form duplicated successfully!", "form": FormSerializer(form).data, }) Anyone could help or give me some hints? -
django-filter shows all fields instead of just the ones specified
In my filters.py: class DataFilter(FilterSet): start_date = DateFilter(field_name='date',lookup_expr=('lt'),) end_date = DateFilter(field_name='date',lookup_expr=('gt')) date_range = DateRangeFilter(name='date') class Meta: model = DataModel fields = ['date', ] I have also tried setting fields = [], but filters of all fields are still there. Why is it showing all even I just only specified one (even none)? And how to fix that? Can anyone help explain? Thank you! In my models.py: class DataModel(models.Model): date = models.DateField(default=now) other_field_1 = models.CharField() other_field_2 = models.CharField() other_field_3 = models.CharField() In my views.py: class DataModelListView(LoginRequiredMixin, FilterView): model = DataModel template_name = 'datamodel_list.html' filter_class = DataFilter I am using django 3, django-filter 21. -
Acess dictionary value in template
I have a list view where I define queryset as a list of objects if current user is not a top manager otherwise queryset is a dictionary with key being employee and value being list of objects. So I want to know how to display the key from this dict and then list it's value - a list. I tried to do it like that <ul> {% for k, v in employees_list.items %} <li><a href="{% url 'employees:employees-detail' pk=v.pk %}"> {{ v.title }} {{ v.last_name }} {{ v.first_name }}</a></li> {% endfor %} </ul> It didn't work out. Here's the view class EmployeesListView(LoginRequiredMixin, ListView): model = Employees template_name = 'employees/employees_list.html' context_object_name = 'employees_list' fields = ['last_name', 'first_name', 'title', 'birth_date', 'reports_to'] is_top_manager = False def get_queryset(self): #current_emp = get_current_users_employee(self.request.user) #return super().get_queryset().filter(reports_to=current_emp) current_emp = get_current_users_employee(self.request.user) this_employees_subordinates = Employees.objects.filter(reports_to=current_emp) if str(current_emp.title) != "Top manager": return this_employees_subordinates else: self.is_top_manager = True print("this user is top manager") lower_level_subordinates = {} for subordinate in this_employees_subordinates: lower_level_subordinates[subordinate] = Employees.objects.select_related('title').filter(reports_to=subordinate) print(lower_level_subordinates) return lower_level_subordinates -
Reverse for 'db' with arguments '('',)' not found. 1 pattern(s) tried: ['db/(?P<db_id>[^/]+)/$']
when I am trying to grab items from db.html with the help of id it is showing an error I cant understand where is the problem please help me out venue.html {% extends 'MYapp/index.html' %} {% block content %} <center> <h1> venue.html </h1> <br> <div class="card-header"> Featured </div> <div class="card-body container-fluid"> <h5 class="card-title">Special title treatment</h5> {% for venues in venue_list %} <p class="card-text container-fluid"> <a href="{% url 'db' all.id %}"> {{ venues }} {{ venues.lastname}}</a> {% endfor %} </p> </div> </center> {% endblock %} views.py from django.shortcuts import render from django.http import * from MYapp.models import * from .form import * def index(request): return render(request,'MYapp/index.html') def venue(request): venue_list = Task.objects.all() return render(request,'MYapp/venue.html',{'venue_list': venue_list}) def db(request, db_id): all = Task.objects.get(pk= db_id) return render(request,'MYapp/db.html',{'all': all}) urls.py another error occers hear it is showing page is not found because of this path('db/<db_id>/', views.db, name ='db'), from django.contrib import admin from django.urls import path from . import views urlpatterns = [ path('nature', views.nature, name ='nature'), path('', views.index, name ='index'), path('footer', views.footer, name ='footer'), path('navebar', views.navebar, name ='navebar'), path('form', views.form, name ='form'), path('venue', views.venue, name ='venue'), path('db/<db_id>/', views.db, name ='db'), ] -
DJANGO : How to iterate a ListView items to convert in cards
I am coding an app "dash" how a startpoint to many users. "a applications dashboard". I want to convert the list of applications in cards, "portfolio style". the user login in the platform, and in the url .../dash open the dash(django app). To here it's perfect. with the generic view - ListView - we obtain the list of applications will be available in the platform (if exist in the model, the application it's installed and available to the user) urls.py: path('dash/', views.ListView_Dash_Apps.as_view()), views.py: class ListView_Dash_Apps(ListView): template_name = "dash/ListarAplicaciones.html" model = App and in the html template, How to iterate the columns of the object_list??? with this i can iterate the rows, but not the column, i receive the str output declarated in the model. <ul> {% for e in object_list %} <li>{{ e }}</li> {% endfor %} </ul> If i can to read the columns data and include in the html (App, url_app, icon, etc etc..)