Using Javascript and AJAX in the Fetch()API method: returns no values as a response

You’ve got 8 different ForeignKey references to the same model in Table1. Are these all references to the same User? Or are they references to different Users?

If they are all references to the same User, then it should only be one ForeignKey field.

If they are references to different users, then you need to provide the related_name attribute for those foreign key fields. Also see Following relationships “backward”.

OK. thanks. below is what is in my shell:

python3 manage.py makemigrations
Migrations for 'schedule_app':
  schedule_app/migrations/0002_remove_table1_patient_scheduling_assignments_amc_099_and_more.py
    - Remove field patient_scheduling from table1
    - Add field amc_099 to assignments
    - Add field assignment to assignments
    - Add field clinical_admin_stocktake to assignments
    - Add field colpo_LEEP to assignments
    - Add field ighid_12022 to assignments
    - Add field ighid_12046 to assignments
    - Add field screening_results_reports to assignments
    - Add field sll_qHPV to assignments
    - Add field date to datemodel
    - Add field month_date to datemodel
    - Add field year_date to datemodel
    - Add field datefield to datemonthmodel
    - Add field taskstart_date to datemonthmodel
    - Add field carla_chibwesha to employees
    - Add field cassius_dintwe to employees
    - Add field employee to employees
    - Add field jermina_nkoana to employees
    - Add field lulu_lewis to employees
    - Add field mark_faesen to employees
    - Add field masangu_mulongo to employees
    - Add field nhlanhla_kgomari to employees
    - Add field noluthando_mabandla to employees
    - Add field sbu_luvuno to employees
    - Add field sophie_williams to employees
    - Add field tafadzwa_pasipamire to employees
    - Add field tumi_dlamini to employees
    - Add field April to monthdate
    - Add field August to monthdate
    - Add field February to monthdate
    - Add field January to monthdate
    - Add field July to monthdate
    - Add field June to monthdate
    - Add field March to monthdate
    - Add field May to monthdate
    - Add field November to monthdate
    - Add field October to monthdate
    - Add field September to monthdate
    - Add field monthdate to monthdate
    - Add field Week1 to quarters
    - Add field Week2 to quarters
    - Add field Week3 to quarters
    - Add field quarter to quarters
    - Add field is_active to status
    - Add field status to status
    - Add field assignment to table1
    - Alter field assignments on assignmentcategory
    - Alter field patient_scheduling on assignments
    - Alter field day_date on datemodel
    - Alter field taskend_date on datemonthmodel
    - Alter field ditiro_twala on employees
    - Alter field December on monthdate
    - Alter field Week4 on quarters
    - Alter field completed on status
(.venv) (.venv) Carlas-MacBook-Air:schedule_project andrewchibwesha$ python3 manage.py migrate
Operations to perform:
  Apply all migrations: admin, auth, contenttypes, schedule_app, sessions
Running migrations:
  Applying schedule_app.0002_remove_table1_patient_scheduling_assignments_amc_099_and_more... OK

I used:

blank=True , null=True

for each field in models.py

I am trying to see these changes on the Django Admin Site but an error that doesn’t seem right has popped up. It has field names I haven’t seen as well as a template I have never seen before and don’t recognize. ??


_str__ returned non-string (type NoneType)


TypeError: __str__ returned non-string (type NoneType)
[24/Aug/2024 12:53:27] "GET /admin/schedule_app/assignments/ HTTP/1.1" 500 389190

However, the Queryset now has values:


ssignments.objects.values()
<QuerySet [{'id': 3, 'assignment': None, 'screening_results_reports': None, 'ighid_12046': None, 'ighid_12022': None, 'amc_099': None, 'sll_qHPV': None, 'colpo_LEEP': None, 'clinical_admin_stocktake': None, 'patient_scheduling': 'patient_scheduling'}]>

?

What information do you believe this error is giving you?

OK. Without getting excited about users and admin. I just believe that in one of my models - Assignments - when a string was supposed to be returned None was returned instead.
Maybe it is a topic for later.
Side Note: In the Django Admin browser the models from my app are spelt incorrectly and I don’t know what this means, but I will look it up.
For now, I am just glad that the database has been loaded and that we are getting somewhere with arranging the view to access this.
Thanks. Maybe you can point me in the direction you would like to go ??

100% correct!

Your Assignments.__str__ method as defined above is:

def __str__(self):
    if self.assignment:
        if self.assignment == 'selectChanged':
            return 'lastAssignmentSelected'
        else: 
            return "err"

