0

Hello i'm using dates for search queries. But i am getting runtime error.

RuntimeWarning: DateTimeField Jobs.job_created_on received a naive datetime (2019-01-17 00:00:00) while time zone support is active.

Views.py

class JobListView(LoginRequiredMixin, generic.TemplateView):
    template_name = 'admin/jobs/job.html'

    def get(self, request, *args, **kwargs):
        context = super(JobListView, self).get_context_data(**kwargs)

        if 'status' in request.GET:
            form = JobSearchForm(request.GET)

            if form.is_valid():
                status = form.cleaned_data['status']
                start_date = form.cleaned_data['start_date']
                end_date = form.cleaned_data['end_date']
                company = self.request.user.userprofile.user_company

                lookups = (Q(job_company=self.request.user.userprofile.user_company) ) 

                if start_date:
                    lookups = lookups | Q(job_created_on__gte=start_date)
                if end_date:
                    lookups = lookups | Q(job_created_on__lte=end_date)

                jobs=Jobs.objects.exclude(job_is_deleted = True).filter(lookups)

        else:
            form = JobSearchForm()
            company_name = self.request.user.userprofile.user_company
            jobs = Jobs.objects.exclude(
                                job_is_deleted = True
                            ).filter(
                                job_company=self.request.user.userprofile.user_company
                            )

        return render(request, self.template_name, {'form': form, 'jobs': jobs})

Forms.py

ACTIVE_CHOICES = (
    ('AllStatus', 'Select Status'),
    ('Active', 'Active'),
    ('InActive', 'Inactive'),
)
class JobSearchForm(forms.Form):
    start_date = forms.DateField(label=False)
    end_date = forms.DateField(label=False)
    status = forms.ChoiceField(choices=ACTIVE_CHOICES, label=False, initial="")

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields['start_date'].widget.attrs['placeholder'] = 'Start Date'
        self.fields['end_date'].widget.attrs['placeholder'] = 'End Date'
        # self.fields['status'].initial = 'Select Status'
        self.fields['start_date'].widget.attrs['class'] = 'job_date'
        self.fields['end_date'].widget.attrs['class'] = 'job_date'
        self.fields['start_date'].required=False
        self.fields['end_date'].required=False

Models.py - Jobs Models

class Jobs(models.Model):
    job_created_on = models.DateTimeField(auto_now_add=True)
    job_created_by = models.ForeignKey(User, on_delete=models.CASCADE, related_name='job_created_bys')
    job_updated_on = models.DateTimeField(auto_now=True)
    job_updated_by = models.ForeignKey(User, on_delete=models.CASCADE, related_name='job_updated_bys')
    job_is_deleted = models.BooleanField(default=False)
    job_deleted_at = models.DateTimeField(blank=True, null=True)
    ACTIVE = 'Active'
    INACTIVE = 'Inactive'
    JOB_ACTIVE_CHOICES = (
        (ACTIVE, 'Active'),
        (INACTIVE, 'Inactive'),
    )
    job_status = models.CharField(
        max_length=8,
        choices=JOB_ACTIVE_CHOICES,
        default=INACTIVE,
    )

Why it is giving me runtime warning - RuntimeWarning: DateTimeField Jobs.job_created_on received a naive datetime (2019-01-17 00:00:00) while time zone support is active.

Cipher
  • 2,060
  • 3
  • 30
  • 58
  • The warning is actually for a `DateTimeField` (namely `Jobs.job_created_on`) and also quite clear. What is your question? – Fynn Becker Jan 17 '19 at 14:03
  • Possible duplicate of [RuntimeWarning: DateTimeField received a naive datetime](https://stackoverflow.com/questions/18622007/runtimewarning-datetimefield-received-a-naive-datetime) – shafik Jan 17 '19 at 14:04
  • Thats not an error, but a warning. Could you add the `Jobs` model definition? – joppich Jan 17 '19 at 14:07
  • 1
    the field `Jobs.job_created_on` is timezone aware. So when you check if `job_created_on` is greater than `start_date` which is a simple date field (not timezone aware, i.e. naive), the result might be different if the query is made by someone in Europe or someone in Australia since the date of `job_created_on` might be different (if `job_created_on` is 10pm on the 1st January 2019 GMT+1, it's 8am on the 2nd January 2019 in Australia). To avoid the warning you need to compare it to a timezone aware datetime. – dirkgroten Jan 17 '19 at 14:13
  • Here i have added Jobs model Please review it – Cipher Jan 17 '19 at 14:17

1 Answers1

3

As @dirkgroten highlighted, your form returns a Date, which doesn't have a timezone, to a timezone-aware DateTime in your model. Here is how fix that with the date lookup:

if start_date:
    lookups = lookups | Q(job_created_on__date__gte=start_date)
if end_date:
    lookups = lookups | Q(job_created_on__date__lte=end_date)
Daniel Hepper
  • 28,981
  • 10
  • 72
  • 75