如何将Django注册模型的date_register字段值写入request.session?
How to save
date_register value to request.session["date"] in Django registration view Got it, let's sort this out for you. The date_register field uses auto_now_add=True, which means Django automatically sets this timestamp right when the object is saved to the database. So the trick is to capture the newly created Registration object after saving it, then grab its date_register value and store it in the session.
Here's how to modify your existing view code:
def get_name(request): if request.method == 'POST': user_code = generate_code(8) subject = 'code' message = user_code phone = request.POST['phone'] form = NameForm(request.POST) if form.is_valid(): date_use = form.cleaned_data.get("date_visit") time_use = form.cleaned_data.get("time_visit") purpose_use = form.cleaned_data.get("purpose") if Registration.objects.filter(date_visit=date_use, time_visit=time_use, purpose=purpose_use).count() == 0: # Capture the created Registration object instead of discarding it new_registration = Registration.objects.create( fio=request.POST['fio'], phone=request.POST['phone'], date_visit=request.POST['date_visit'], time_visit=request.POST['time_visit'], number_car=request.POST['number_car'], purpose=request.POST['purpose'], tso=request.POST['tso'] ) # Store the date_register value in session (convert to ISO string since sessions can't hold datetime objects directly) request.session["date"] = new_registration.date_register.isoformat() request.session["phone"] = phone request.session["code"] = user_code return HttpResponseRedirect('endreg') else: form = NameForm() return render(request, 'registers/detail.html', {'form': form})
Key changes explained:
- Instead of calling
Registration.objects.create(...)without assigning it to a variable, we save the result tonew_registration. This gives us access to all fields of the newly created record, including the auto-generateddate_register. - We convert the
date_registerdatetime object to an ISO-formatted string using.isoformat()because Django sessions can't store raw datetime objects directly (they require serializable data). If you need to use this value later, you can convert it back to a datetime withdatetime.datetime.fromisoformat(request.session["date"]).
That's all you need to do—now the date_register timestamp will be stored in request.session["date"] whenever a new registration is successfully created.
内容的提问来源于stack exchange,提问作者qwerty
相关产品推荐
相关产品推荐