In this specific case, if the first if is false (if self.assignment:), this function will return None instead of a string. (The else: return "err" clause only applies to the inner if, if self.assignment == "selectChanged".)

So now at this point, your JavaScript in your page should be able to make a valid request, and get a valid response from your view. Is it doing that?

Hi. YES the Javascript is making the request, however the response from the view is confusing me and incorrect.
On the one hand there is the variable data which is within the view: getfirstAssignmentSelected. On the other hand there is a key that needs to be used to access selectChanged which is another variable that is supposed to return the output required after the hardcoding has been done.
I am confused because I cannot see if the eventual url which is also getfirstAssignmentSelected, or another variable like data, or an attribute_id will eventually be the reason for Django to output the selection made in the first table as selectChanged (according to the javascript and functions).
Please do try and help me here as well… I am stuck.

The output that I am getting in the table is indicating to me that if I try to access {{ form.data }} then in my schedule_app a MultiValueDict can be accessed but the values that it is reading in their at the moment are { } - meaning an empty dictionary. Maybe I need to find a way to use this dictionary properly because you stated that in the view getfirstAssignmentSelected, the response is a dictionary including:

'screening_results_reports': data.screening_results_reports

I still believe that the forms are somehow using the variable data created. I don’t believe that the form is consuming the process properly though since I begun looking for ways to include the option values that represent each selected option, but now have commented that code out.

Is it possible by adding response = and then the dictionary you’d like me to use the response instead of the dictionary or does this still mean that the dictionary needs to be loaded with such data that relates to the Assignments model ??

I believe this view is the one we are supposed to be dealing with in views.py:


def TaskSchedule(request):
    context = {}

    # create object of form
    form = FormData(request.POST or None, request.FILES or None)

    # check if form data is valid
    if form.is_valid():
        # save the form data to model
        form.save()

    context['form'] = form
    return render(request, 'main/TaskSchedule.html', context)

?

As I am saying, this might be incorrect I think

Looking at the get method using in Django, I’ve attempted to continue play around with the API in the shell. The following error might be related to how I am attempting to use the GET method with the Fetch API.

 a=Assignments.objects.get(screening_results_reports='screening_results_reports')
Traceback (most recent call last):
  File "<console>", line 1, in <module>
  File "/Users/andrewchibwesha/Visual Studio Projects/test_app/.venv/lib/python3.12/site-packages/django/db/models/manager.py", line 87, in manager_method
    return getattr(self.get_queryset(), name)(*args, **kwargs)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/Users/andrewchibwesha/Visual Studio Projects/test_app/.venv/lib/python3.12/site-packages/django/db/models/query.py", line 649, in get
    raise self.model.DoesNotExist(
schedule_app.models.Assignments.DoesNotExist: Assignments matching query does not exist.
>>> 

My data table has very simple data with no parameters as you mentioned. So when I attempt to use indexing I get:

>>> Assignments.objects.all()[2].data
Traceback (most recent call last):
  File "<console>", line 1, in <module>
  File "/Users/andrewchibwesha/Visual Studio Projects/test_app/.venv/lib/python3.12/site-packages/django/db/models/query.py", line 452, in __getitem__
    return qs._result_cache[0]
           ~~~~~~~~~~~~~~~~^^^
IndexError: list index out of range

Again, trying to address only one issue at a time.

What is the data that the view needs to return? (Identify it specifically using the names of the models.)

(None of these other topics you raise have any meaning until we’ve got the view working. Unless you’re getting the right data, trying to render the data you’re getting doesn’t help anything.)

Hi. ok. Data Models I would like the view to return are ‘Assignments’, ‘MonthDate’, and Employees. I thought of focusing on the Assignments Model for now. Does this have anything to do with making the correct call using saved data ? I’ve noticed the id’s have slightly different names because of naming convention, but yes, let’s work towards getting the view returning the data it needs to. Am I still looking for the wrong models and related saved data ?

Ok, I can see returning Assignments, because you’re passing the desired value of screening_results_reports in as the url parameter. This will allow you to identify which instance of Assignments to return.

However, I see no relationship between Assignments and either MonthDate or Employees, nor do I see a defined relationship between MonthDate and Employees, so I’m not sure how you can determine which instance of either of those two models to return.

I would eventually like to just add these other models in addition to Assignments to be able to create performance charts and an archive.
You’re right though if there is going to be any relation it still needs to be created.

I am looking this up and trying my best to use the url parameter like you say that directs this API call to a located url as opposed to other parameters (like we discussed there aren’t parameters in these fields). Unfortunately I am unable to get it right ??