Home > database >  How to show user's information (special ID, firstName, lastname) in another template after succ
How to show user's information (special ID, firstName, lastname) in another template after succ

Time:03-03

How to show user's information (special ID, firstName, lastname) in another template after successful form submission in Django. I have a form to ask users information(general information, Education, experience) and I give random unique test_id. After the user-submitted the form successfully, I have to show his/her test_id to memorize. I didn't have an idea about view form. My solution is a bit stupid

My model:

class UserForm_uz(models.Model):

      test_id = models.CharField(default=random_string,max_length=5,editable=False,unique=True)
      rasm = models.ImageField(upload_to='media/rasmlar',null=True,blank=True)
      jobName = models.ForeignKey(Job, on_delete=models.CASCADE)
      lastName = models.CharField(max_length=200)
      firstName = models.CharField(max_length=200)
      middleName = models.CharField(max_length=200,blank=True,null=True)
      birthData = models.DateField()
      nation = models.CharField(max_length=50,blank=True,null=True)

My view:

class FormAfterView(View):

    def get(self,request):
        obj = UserForm_uz.objects.all().last()
        test_id = obj.test_id
        firstName = obj.firstName
        lastName = obj.lastName
        return render(request,"formafter.html",{"test_id":test_id,"firstName":firstName,"lastName":lastName})

CodePudding user response:

You can pass your queryset directly to your Django template and use that queryset to display data accordingly. So your function will like this...

View

class FormAfterView(View):
    def get(self,request):
        obj = UserForm_uz.objects.all().last()
        context = {
           'user_details': obj,
        }
        return render(request,"formafter.html", context)

Django Templates

<p>{{user_details.test_id}}</p>
<p>{{user_details.firstname}}</p>
........

Also, you should try to pass parameters with URLs to fetch data from models. Using obj = UserForm_uz.objects.all().last() does work but it's not the preferred way and sometimes it can give you wrong data if you placed an ordering query in your models class. What you can do is

URL file

urlpatterns = [
    path("form_after_view/<string:main_id>", views.FormAfterView, name="form_after_view"),
]

Form save view

class FormAfterView(View):

    def post(self,request):
        form = Formclass(request.POST)
        if form.is_valid():
           form.save()
           return redirect('form_after_view', form.main_id)

Next Step View

class FormAfterView(View):
      def get(self,request, main_id):
        obj = UserForm_uz.objects.get(main_id=main_id)

This will give you the exact instance that you just saved in previous step view.

  • Related