Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django REST File Upload Error curl: (26) couldn't open file
I am trying to make an API endpoint using Django REST Framework which allows for file uploads. I have implemented a basic APIView to do this as per the Django REST Framework documentation but am still receiving the error curl: (26) couldn't open file file=@/Users/espresso/Documents/Work/Work\ Maps/Extracted\ Maps/abb1.geojson" views.py class FileUpload(APIView): parser_classes = (FileUploadParser,) def put(self, request, filename, format=None): file_obj = request.FILES['file'] return Response({"status":"successful"}, content_type="application/json") urls.py urlpatterns = [ url(r'^api/v1/upload/(?P<filename>[^/]+)$', views.FileUpload.as_view(), name='upload'), ] Curl $ curl http://127.0.0.1/dashboard/api/v1/upload/ \ --request PUT \ -H "Content-Type: multipart/form-data" \ -F "file=@/Users/espresso/Documents/Work/Work\ Maps/Extracted\ Maps/abb1.geojson" \ -F "filename=abb1.geojson" -
GraphQL with Django
I have a slight problem understanding how to restrict graphql queries. How can I make sure that a user who is not allowed to see a certain information can not get it through a relationship from a model? I have three different user types which have certain permissions. Each user can only access the information which he's allowed to access from the root query. But I can still access information from a user which he should not see if I have a certain depth of query and use certain relationships? Can someone please tell me how to restrict the query output or how to restrict it in the schema.py? Thanks in advance -
django dates and pandas dates conversion
I am trying to compare dates pulled from my Django database, and dates from a spreadsheet imported and processed using pandas. How can I make them equal for comparison sake? I don't need the time, just the date I do have tz support on in my settings.py, but this is because it is needed in other areas of my application. from django.views import generic from django.views.generic import TemplateView from django.urls import reverse_lazy from django.urls import reverse from .models import ClientJobs from django.contrib.auth.mixins import LoginRequiredMixin from django.shortcuts import render from django.http import HttpResponse, HttpResponseRedirect import datetime, time from datetime import date from datetime import datetime import pandas as pd class uploadView(TemplateView): template_name = 'uploadPage.html' def get(self, *args, **kwargs): #read excel file, turn into dataset, remove date values set to NaT (no date) and set as 0 instead excelFile = (r'C:\Users\matth\testing\Old.xlsx') dataSet = pd.read_excel(excelFile).fillna(0) lastDataSet = ClientJobs.objects.filter(dataSetNumber = 1) oldVisitDate = lastDataSet[0].visitDate newVisitDate = dataSet.iloc[0][1].to_pydatetime() print(oldVisitDate) print(newVisitDate) return super().get(*args, **kwargs) This returns: 2019-04-18 05:00:00+00:00 2019-04-18 00:00:00 As you can see the queried result has tz info, and the pandas result does not. My goal is to compare the dates to see if they are equal. I don't need the time, just the … -
Setting background image via CSS in Django project
I think I'm doing everything pretty right, but it still doesn't work. Here are my structure and html file: {% load static %} <style> body{ margin:0; padding: 0; background: url("{% static 'aztu.jpg' %}"); } </style> -
django admin site override the change_list.html
is their any possible to override the change_list.html? i just want to add another table/listview, models.py class StudentsEnrollmentRecord(models.Model): Student_Users = models.ForeignKey(StudentProfile, related_name='students', on_delete=models.CASCADE,null=True) School_Year = models.ForeignKey(SchoolYear, related_name='+', on_delete=models.CASCADE, null=True, blank=True) Courses = models.ForeignKey(Course, related_name='+', on_delete=models.CASCADE, null=True, blank=True) Section = models.ForeignKey(Section, related_name='+', on_delete=models.CASCADE, null=True,blank=True) admin.py class StudentsEnrollmentRecordAdmin(admin.ModelAdmin): #inlines = [InLineSubject] list_display = ('lrn', 'Student_Users', 'Education_Levels', 'Courses', 'Section', 'Payment_Type', 'Discount_Type' ,'School_Year') #list_select_related = ('Student_Users') ordering = ('Education_Levels','Student_Users__lrn') list_filter = ('Student_Users','Education_Levels','Section','Payment_Type') def lrn(self, obj): return obj.Student_Users.lrn -
Django - how to filter though multiple manyTomany relationship layers
Consider the following setup: class ModelA(models.Model): foreign = models.ForeignKey(ModelB, on_delete=models.CASCADE) children = models.ManyToManyField('self', related_name="parent", symmetrical=False, blank=True) class ModelB(models.Model): caption = models.CharField(db_index=True, max_length=50, null=False, unique=True) children = models.ManyToManyField(ModelC, blank=True) class ModelC(models.Model): ...lots of fields Now, given the pk of a ModelA Object, I want to get and filter all the related ModelC Objects. Here is what i'm trying to achieve efficiently: modelC_objects = ModelA.objects.filter(parent__in=[modelA_id]).distinct().foreign.children .filter(pk__lte=last_id) .exclude(is_private=True) .order_by('-pk')[0:100] .prefetch_related("other") ) Obviously that doesn't work. I am currently doing something ugly like this: modelA_objects = ModelA.objects.filter(parent__in=[modelA_id]).distinct() modelC_querysets = [modelA.foreign.children for modelA in modelA_objects] if modelC_querysets: modelC_objects = modelC_querysets[0] modelC_querysets.pop(0) for x in modelC_querysets: modelC_objects = modelC_objects | x filtered = (modelC_objects.filter(pk__lte=last_id) .exclude(is_private=True) .order_by('-pk')[0:100] .prefetch_related("other") ) How can I achieve what I attempted? -
Django advanced query - objects of a Foriegnkey?
I have a Django models where I have this : class Patient(models.Model): FirstName = models.CharField(max_length=264) LastName = models.CharField(max_length=264) Address = models.TextField(blank=True) Telephone_no = models.CharField(max_length=100,blank=True) user = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE,related_name='patients') class UploadedImages(models.Model): patient = models.ForeignKey(Patient,on_delete=models.CASCADE,related_name='images') original = models.ImageField(upload_to = user_directory_path, validators=[validate_file_extension],verbose_name = 'Image') enhanced = models.ImageField(upload_to=analyses_directory_path, blank=True) segmented = models.ImageField(upload_to=analyses_directory_path, blank=True) class Processed(models.Model): uploaded_image = models.ForeignKey(UploadedImages,on_delete=models.CASCADE,related_name='processed') pre_analysed = models.ImageField(upload_to=analyses_directory_path, blank=True) analysedimage = models.ImageField(upload_to=analyses_directory_path, blank=True) so I want to make queries based on the current user which is user = request.user this is possible in the patient model case as I can make Patient.objects.filter(user=user) but i can't make it the other 2 models is there any idea how I can do this? I didn't add the user FK as I thought I wouldn't need it but now I do? do i need to add it ? can I make a query without adding the field ? -
How to add category from user interface using Django
I have a problem related with category section: when I rm by db.sqlite3 (I'm using linux terminal), I can't add category manually from user interface (later UI). I have empty section without + to add categories: But when I accessing my admin panel, I can add categories manually without any problems(I don't know why, but this + symbol exist: After this manipulation I can select this category in UI. I need a solution, that would allow user add category from UI, solution, in which not only I can add some categories from admin panel and let users choose from them. I need to add this + sign in my UI. Some code: from views.py def blog_category(request, category): posts = Post.objects.filter(categories__name__contains=category).order_by('-date_posted') content = { 'category': category, 'posts': posts } return render(request, 'blog/blog_category.html', content) post_form.html {% extends 'blog/base.html' %} {% load crispy_forms_tags %} {% block content %} <div class="content-section"> <form method="POST" enctype="multipart/form-data"> {% csrf_token %} <fieldset class="form-group"> <legend class="border-bottom mb-4">Blog Post</legend> {{ form|crispy }} </fieldset> <div class="form-group"> <button class="btn btn-primary" type="submit">Post</button> </div> </form> </div> {% endblock content %} -
Django ModelChoiceField doesn't validate the form
The choices are displayed correctly from the queryset. The problem is that the form does not pass the validation block code. I've been trough all posibilities on similiar questions here on stack and nothing suits me. This is my form: class AddContract(forms.Form): ********************* city = forms.ModelChoiceField(queryset=None, widget=forms.Select, required=True,to_field_name='city', initial=0) ********************* def __init__(self, *args, **kwargs): sub_user = kwargs.pop('sub_user', None) super(AddContract, self).__init__(*args, **kwargs) self.fields['city'].queryset = City.objects.filter(sub_user=sub_user) This is my view: if request.method == 'POST' and 'addcontract' in request.POST: addcontract_form = AddContract(request.POST) if addcontract_form.is_valid(): ********** city= addcontract_form.cleaned_data['city'] ********** addcontract_form = AddContract(sub_user=sub_user) -
Change color of form field if it's not the first (default value)
I am trying to change the color of a form field (or put a border around the field) if the value is not the default (first option) and for text fields if there is text in the field. For example, the form has five (5) fields and if any of those fields has a value that is not the very first (default) option or has text in the field if it's a text field, I want to change the color of the field background or put a border around it to denote that the field has changed for the user that is searching. I want to change the color or add a border to all fields in the form. Seems like the best way to do this would be to use Javascript to loop through the form fields and check if the selection is the first option but I am not familiar with Javascript and all of the solutions I have found only check if the value is empty, not if the value is the first value or not for multiple fields. I am using basic HTML and Python/Django from a frontend and backend standpoint respectively. Any advice on the … -
Django Form Wizard: Skip a step but still provide data
I am creating a form using django form wizard. The first step is a user selection, but based upon permissions, some users can only create a form for themselves. If this is the case, there is no reason for them to see the user selection step (as the user will just be the current user). I would like to skip this step, but still provide the data (the current user) to the form. Later, I am accessing that step's data to prefill other fields, so I need to save the data somewhere. I could handle this with multiple if checks seeing if the form data exists, if not, get the current user...etc, but this seems messy. Is there a way to tell the form wizard to not totally skip the step, but just not show it? -
problem with connecting Clever Cloud bucket to django with envronment variable
I have a problem to connect my CC bucket to a django application. My bucket looks as follows: Could you please tell me what I have to define as CC_FS_BUCKET? I thought it is: folder:addon-id.host -
How can get last nth item of a query on PostgreSql
Question: How I can get the last 750 records of a query in the Database level? Here is What I have tried: # Get last 750 applications apps = MyModel.active_objects.filter( **query_params ).order_by('-created_at').values_list('id', flat=True)[:750] This query fetches all records that hit the query_params filter and after that return the last 750 records. So I want to do this work at the database level, like mongoDb aggregate queries. Is it possible? Thanks. -
Django form submit redirect to a different url
Please help action is set to =".", but django redirects to another url views.py def post_detail(request, year, month, day, post): post = get_object_or_404(Post, slug=post, status='published', publish__year=year, publish__month=month, publish__day=day) # List of active comments for this post comments = post.comments.filter(active=True) new_comment = None if request.method == 'POST': # A comment was posted comment_form = CommentForm(data=request.POST) if comment_form.is_valid(): # Create Comment object but don't save to database yet new_comment = comment_form.save(commit=False) # Assign the current post to the comment new_comment.post = post new_comment.save() else: comment_form = CommentForm() return render(request, 'blog/post/detail.html', {'post': post, 'comments': comments, 'new_comment': new_comment, 'comment_form': comment_form}) urls.py from django.urls import path from . import views app_name = 'blog' urlpatterns = [ path('', views.PostListView.as_view(), name='post_list'), path('<int:year>/<int:month>/<int:day>/<slug:post>', views.post_detail, name='post_detail'), path('<int:post_id>/share/', views.post_share, name='post_share'), ] detail.html <h2>Add a new comment</h2> <form action="." method="post"> {{ comment_form.as_p }} {% csrf_token %} <p><input type="submit" value="Add comment"></p> </form> When i click on submit button i expected it to remain on this url "http://localhost:8000/blog/2019/11/20/one-more-post", but it cut off the slug part and redirect to this: "http://localhost:8000/blog/2019/11/20/", there by throwing page not found error "Page not found (404)" -
Django - Pre-populating a ModelForm with parameters passed in url
I am trying to pre-populate a ModelForm with data from an url but get the following error message: Reverse for 'create_entry' with arguments '(1, datetime.date(2019, 11, 1))' not found. 2 pattern(s) tried: ['create_entry/<int:habit_id>/(?P<selected_day>\\d{4}-\\d{2}-\\d{2})/$', 'create_entry/$'] In the template, the url reads: {% url 'habitap:create_entry' habit.id date %} and in the url conf, I have: re_path(r'^create_entry/<int:habit_id>/(?P<selected_day>\d{4}-\d{2}-\d{2})/$', create_entry, name='create_entry') and path('create_entry/', create_entry, name='create_entry') ( I am using a view with optional arguments) If I take out habit.id from the url, the error goes away but the form doesn't get pre-populated and the url is not declared properly. Please do not hesitate to let me know if you need more information. Thank you for your help ! -
django.db.utils.ProgrammingError: column calculator_calculation._id does not exist using heroku and djongo
My app works on my local machine but when deployed to heroku with the exact same code I get errors when using get requests to my API views involving any DB interaction. I have a feeling heroku is trying to use postgres for some reason, even though I do not have any code dealing with postgres in my code. Any help is appreciated, I have done migrations a million different ways with no luck, even though mongo shouldnt need migrations. Error and code below 2019-11-21T18:26:15.428986+00:00 app[web.1]: Traceback (most recent call last): 2019-11-21T18:26:15.428989+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/django/core/handlers/exception.py", line 34, in inner 2019-11-21T18:26:15.428991+00:00 app[web.1]: response = get_response(request) 2019-11-21T18:26:15.428993+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/django/core/handlers/base.py", line 115, in _get_response 2019-11-21T18:26:15.428995+00:00 app[web.1]: response = self.process_exception_by_middleware(e, request) 2019-11-21T18:26:15.428997+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/django/core/handlers/base.py", line 113, in _get_response 2019-11-21T18:26:15.429000+00:00 app[web.1]: response = wrapped_callback(request, *callback_args, **callback_kwargs) 2019-11-21T18:26:15.429002+00:00 app[web.1]: File "/app/calculator/views.py", line 22, in calculate 2019-11-21T18:26:15.429004+00:00 app[web.1]: print(calcs) 2019-11-21T18:26:15.429006+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/django/db/models/query.py", line 250, in __repr__ 2019-11-21T18:26:15.429008+00:00 app[web.1]: data = list(self[:REPR_OUTPUT_SIZE + 1]) 2019-11-21T18:26:15.429010+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/django/db/models/query.py", line 274, in __iter__ 2019-11-21T18:26:15.429012+00:00 app[web.1]: self._fetch_all() 2019-11-21T18:26:15.429014+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/django/db/models/query.py", line 1242, in _fetch_all 2019-11-21T18:26:15.429016+00:00 app[web.1]: self._result_cache = list(self._iterable_class(self)) 2019-11-21T18:26:15.429018+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/django/db/models/query.py", line 55, in __iter__ 2019-11-21T18:26:15.429020+00:00 app[web.1]: results = compiler.execute_sql(chunked_fetch=self.chunked_fetch, chunk_size=self.chunk_size) 2019-11-21T18:26:15.429022+00:00 app[web.1]: File … -
Pycharm & Django w/ multiple settings and environment variables issues
I have an issue creating apps and running server from Terminal in PyCharm django project. I have used Pycharms manage.py tool option it doesnt work either. but I cant see my env variables in terminal when I type env. My settings.py looks like this: import os import json import dj_database_url import django_heroku if os.environ.get('DJANGO_DEV'): with open('config.json') as data: configs = json.load(data) from project.dev_settings import * else: configs = os.environ.get('SECRET_KEY') and at the bottom I have heroku settings like this(which works like a charm) DATABASES['default'].update(db_from_env) django_heroku.settings(locals()) when I type for example python manage.py runserver I get an error TypeError: 'NoneType' object is not subscriptable I am clueless at this point what is wrong since I have setup my env variables in pycharm configuration. -
Infinite list filtering does not work - Django
Creates the simplest infinite list that expands when it reaches the end of the page. My code looks something like this: views.py from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger query = Product.objects.all() #paginator page = request.GET.get('page', 1) paginator = Paginator(query, 21) try: numbers = paginator.page(page) except PageNotAnInteger: numbers = paginator.page(1) except EmptyPage: numbers = paginator.page(paginator.num_pages) in the template I use it this way: <!-- products list --> <div class=" infinite-container"> <!-- product query --> {% for product in numbers %} <div class="accordion accordion-spaced infinite-item"> <h1>{{ product }}</h1> </div> {% endfor %} <!-- end query --> </div> <!-- Load more --> {% if numbers.has_next %} <div class="mt-4 text-center"> <a href="?page={{ numbers.next_page_number }}" class="btn infinite-more-link">Loading...</a> </div> {% endif %} <!-- end pagination --> <!-- Infinite Scroll --> <script src="{% static 'assets/js/jquery-3.1.1.min.js' %}"></script> <script src="{% static 'assets/js/jquery.waypoints.min.js' %}"></script> <script src="{% static 'assets/js/infinite.min.js' %}"></script> <script> var infinite = new Waypoint.Infinite({ element: $('.infinite-container')[0] }); </script> If I try to add filtering by category, it works only for the first page, and the next items that showed after expanding are incorrect (it shows what should not). I do it this way: query = Product.objects.all() sort = request.GET.get('sort', False) if sort: query = query.filter(category=sort) #[... other elements in … -
Django admin site: customize the select_to_change.html
How to customize the Select_to_change.html? i just want that the viewi is like this not like this this is my model.py class gradingPeriod(models.Model): Pending_Request = [ ('Active', 'Active'), ('Inactive', 'Inactive'), ] Grade_Scales_Setting= models.ForeignKey(gradeScalesSetting, related_name='+', on_delete=models.CASCADE,null=True) Description = models.CharField(max_length=500,blank=True) Display_Sequence = models.IntegerField() Status = models.CharField(max_length=500, null=True, choices=Pending_Request,blank=True) StartDate=models.DateField(null=True,blank=True) EndDate=models.DateField(null=True,blank=True) Status = models.CharField(max_length=500, null=True, choices=Pending_Request,blank=True) class gradingPeriodsSetting(models.Model): Pending_Request = [ ('Active', 'Active'), ('Inactive', 'Inactive'), ] School_Year = models.ForeignKey(SchoolYear, related_name='+', on_delete=models.CASCADE, null=True, blank=True) Education_Levels = models.ForeignKey(EducationLevel, related_name='+', on_delete=models.CASCADE, blank=True, null=True) Courses = models.ForeignKey(Course, related_name='+', on_delete=models.CASCADE, null=True, blank=True) NumberOfGradingPeriods = models.IntegerField(blank=True, null=True) Status = models.CharField(max_length=500, null=True, choices=Pending_Request,blank=True) class gradingPeriodsSummary(models.Model): Pending_Request = [ ('Active', 'Active'), ('Inactive', 'Inactive'), ] Grading_Periods_Setting= models.ForeignKey(gradingPeriodsSetting, related_name='+', on_delete=models.CASCADE,null=True) Description = models.CharField(max_length=500,blank=True) Display_Sequence = models.IntegerField() Start_Grading_Period= models.ForeignKey(gradingPeriod, related_name='+', on_delete=models.CASCADE,null=True) End_Grading_Period= models.ForeignKey(gradingPeriod, related_name='+', on_delete=models.CASCADE,null=True) Status = models.CharField(max_length=500, null=True, choices=Pending_Request,blank=True) I dont know how to code it to admin.py, is it possible right? -
Bulk upsert with Django
bulk_create with ignore_conflicts=True insert new records only and doesn't update existing one. bulk_update updates only existing records and doesn't insert new one. Now I see only one variant to make upsert is a raw query: from catalog.models import Product with connection.cursor() as cursor: cursor.executemany( """ INSERT INTO app_table (pk, col1, col2) VALUES (%s, %s, %s) ON DUPLICATE KEY UPDATE col1 = VALUES(col1), col2 = VALUES(col2); """, [ ('1', 'val1', 'val2'), ('2', 'val1', 'val2'), ] ) Is there another way to perform bulk upsert in Django? -
Pagination bar not rendering properly in html page
Using: https://medium.com/@sumitlni/paginate-properly-please-93e7ca776432 as reference. I am working with a couple hundred thousand rows of data and have been rendering the data in an html page. So far, I am properly displaying the first 10 rows of data but my pagination bar that should display under the table is not displaying, but I can change the page number by appending '?page=1' to the url. My view function and template are below, while url_replace.py and proper_paginate.py are unchanged from the link posted above: views.py def eventcode(request): meters_obj = Meterdiagbyday.objects.all() page = request.GET.get('page', 1) paginator = Paginator(meters_obj, 10) try: meters_obj = paginator.page(page) except PageNotAnInteger: meters_obj = paginator.page(1) except EmptyPage: meters_obj = paginator.page(paginator.num_pages) return render(request, 'searchengineapp/eventcode.html', {'meters_obj': meters_obj}) template {% if is_paginated %} {% load url_replace %} {% load proper_paginate %} <ul class="pagination"> {% if meters_obj.number == 1 %} <li class="disabled"><span>⇤</span></li> {% else %} <li><a class="page-link" href="?{% url_replace request 'page' 1 %}">⇤</a></li> {% endif %} {% if meters_obj.has_previous %} <li><a class="page-link" href="?{% url_replace request 'page' meters_obj.previous_page_number %}">&laquo;</a></li> {% else %} <li class="disabled"><span>&laquo;</span></li> {% endif %} {% for i in paginator|proper_paginate:meters_obj.number %} {% if meters_obj.number == i %} <li class="disabled"><span>{{ i }} <span class="sr-only">(current)</span></span></li> {% else %} <li><a class="page-link" href="?{% url_replace request 'page' i %}">{{ … -
Formset Factory Make Fields Required
I am using a modelformset_factory in Django to have a user fill out an unknown number of fields. I have made the fields required but in the HTML rendering Django does not add required to the HTML element, looking around online this seems to be a common issue but I have not seen any valid answers that apply for what I want and I feel like this should be simple. How do I make Django add the required tag to appropriate HTML elements? class ItemForm(forms.ModelForm): class Media: js = (formset_js_path,) class Meta: model = PurchaseOrderItems fields = ['name', 'vendor', 'quantity', 'price', 'description'] labels = { 'name': 'Item', } def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) # self.fields['description'] .widget.attrs['required'] = 'required' self.empty_permitted = False self.fields['description'] = forms.CharField( required=False, label='Description', ) def clean(self): """ :return: """ cleaned_data = super().clean() # print(cleaned_data) ItemFormSet = modelformset_factory( PurchaseOrderItems, form=ItemForm, extra=0, min_num=1, validate_min=True, can_delete=True, ) Here is the HTML rendered for the name field, no required: <input type="text" name="form-0-name" maxlength="150" class="form-control" id="id_form-0-name"> -
Django related question. Should a client script import my models or have its own classes?
(note, this is for a private research database using django. This is not for a public website. Users can have access to all source code) I want to build the data for a django model in a script ran off server by a client. The client script will post json to a url where a django view will create the model and save to database on the server. On the client script side I plan to build objects of a class mirroring the model, then put that in json with a method that builds a dictionary. I'm wondering if there is some best practice for this which I am unaware of. Should the script import the actual django model code, or should a new class with the same properties but only derived from "object" be used. -
Django logout bootstrap navbar
I want to add a logout button to my bootstrap navbar but it doesn't look right. {# template.html #} <nav class="navbar navbar-light"> <div class="container"> <div class="navbar-expand"> <ul class="navbar-nav mr-auto"> {% if user.is_authenticated %} <li class="nav-item"> <a href="#" class="nav-link">{{ user.get_username }}</a> </li> <form class="form-inline nav-item" action="{% url 'account_logout' %}" method="POST"> {% csrf_token %} <button type="submit" class="btn btn-info">Log out</button> </form> {% else %} <li class="nav-item"> <a class="nav-link" href="{% url 'account_login' %}">Log in</a> </li> <li class="nav-item"> <a class="nav-link" href="{% url 'account_signup' %}">Sign up</a> </li> {% endif %} </ul> </div> </div> </nav> is there any way to make the button look like a bootstrap nav-link ? If not, how do I make it an anchor that will POST to Django's logout endpoint? -
In Django model how to use related models to check if employee's training is up to date?
Employees have periodic training. When they are hired they have an initial training "I". After a period of time based on TrainingCourse, all employees in a TrainingEvent are due for refresher training "R". I am trying to make a report that shows employees that are overdue for a training. However, I am having difficulty getting the records to "talk" to each other I.E. If John Doe has initial training, that training was overdue, then has refresher training the initial training now shows as NOT overdue. If employee takes courseIdentifier SAF001 with courseType I then they take courseType R of the same identifier they are up to date and not overdue. Do I need to change my database structure? The code is not live. How do I check if an individual attendee of a TrainingEvent is overdue on training? class Department(models.Model): departmentName = models.CharField(max_length = BIG_MAX_LENGTH) #Engineering departmentCode = models.IntegerField(unique = True) #department code, like 123 departmentDescription = models.CharField(max_length = BIG_MAX_LENGTH, blank = True) #like Engineering Department and Design requiredDepartmentTraining = models.ManyToManyField('TrainingCourse', blank=True, related_name = "trainings") def save(self,*args, **kwargs): print("self: ", self) if not self.id: #new/create super(Department, self).save(*args, **kwargs) super(Department, self).save(*args, **kwargs) def __str__(self): return self.departmentName class TrainingCourse(models.Model): courseName = models.CharField(max_length …