Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
nginx redirect from url to another in django admin panel
I would like to have redirect in django admin panel, like this: from https://url_to_my_page/admin/filer/ to https://url_to_my_page/admin/filer/folder/ I tried to make this on nginx side, but didn't worked: location /admin/filer/ { return /admin/filer/folder/; } -
Django: sqlite3 failed to find the path of sqlite file
Connection to Django default failed. path to 'C:\Users\nblizz\Workspace\Files\myweb\Web\db.sqlite3': 'C:\Users\nblizz\Workspace\Files\myweb' does not exist I changed project name from myweb to pyweb, but Django's sqlite3 still recognizes the path of .sqlite file as myweb. So above error message keeps appear. I modified all of myweb in settings.py and manage.py but nothing has changed. How to I fix the path of .sqlite files of Django? settings.py: BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } -
Why am I receiving a non-nullable field error and is to correct to user ForeignKey to relate the tables with each other?
This is my code and I keep receiving an error! from django.db import models # Create your models here. class topics(models.Model): topic_level = models.BooleanField() topic_name = models.TextField() topic_question = models.ForeignKey('questions', on_delete=models.CASCADE) topic_answer = models.ForeignKey('answers', on_delete=models.CASCADE) topic_image = models.ForeignKey('images', on_delete=models.CASCADE) class questions(models.Model): question_description = models.TextField() questions_type = models.BooleanField() question_answer = models.ForeignKey('answers', on_delete=models.CASCADE) question_image = models.ForeignKey('images', on_delete=models.CASCADE) class answers(models.Model): description = models.TextField() answer_image = models.ForeignKey('images', on_delete=models.CASCADE) class images (models.Model): image_blob = models.BinaryField() This is the error: You are trying to add a non-nullable field 'answer_image' to answers without a default; we can't do that (the database needs something to populate existing rows). sting rows). Please select a fix: 1) Provide a one-off default now (will be set on all existing rows with a null value for this column) 2) Quit, and let me add a default in models.py I would like to know if I add a default value, will it affect the relationship between the tables? And what value to add? Does a random value do the job? Thanks, -
Django and Elasticbeanstalk: internal dummy connection (doesn't work on eb even though the part works on local)
I deployed my project to elasticbeanstalk but there's a thing that doesn't work there even though it works on local environment. The error happens here. def add_entry(request): if 'entry_form' in request.POST: # group is None if the hidden value is empty and it means it's not group page try: group = Group.objects.get(pk=request.POST.get('group_pk')) except: group = None entry_form = EntryForm(request.POST, user=request.user, group=group) entry_formset = PhotoFormset(request.POST, request.FILES) if entry_form.is_valid() and entry_formset.is_valid(): new_entry = entry_form.save() for entry_form in entry_formset.cleaned_data: try: photo = entry_form['photo'] new_photo = Photo(entry=new_entry, photo=photo) new_photo.save() except: break messages.success(request, "Your post has been saved successfully.") return redirect(request.POST.get('current_path')) This part is just posting an Entry object and Photo objects. It's supposed to get hidden value from html and redirect to the current page. html <input type="hidden" name="group_pk" value="{{ group.pk }}"> <input type="hidden" name="current_path" value="{{ request.get_full_path }}"> <button type="submit" name="entry_form" class="btn btn-primary">Post</button> However, it redirects to entry/add url that I don't set template and error happens. path('entry/', include([ path('add', views.add_entry, name='add_entry'), Error code is 500. I found this on access log on eb. [21/Jan/2019:08:43:22 +0000] "OPTIONS * HTTP/1.0" 200 - "-" "Apache/2.4.34 (Amazon) mod_wsgi/3.5 Python/3.6.5 (internal dummy connection)" I tried with other forms that has the almost the same logic on my website. … -
In Django , How to handle multi user types with more than 1 user has access to same content?
In a Django Application, I have a model called application.py which is created by a user say "u". I want to list all the application created by the user "u" later, so i may need to add a reference to the model application.py from user.py. I have one more requirement , as an admin , i need to provide access to any number of users to the same applications. So I assume this can be done with many to many relation.(Since users can access many applications). Now the question is , is it possible to implement this behavior with user groups ,with one group is responsible for handling one application, so that in a later point of time i can add as many users as needed from the backend to respective groups to manage the same application.? Which one is better , managing the users using many to many relation with model application.py or relating a group to application.py and managing users using groups. -
Import CSV and preprocess them before saving into database
I have a Check In & Check Out table which has the attributes as below: 'id', 'unit_id', 'guest_name', 'check_in_date', 'check_out_date', 'total_night', 'total_charges' For the unit_id attribute, it is the foreign key(unit_id) of Unit table which consist of unit_id, unit_number and property_id as foreign key of Property Table. For the property_id in Property table, it has property_name attribute as well. However, the CSV that needs to be imported into Check In & Check Out table only consist of unit_number and property_name. Therefore, I need to run query to find the property_id given the property name and then only able to retrieve unit_id given the unit_number and property_id. CSV can then be saved into database along with other attributes. I am looking at this repository but has little idea on which part to override to write the actual algorithm for it. Anyone can show me some light? Or perhaps introducing me another package that able to perform the task. Only CSV format is fine. Don't need other type of format for import. Thanks -
Django. Check if there is an instance in A with foreignkey to B
sorry but even if it's a small issue , I'm trying for more than 8 hours to solve and understand the problem. I'm trying to understand querysets with "select_related" etc. I have 3 models. Delivery, Package and Order class Order(models.Model): # a lot of fields describing the orderinformation adress = models.ForeignKey(Adress,on_delete=models.PROTECT,blank=True,null=True) class Package(models.Model): length = models.IntegerField(default=0) width = models.IntegerField(default=0) height = models.IntegerField(default=0) weight = models.IntegerField(default=0) parcel = models.IntegerField(default=0) delivery = models.ForeignKey(Delivery,on_delete=models.CASCADE) class Delivery(models.Model): adress= models.ForeignKey(Adress,on_delete=models.CASCADE,default=0) In Save-Method of Order I want to check if there exists a package which refers to the same delivery.adress as the order.adress if Package.objects.select_related('delivery').filter(delivery__adress == self.adress).exists() Problem: I want to make a queryset which does an Inner Join between Order and Package. I want to list all Packages with the orders. Like: "Select order.nr, order.price,order.package FROM order INNER JOIN package ON package.id = order.package_id. But only get Results with a Left Outer Join. I would appreciate your help. Thanks. -
Can't use def destroy viewset.viewset (soft delete)
I got this err, i already searched and get this resolved and already add date_time variable but cant and I just want to use viewset instead, please help me solve :( django.core.exceptions.FieldError: Cannot resolve keyword 'transaction' into field. Choices are: address, created_at, deleted_at, id, notification, phone_number, status, total, transactionvariant, updated_at, user, user_id here is my def destroy(views.py): class TransactionView(viewsets.ViewSet): def list(self, request): user = get_object_or_404(User, pk=request.user.id) queryset = Transaction.objects.filter(user_id=user).exclude(deleted_at__isnull=False) serializer = TransactionSerializer(queryset, many=True) return Response(serializer.data, status=200) def retrieve(self, request, pk=None): user = get_object_or_404(User, pk=request.user.id) transaction = TransactionVariant.objects.filter(transaction__pk=pk).filter(transaction__user_id=user) serializer = TransactionVariantSerializer(transaction, many=True) return Response(serializer.data) def destroy(self, request, pk=None): date_time = datetime.now() # user = get_object_or_404(User, pk=request.user.id) transaction = Transaction.objects.filter(transaction__pk=pk).update(deleted_at=date_time) serializer = TransactionSerializer(transaction, many=True) return Response(serializer.data) and my serializers.py class ProductSerializer(serializers.ModelSerializer): class Meta: model = Product fields = ('name',) class VariantSerializer(serializers.ModelSerializer): # product = ProductSerializer(many=False, read_only=True) class Meta: model = Variant fields = ('name', 'size', 'color', 'price', 'image_link',) class TransactionVariantSerializer(serializers.ModelSerializer): variant = VariantSerializer(many=False, read_only=True) # products = serializers.VariantSerializer(variant) # products = serializers.(fields='variant') class Meta: model = TransactionVariant fields = ('quantity','variant') class TransactionSerializer(serializers.ModelSerializer): transaction_id = serializers.IntegerField(source='id') # product = ProductSerializer(many=False, read_only=True) # variant = VariantSerializer(many=False, read_only=True) class Meta: model = Transaction # fields = ('transaction_id','user_id','status','total','created_at') fields = '__all__' -
How to apply partial validation in Django Models on a REST API
I'm getting started with building REST API with Django using DRF. I get that there are default validations that can be applied to fields while definig a Model class. I need to know, what should be a good approach for defing a partial validation for field. Let us consider the following Model CLass : class Test(models.Model): a = models.CharField("A", max_length=100) b = models.TextField("B", blank=True, null=True) c = models.TextField("C", null=True, blank=True) Now for field a it is a required field which is what I need, for the fields b and c, I want that either of one should be present always, that is if b is present c can be null or empty and vice-a-versa. So I read that I can write the serializer and wireup the validation code within it, also I can define a clean method within my model to provide the validation logic. Can someone provide me an example? -
How to generate plot according to the variable in dJango?
I am newbie to dJango. In my webpage, there are five choices for user to be able to select. For example, there are c1,c2,c3,c4 and c5. And if user selects c4, then the numeric values in column c4 can be seen as webpage as a graph. Above scenario is what I want to do. However, I had hard time achieving above issue. As you can see, below is my javascript code. And the variable d.c4 is hardcoded. However, I want to change it so that it can be converted according to the user select. However, I don't know how to achieve it. var line = d3.svg.line() .x(function(d,i) { return x(i)}) .y(function(d,column) { return y(d.c4);}); The values which user selected are contained in the column_json variable. var column = {{column_json|safe}} I just changed the code as below but it didn't work as I expected. var line = d3.svg.line() .x(function(d,i) { return x(i)}) .y(function(d,column) { return y(d.column);}); Any help will be appreciated. Thanks. -
Parsing Django DateTimeField in Javascript(React)
I built my backend api with django rest framework in which the model has a DateTimeField. date = models.DateTimeField(auto_now_add=True) When I get the data from the api to React I get something like this 2019-01-20T19:24:58.674435Z How can I parse this in javascript and convert to a readable form? -
Caching per-app in Django rather than per-site or per-view
Lets say I have two apps in my Django website one for the API and one for the html pages, all urls starting with /api/ are handled by the API app. I have setup two caches with a specific setup for each like so: CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.db.DatabaseCache', 'LOCATION': 'page_cache', 'TIMEOUT': 7200, 'OPTIONS': { 'MAX_ENTRIES': 300, } }, 'api': { 'BACKEND': 'django.core.cache.backends.db.DatabaseCache', 'LOCATION': 'api_cache', 'TIMEOUT': 3600, 'OPTIONS': { 'MAX_ENTRIES': 3000, } } } How would I setup so that all requests to the API use the 'api' cache and all other requests use the 'default' cache? I know I can use the cache_page function/decorator in the 'api' apps urls or views but I have a lot of urls and views so this would be annoying to maintain if I wanted to alter the timeout for instance. I am also aware that I could just customise the middleware to point to a different cache when the request starts with '/api/' but is there no cleaner way of doing this? -
'search' is decorated with takes_context=True so it must have a first argument of 'context'. Django 2.1.5
I make search with inclusion tag, but this causes an error "'search' is decorated with takes_context=True so it must have a first argument of 'context'" inclusion_tag.py @register.inclusion_tag('post/search_tpl.html', takes_context=True) def search(self, context, *args, **kwargs): request = context['request'] query = self.request.GET.get('q') founded = Post.objects.filter(Q(title__icontains=query)|Q(body__icontains=query)) return {'founded': founded} If I remove "self" - this causes an error "Cannot use None as a query value" If I sub "self" to second place - this causes en error "'search' did not receive value(s) for the argument(s): 'self'" -
RuntimeError: Table column/cell width not specified, unable to continue
I am trying to create a PDF file by using pyfpdf in python django. from fpdf import FPDF, HTMLMixin class WriteHtmlPDF(FPDF, HTMLMixin): pass html = f"""<div><table>....</table></div>""" pdf = WriteHtmlPDF() # First page pdf.add_page() pdf.write_html(html) pdf.output('html.pdf', 'F') I am using the multiple tables in my HTML code and facing the problem while creating the PDF. following is the error, which I am getting. Traceback (most recent call last): web_1 | File "/usr/local/lib/python3.6/dist-packages/fpdf/html.py", line 72, in handle_data web_1 | l = [self.table_col_width[self.table_col_index]] web_1 | IndexError: list index out of range web_1 | web_1 | During handling of the above exception, another exception occurred: web_1 | web_1 | Traceback (most recent call last): web_1 | File "/usr/local/lib/python3.6/dist-packages/django/core/handlers/exception.py", line 41, in inner web_1 | response = get_response(request) web_1 | File "/usr/local/lib/python3.6/dist-packages/django/core/handlers/base.py", line 187, in _get_response web_1 | response = self.process_exception_by_middleware(e, request) web_1 | File "/usr/local/lib/python3.6/dist-packages/django/core/handlers/base.py", line 185, in _get_response web_1 | response = wrapped_callback(request, *callback_args, **callback_kwargs) web_1 | File "/usr/local/lib/python3.6/dist-packages/django/contrib/auth/decorators.py", line 23, in _wrapped_view web_1 | return view_func(request, *args, **kwargs) web_1 | File "./eauction/views.py", line 638, in get_login_report web_1 | pdf.write_html(result_data) web_1 | File "/usr/local/lib/python3.6/dist-packages/fpdf/html.py", line 401, in write_html web_1 | h2p.feed(text) web_1 | File "/usr/lib/python3.6/html/parser.py", line 111, in feed web_1 | self.goahead(0) web_1 … -
Django - serializer validation with foreign key
I have two models to represent a Student and his Contact. class Contact(models.Model): phone_num = models.IntegerField() email = models.TextField() class Student(models.Model): name = models.TextField() age = models.IntegerField() contact = models.ForeignKey(Contact) The data structure that I needed to return with: { name: 'Peter', age: 18, contact: { phone_num: 1234567890, email: 'peter123@gmail.com' } } In my post request, I receive a json format data: { name: 'Mary', age: 19, phone_num: 9876543210, email: mary987@gmail.com } I'm trying to create a serializer for data validation. Contact: class ContactSerializer(ModelSerializer): class Meta: model = Contact exclude = ('id',) Student: class StudentSerializer(ModelSerializer): contact = ContactSerializer() class Meta: model = Student exclude = ('id',) I tried to put the post request data into the serializer and check if it's valid. data = { name: 'Mary', age: 19, phone_num: 9876543210, email: mary987@gmail.com } student = StudentSerializer(data=data) student.is_valid() // It returns false. print(student.errors) // Print: {'contact': [ErrorDetail(string='This field is required.', code='required')]} How can I valid my data with this data structure? -
Django dump data from multiple databases
I have a project with 2 different databases, both of them must be inconsistent with each other but logically they must remain separate from each other. For dumping I used to use dumpdata from django commands, but I faced with a problem for consistency, I must to define which database I want to back up and use two commands for dumping their data, such as: ./manage.py dumpdata api1 > api1.json // which is the default database ./manage.py dumpdata api2 --database api2_db > api2.json // which uses the second database I defined the routers for each database separately and defined them in a correct order in settings.py, I found this answer but it does not work for me. Is there any suggestion for dumping both databases in the same time to remain them consistent because during dumping the first database no other data must apply to the second one and vice versa, Do you recommend using a database even if they have not any relation to each other and data in the first database is general and use in all apps we are working on, but the second one is a database which is used in a certain branch of our … -
Is it possible to have my Angular frontend subscribed to my Redis Server in Django backend?
Right now I have to repeatedly call the API to check for Updates. Is it possible to have a Subscriber kind of method to invoke the API call if changes are made? Angular.js frontend and django backend server. -
Django application became slow after integrating apache webgate
I have created a Djnago application and the application was working fine until i integrated Oracle OAM Web-gate with my application. Application is working inside a docker container and i'm able to telnet all the incoming and outgoing OAM ports from docker(even though i haven't exposed any specific posts) I have no idea what happened to the application after the integration. From the first redirection to the SSO page it takes min 30 sec to load single. If i run the application using Run server the application is working fine. I'm using Server Version: Apache/2.4.6 (CentOS) mod_wsgi/4.6.5 Python/3.6 Django 1.11 Loaded modules are the following Loaded Modules apache2entry_web_gate.cpp, core.c, http_core.c, mod_access_compat.c, mod_actions.c, mod_alias.c, mod_allowmethods.c, mod_auth_basic.c, mod_auth_digest.c, mod_authn_anon.c, mod_authn_core.c, mod_authn_dbd.c, mod_authn_dbm.c, mod_authn_file.c, mod_authn_socache.c, mod_authz_core.c, mod_authz_dbd.c, mod_authz_dbm.c, mod_authz_groupfile.c, mod_authz_host.c, mod_authz_owner.c, mod_authz_user.c, mod_autoindex.c, mod_cache.c, mod_cache_disk.c, mod_cgi.c, mod_data.c, mod_dav.c, mod_dav_fs.c, mod_dav_lock.c, mod_dbd.c, mod_deflate.c, mod_dir.c, mod_dumpio.c, mod_echo.c, mod_env.c, mod_expires.c, mod_ext_filter.c, mod_filter.c, mod_headers.c, mod_include.c, mod_info.c, mod_lbmethod_bybusyness.c, mod_lbmethod_byrequests.c, mod_lbmethod_bytraffic.c, mod_lbmethod_heartbeat.c, mod_log_config.c, mod_logio.c, mod_lua.c, mod_mime.c, mod_mime_magic.c, mod_negotiation.c, mod_proxy.c, mod_proxy_ajp.c, mod_proxy_balancer.c, mod_proxy_connect.c, mod_proxy_express.c, mod_proxy_fcgi.c, mod_proxy_fdpass.c, mod_proxy_ftp.c, mod_proxy_http.c, mod_proxy_scgi.c, mod_proxy_wstunnel.c, mod_remoteip.c, mod_reqtimeout.c, mod_rewrite.c, mod_setenvif.c, mod_slotmem_plain.c, mod_slotmem_shm.c, mod_so.c, mod_socache_dbm.c, mod_socache_memcache.c, mod_socache_shmcb.c, mod_status.c, mod_substitute.c, mod_suexec.c, mod_systemd.c, mod_unique_id.c, mod_unixd.c, mod_userdir.c, mod_version.c, mod_vhost_alias.c, mod_wsgi.c, prefork.c, I have done my R&D but still failed to … -
Bootstrap Dropdown in Navbar doesn't show dropdown when clicked
I'm trying to set up a Navbar for my light control/camera monitoring system. However, for my camera dropdown whenever I go to select a specific camera, it doesn't show anything. This is running on a Win 10 machine with the latest Django and bootstrap for development. I've tried added jQuery and updating my bootstrap files. {% load staticfiles %} <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <meta charset="UTF-8"> <title>Light Control</title> <link rel="stylesheet" href="{% static 'css/bootstrap.css' %}" media="screen" type="text/css" /> <link rel="stylesheet" href="{% static 'css/style.css' %}" media="screen" type="text/css" /> <link rel="stylesheet" href="{% static 'css/bootstrap-theme.css' %}" media="screen" type="text/css" /> </head> <body> <nav class="navbar navbar-expand-lg navbar-light bg-light"> <a class="navbar-brand">Light Control</a> {% if isLogged %} <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNavDropdown" aria-controls="navbarNavDropdown" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarNavDropdown"> <ul class="navbar-nav"> <li class="nav-item"> <a class="nav-link" href="/control">Light Control<span class="sr-only">(current)</span></a> </li> <li class="nav-item dropdown"> <a class="nav-link dropdown-toggle" href="#" id="navbarDropdownMenuLink" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> Cameras </a> <div class="dropdown-menu" aria-labelledby="navbarDropdownMenuLink"> <a class="dropdown-item" href="/camera/office">Office</a> <a class="dropdown-item" href="/camera/office">ec</a> </div> </li> </ul> </div> <div> <a href="/logout/" class="btn btn-outline-danger">Log Out</a> </div> {% endif %} </nav> </body> </html> I tried to click on the button, but nothing actually shows up once I click on it. -
Unable to extends the base templates Django
I had created a base.html with the following content. {% load staticfiles %} {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Yarn Management System</title> </head> <body> <div class="content-page"> <!-- Start content --> {% block content %} {% endblock %} <!-- END content --> </div> </body> </html> Now i am trying to extends my base.html {% extends 'base.html' %} {% block content %} <h1>Content Block</h1> {% endblock %} But i am not getting required result. So please point out the mistake. -
How to implement caching on page view and render two different template(for mobile & for desktop) on same url hit?
I want to implement caching on views according to device type i.e. whether it is a mobile or a desktop. I have used mixins to detect device type and render template. -
My PostAdmin moderation class doesn't filter users' posts
I am setting up a Post administration system. So the spammers would not be able to post their junk posts on my page. I created a PostAdmin class but it is not working. Here is my admin.py from django.contrib import admin from .models import Post class PostAdmin(admin.ModelAdmin): ... def make_published(self, request, queryset): rows_updated = queryset.update(status='p') if rows_updated == 1: message_bit = "1 story was" else: message_bit = "%s stories were" % rows_updated self.message_user(request, "%s successfully marked as published." % message_bit) admin.site.register(Post, PostAdmin) Here is my models.py from django.db import models from django.utils import timezone from django.contrib.auth.models import User from django.urls import reverse STATUS_CHOICES = ( ('d', 'Draft'), ('p', 'Published'), ('w', 'Withdrawn'), ) class Post(models.Model): title = models.CharField(max_length=100) content = models.TextField() date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) status = models.CharField(max_length=10, choices= STATUS_CHOICES, default='draft') def __str__(self): return self.title def get_absolute_url(self): return reverse('post-detail', kwargs={'pk': self.pk})``` -
Embedding opencv video in html web page
I am working on a computer vision program that opens a cctv camera and detects objects in the frame. I am using opencv python for this. For the UI i am using django to create a web application. The web app contains a button which when pressed starts a live stream. While this works fine, the live stream is opened in a new window. Is there any way to embed the live stream onto the website? for example running a video in a html web page by using the video tag I looked online but could not find a proper answer to my problem. Please help me Thanks in advance -
How get and save current user ID in a TabularInline from BaseTable in django models
How to get current user ID and save in a TabularInline from a BaseTable with custom Mixin in django admin. The value pass by model is NULL. models.py class BaseTable(models.Model): created_at = models.DateTimeField(auto_now_add=True, editable=False) modified_at = models.DateTimeField(auto_now=True, editable=False) created_by = models.ForeignKey(User, on_delete=models.PROTECT, related_name='%(class)s_createdby', editable=False) modified_by = models.ForeignKey(User, on_delete=models.PROTECT ,related_name='%(class)s_modifiedby', editable=False) class Meta: abstract = True class CheckOutItem(BaseTable): // inherited admin.py First the Mixin class AuditMixin(object): def save_model(self, request, obj, form, change): if obj.created_by_id is None: obj.created_by_id = request.user.id obj.modified_by_id = request.user.id super(AuditMixin, self).save_model(request, obj, form, change) ... And the admin model class CheckOutItemInline(AuditMixin, admin.TabularInline): model = CheckOutItem extra = 1 @admin.register(CheckOut) class CheckoutAdmin(AuditMixin, admin.ModelAdmin): model = CheckOut The trace error log. IntegrityError at /admin/system/checkout/add/ (1048, "Column 'created_by_id' cannot be null") Request Method: POST Request URL: http://192.168.4.100/admin/system/checkout/add/ Django Version: 2.1.1 Exception Type: IntegrityError Exception Value: (1048, "Column 'created_by_id' cannot be null") Exception Location: /home/ricardo/www/developer/python/bmhair/env/lib/python3.6/site-packages/django/db/backends/mysql/base.py in execute, line 76 Python Executable: /usr/bin/python3 Python Version: 3.6.7 Python Path: ['/home/ricardo/www/developer/python/bmhair/framework', '/home/ricardo/www/developer/python/bmhair/env/lib/python3.6/site-packages', '/usr/lib/python36.zip', '/usr/lib/python3.6', '/usr/lib/python3.6/lib-dynload', '/usr/local/lib/python3.6/dist-packages', '/usr/lib/python3/dist-packages'] Server time: Seg, 21 Jan 2019 00:06:27 -0400 Local Vars args ("'2019-01-21 04:06:27.441238'", "'2019-01-21 04:06:27.441335'", 'NULL', 'NULL', '11', '2', "'1.00'", "'35.00'", "'35.00'") db <_mysql.connection open to 'localhost' at 7f1cc050e338> exc query (b'INSERT INTO system_checkoutitem (created_at, modified_at, created_by_' b'id, … -
First record start date, last record end date for contract of each user, and how to apply filters
I'm in a bit over my head here. I've got a table with the contract information of all employees. An employee can have multiple contracts in this table as everytime they get promoted, or are up for renewal, a new contract will be made. Apart from that there's the possibility that an employee leaves the company for any period of time, so there may be gaps between contracts. There are two things I'm trying to achieve: The average time employees stay on each jobgrade Years of service, so length of each contract from an employee combined class Contract(models.Model): user = models.ForeignKey(User, on_delete = models.CASCADE) employment = models.ForeignKey(Employment, on_delete = models.CASCADE, null = True, blank = True) jobgrade = models.ForeignKey(Jobgrade, on_delete = models.CASCADE, null = True, blank = True) contract_start = models.DateField(null = True, blank = True) contract_end = models.DateField(null = True, blank = True)