Home > database >  How do I check if a record saved successfully in Django?
How do I check if a record saved successfully in Django?

Time:04-02

Could you take a look at this code below?

It seems like the form is submitted and validated successfully. However, it doesn't seem to be saving to my database. Please check my comment in the post() method below starting with #####. I know in PHP one can print_r($var); exit; but can't seem to find equivalent in Python/Django.

class ReportListView(ListView):
    model = ReportList
    form_class = ReportListForm
    initial = {}
    context_object_name = 'reportlists'
    template_name = "reports.html"

def get_context_data(self, **kwargs):
    context = super().get_context_data(**kwargs)
    #context['now'] = timezone.now()
    return context

def get_queryset(self):
    return ReportList.objects.filter(user=self.request.user)

def get(self, request, *args, **kwargs):
    form = self.form_class(initial=self.initial)
    return render(request, self.template_name, {'form': form})

def post(self, request, *args, **kwargs):
    form = self.form_class(request.POST)
    if form.is_valid():
        # process form cleaned data
        # name = form.cleaned_data.get('name')  # .lower()
        new_report = form.save(commit=False)
        new_report.user = self.request.user
        new_report.save()
        
        ### what can I write to check if new report has been saved? 
        ### also, how can I print something here to print that in the browser e.g. 
        ### print(datavariable) 
        ### exit() ?? or something to stop execution here so that I read previous print output

        return redirect('report')

    return render(request, self.template_name, {'form': form})

CodePudding user response:

I know where the problem is. If you try to print anything from get_context_data() or get_queryset() it's going to fail, because you specified your context in get() method. So both get_context_data() and get_queryset() are not going to be called. In your case what you want to do is to modify your get() method and get rid of two previous methods I mentioned, so your code in get() would look like this:

def get(self, request, *args, **kwargs):
    form = self.form_class(initial=self.initial)
    reportlists = ReportList.objects.filter(user=self.request.user)
    return render(request, self.template_name, {'form': form, 'reportlists': reportlists}})

Overwriting get() and post() is what would ultimately be the source of your template's content. Now I defined reportlists in your get() method, and sent it via context to the template, so it would be accessed under the name reportlists in the template itself. The whole code now could look like this:

class ReportListView(ListView):
    model = ReportList
    form_class = ReportListForm
    initial = {}
    template_name = "reports.html"

    def get(self, request, *args, **kwargs):
        form = self.form_class(initial=self.initial)
        reportlists = ReportList.objects.filter(user=self.request.user)
        return render(request, self.template_name, {'form': form, 'reportlists': reportlists})

    def post(self, request, *args, **kwargs):
        form = self.form_class(request.POST)
        if form.is_valid():
            # process form cleaned data
            # name = form.cleaned_data.get('name')  # .lower()
            new_report = form.save(commit=False)
            new_report.user = self.request.user
            new_report.save()
            return redirect('report')

        return render(request, self.template_name, {'form': form})

CodePudding user response:

Simply you can check if new_record has an id:

created = new_record.id

for instance:

if not created:
    raise  # or other stuff

CodePudding user response:

If the save .save() fails. Django will throw an exception. You shouldn't worry about it. but you can try performing a filter request and see if the object is created. (but it's not recommended. it will cause an additional DB hit)

  • Related