0

I'm working on an Django 3 app which allows users to add and remove data requests for review. The user will select the user and site from a list and depending on the availability of data will populate a date/time field to be able to select a start and end date range. I'm using the Tempus Dominus time date picker to set the available dates in the date picker and am hardcoding them for the time being. The end goal will be to query Elasticsearch for them but hardcoded is fine for now.

My question is; At the moment the form is static, meaning none of the selections change the content in other sections of the form. How can i make it dynamic so that the list of enableDates dates changes when the user selects a different user or site from the dropdown lists? Just to be clear, the list of users and sites will never change, it's just the enableDates that need to change.

I'd appreciate any help or advice.

At the moment the form for submitting a request, along with displaying any existing requests looks like:

enter image description here

This is my MODEL for storing data requests:

class DataRequest(models.Model):

USERS = [
    ('User1', 'User1'),
    ('User2', 'User2'),
    ('User3', 'User3'),
]
users = models.CharField(
    choices=USERS,
    max_length=32,
    default='User1',
)

SITE = [
    ('Site1', 'Site1'),
    ('Site2', 'Site2'),
    ('Site3', 'Site3'),
]
site =models.CharField(
    choices=SITE,
    max_length=32,
    default='Site1',
)
start = models.DateTimeField() 
end = models.DateTimeField() 
user = models.ForeignKey(CustomUser, on_delete=models.CASCADE)

def get_request(self):
    request = {
        "id": self.id,
        "users": self.users,
        "site": self.site,
        "start": self.start,
        "end": self.end,
        }
    return request

This is the FORM:

class RequestForm(ModelForm):
 start = forms.DateTimeField(
    widget=DateTimePicker(
        options={

        },
        attrs={
            'append': 'fa fa-calendar',
            'input_toggle': True,
            'icon_toggle': True,
        }
    )
 )
 end = forms.DateTimeField(
    widget=DateTimePicker(
        options={
            'useCurrent': False,
            'enabledDates':["2021-02-20",], // hard coded dates go here
        },
        attrs={
            'append': 'fa fa-calendar',
            'input_toggle': True,
            'icon_toggle': True,
        }
    )
 )

 class Meta:
    model = DataRequest
    fields = ['users','site', 'start','end']

 def __init__(self, *args, **kwargs):
    super(RequestForm, self).__init__(*args, **kwargs)
    self.fields['users'].widget.attrs.update({'class' : 'form-control'})
    self.fields['site'].widget.attrs.update({'class' : 'form-control'})

this is the VIEW for adding and removing requests, the list of existing data requests is sent over in the page context:

 def delRequest(request, pk):
    if request.method == 'POST':
        request = DataRequest.objects.get(id=pk)
        request.delete()
    return redirect('dashboard')

 def addRequest (request):
    if request.method == 'POST':  
        form = RequestForm(request.POST)
        if form.is_valid():
            DataRequest.objects.create(
                user=request.user,
                users=form.cleaned_data['users'],
                site=form.cleaned_data['site'],
                start=form.cleaned_data['start'],
                end=form.cleaned_data['end']
            )
            print("Added new Request")
            return redirect('dashboard')
  • javascript in your template is probably the way to go. – Danoram Feb 19 '21 at 17:56
  • Hi Danoram, do you mean send all the dates across to the HTML and filter on that? The issue there is that the list of potential dates is huge and could go back years for each user and site. –  Feb 19 '21 at 22:36
  • How many users and how many sites are there? – Danoram Feb 20 '21 at 10:37
  • Hi, there'll be around 10 users, all with specific site information, also around 10. The data itself is time series data in a minutes' resolution. So each user will have 10 different sites, so with a years' worth of data, that's: 525960 mins a year x 10 sites = 5259600 per user, times 10 users = 52596000 data points. Which is why i'm keen on filtering on the server side given the size. I hope that made sense. –  Feb 20 '21 at 14:54
  • Ok I think I understand your question better now. I thought you wanted to change the `enabledDates` option on the start and end datetimepickers, based on the user and site selected from the choice fields - but what you *actually* want to do is is filter some datapoints and display them in the view based on the which user/site is selected? – Danoram Feb 20 '21 at 15:00
  • The two points above sound the same to me. The main thing I'm unsure of is how the communication between the FE and backend works. I mean I could create a new POST every time the options change, but i think that would force a reload of the page which seems a bit clunky. I'm looking into Django Channels which should provide a better user experience, but that seems overkill. –  Feb 21 '21 at 18:24
  • Any way for clarity this is what i'm trying to do (rightly or wrongly). 1) The page is loaded with a set of defaults .2) The user changes the site selection. 3) somehow the backend picks this change up and runs a query against ElasticSearch. 4) I get a list of dates back from ES and update the List of enabledDates. 5) this somehow gets sent back to the FE for the user to select from. I'll update the question to make it more explicit. –  Feb 21 '21 at 18:24
  • 1
    Sounds like you need some API endpoint in your backend that you can query with ajax in the view. Have a look at `django-rest-framework` – Danoram Feb 21 '21 at 18:26
  • Excellent, thanks, I'm already using DRF and have other endpoints in the app doing other stuff. But setting up a custom endpoint sounds like its stepping out of the whole forms / templates thing that Django's got going on (which may well be the solution). Never done any ajax before so will look into that. thanks –  Feb 22 '21 at 09:44

0 Answers0