Я пишу API для сохранения данных в модели и в настоящее время имею дело с ошибкой string indices must be integers, not str
. Я искал в Интернете решения, включая множество вопросов на этом сайте, касающихся этой ошибки, и до сих пор не нашел решения. На данный момент я включил в свой код оператор try-exc, потому что сервер просто говорит, что ошибка является внутренней, а оператор try-exc дает немного больше информации о том, почему код выдает ошибку. Я дважды проверил и уверен, что мои кастинги верны. Я включил свой код ниже. Любые предложения приветствуются.
views.py
def send_data(request):
API_ENDPOINT = "http://127.0.0.1:8000/data"
my_dict = {
'eventtransactions_id': 0000111,
'profitcenter_id': 7,
'customer_gender': 'F',
'customer_firstname': 'Jan',
'customer_lastname': 'Smith',
'actualdatetime': "02-15-2020 18:54:58",
'custnum': 8880005643,
'birthdate': "02-15-2000 18:54:58",
'membertype': 'Student',
'eventname': 'Location',
},{
'eventtransactions_id': 1234567,
'profitcenter_id': 7,
'customer_gender': 'M',
'customer_firstname': 'Joe',
'customer_lastname': 'Smith',
'actualdatetime': "02-15-2020 18:54:58",
'custnum': 8880005643,
'birthdate': "07-15-1999 18:54:58",
'membertype': 'Student',
'eventname': 'Location',
}
json_dict = json.dumps(my_dict)
requests.post(API_ENDPOINT, data=json_dict)
return HttpResponse("I'm broken.")
@csrf_exempt
def receive_data(request):
if request.method == 'POST':
my_data = request.body
data = json.loads(my_data)
json_data = json.dumps(data)
try:
new_swipe = FitnessCenterSwipe.objects.create(
profitcenter_id= int(json_data['profitcenter_id']),
eventtransactions_id= int(json_data['eventtransactions_id']),
custnum= int(json_data['custnum']),
customer_lastname= json_data['customer_lastname'],
customer_firstname= json_data['customer_firstname'],
actualdatetime= datetime.datetime.strptime(json_data['actualdatetime'], '%m-%d-%Y %H:%M:%S'),
eventname= json_data['eventname'],
membertype= json_data['membertype'],
birthdate= datetime.datetime.strptime(json_data['birthdate'], '%m-%d-%Y'),
customer_gender= json_data['customer_gender'],
)
print("\n")
print("ENTRY CREATED")
except Exception as e:
print(e)
else:
print("NOT POST REQUEST")
return HttpResponse("I'm broken 1.")
models.py
class FitnessCenterSwipe(models.Model):
profitcenter_id = models.IntegerField()
eventtransactions_id = models.IntegerField() #unique?
custnum = models.IntegerField()
customer_lastname = models.CharField(max_length=150)
customer_firstname = models.CharField(max_length=150)
actualdatetime = models.DateTimeField()
eventname = models.CharField(max_length=150)
membertype = models.CharField(max_length=150)
birthdate = models.DateTimeField()
customer_gender = models.CharField(max_length=6)