S
S
stayHARD2015-08-27 10:38:28
Django
stayHARD, 2015-08-27 10:38:28

How to handle dynamic POST request Django?

Hello.
A POST request arrives in a view like this:

<QueryDict: {u'med': [u'Aspirine'], u'dates': [u'2015-08-27,2015-08-29,2015-08-31'], u'unit1': [u'gram'], u'amount1': [u'1'], u'time1': [u'06:00:00'], u'course': [u'course name'], u'amount': [u'2'], u'med1': [u'Aspirine'], u'dates1': [u'2015-08-28,2015-08-30'], u'user': [u'test'], u'time': [u'08:00:00', u'12:00:00'], u'duration': [u'7'], u'csrfmiddlewaretoken': [u'9QSTwHmYkwuuQPSB3NbaR3L5S0v2jnpI'], u'start_date': [u'2015-08-27'], u'unit': [u'pil']}>

Based on it, it is necessary to make N fields in the database.
For one, I did this:
user = get_object_or_404(User, username = request.POST.get('user'))
    # create ONE new course
    new_course = Course(title = request.POST.get('course'), start_date = datetime.datetime.strptime(request.POST.get('start_date'), "%Y-%m-%d").date(), user = user)
    new_course.save()
    # create new days, count days = duration of the course
    start_delta = datetime.datetime.strptime(request.POST.get('start_date'), "%Y-%m-%d").date()
    end_delta = start_delta + timedelta(int(request.POST.get('duration')))
    delta = end_delta - start_delta
    for date in range(delta.days + 1):
      if str(start_delta + timedelta(days = date)) in request.POST.get('dates').split(','):
        med = get_object_or_404(Med, med = request.POST.get('med'))
        new_day = Day(date = start_delta + timedelta(days = date), course_id = new_course.id)
        new_day.save()
        new_preparate = Preparate(time = str(", ".join(request.POST.getlist('time'))), amount = request.POST.get('amount'), unit = request.POST.get('unit'), day_id = new_day.id, med_id = med.id)
        new_preparate.save()
      else:
        new_day = Day(date = start_delta + timedelta(days = date), course_id = new_course.id)
        new_day.save()

In this piece of code, I find a user, assign a course (1 pc) to him. Then I assign days to the course (their number is unknown in advance. (They are entered by the user, for example 7 - then 7 days will be created that will be assigned to the course.)
Then I create "drugs" and assign them to the days that the user specifies in dates
How to do the same for only Nth number of fields.name for form
fields med, med1, med2, med3....and so on for all fields. Their number is unlimited.
Thanks in advance for any advice ;)

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
sim3x, 2015-08-27
@stayHARD

PHP style is very sad to look at in django
https://docs.djangoproject.com/en/1.8/topics/forms...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question