Home > Net >  Why I cannot save my template's content in my postgres database?
Why I cannot save my template's content in my postgres database?

Time:07-09

I have a model to rate a rented car in my Django project. However, when I submit the template's content, it seems that they are saved in the database but when I check in my data base, the table is empty. I've check all my code, I cannot find the error. Please, here are my model, views, the urls and my template respectively.

Model:

class tb_CARS_COMMENTS(models.Model):
    SCORE_CHOICES = zip(range(6), range(6) )
    nom_client = models.CharField(max_length=250)
    vehicule = models.ForeignKey(tb_CARS, on_delete=models.CASCADE, null=True)
    qualite = models.PositiveSmallIntegerField(choices=SCORE_CHOICES, blank=False)
    prix = models.PositiveSmallIntegerField(choices=SCORE_CHOICES, blank=False)
    confort = models.PositiveSmallIntegerField(choices=SCORE_CHOICES, blank=False)
    conduite = models.PositiveSmallIntegerField(choices=SCORE_CHOICES, blank=False)
    email = models.EmailField(max_length=254)
    site_web = models.CharField(max_length=250, null=True, blank=True)
    Commentaires = models.TextField()
    
    def __str__(self):
        return 'Évaluation(Véhicule ='  str(self.vehicule) ', Qualité ='  str(self.qualite)\
         ', Prix ='  str(self.prix) ', Confort ='  str(self.confort) ', Conduite ='  str(self.conduite) ')'

    class Meta:
        verbose_name='COMMENTAIRE'
        verbose_name_plural='COMMENTAIRES'

The views:

def AddComment(request):
    detail=get_object_or_404(tb_CARS_CONDITIONS,id=id)
    form=CARS_COMMENTForm(request.POST or None)
    if request.method == 'POST':
        if form.is_valid():
            print('Hello chef')
            obj, created = tb_CARS_COMMENTS.objects.update_or_create(
            vehicule=detail.vehicule_id,
            nom_client=request.GET.get('nom_client'),
            qualite=request.GET.get('qualite'),
            prix=request.GET.get('prix'),
            confort=request.GET.get('confort'),
            conduite=request.GET.get('conduite'),
            email=request.GET.get('email'),
            site_web=request.GET.get('site_web'),
            Commentaires=request.GET.get('Commentaires')
            )

        else:
            print('We are not reaching here')
            
    context={
        }
    return render(request,'Cars/comments.html', context )

The urls:

app_name = 'website'
urlpatterns = [
    path('', views.HompePage, name='home_page'),
    path('about_page/', views.AboutPage, name='about_page'),
    path('contact_page/', views.ContactPage, name='contact_page'),
    path('service_page/', views.ServicePage, name='service_page'),
    path('liste_voiture/', views.ListeVoiture, name='liste_voirute'),
    path('vehicule/<int:id>/detail/', views.DetailsVoiture, name='vehicule_detail'),
    path('addComments/', views.AddComment, name='add_comments'),
]

The template:

<!-- Car Review Form-->
    <div >
                    <h2 >Rédiger un commentaire</h2>
                    <form action='' method="post">
                        {% csrf_token %}
                        <div >
                            <div >
                                <div >
                                    <label>Qualité:</label>
                                    <div >
                                        <input name="qualite"  type="hidden"/>
                                        <div ></div>
                                    </div>
                                </div>
                            </div>
                            <div >
                                <div >
                                    <label>Prix:</label>
                                    <div >
                                        <input name="prix"  type="hidden"/>
                                        <div ></div>
                                    </div>
                                </div>
                            </div>
                            <div >
                                <div >
                                    <label>Comfort:</label>
                                    <div >
                                        <input name="confort"  type="hidden"/>
                                        <div ></div>
                                    </div>
                                </div>
                            </div>
                            <div >
                                <div >
                                    <label>Conduite:</label>
                                    <div >
                                        <input name="conduite"  type="hidden"/>
                                        <div ></div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div >
                            <div >
                                <input type="text" placeholder="Nom complet" name="nom_client">
                            </div>
                            <div >
                                <input type="email" placeholder="Email" name="email">
                            </div>
                            <div >
                                <input type="url" placeholder="Site web optionnel" name="site_web">
                            </div>
                            <div >
                                <input type="text" placeholder="Test" name="test">
                            </div>
                        </div>
                        <textarea cols="30" rows="10" placeholder="Redigez votre commentaire" name="Commentaires"></textarea>
                        <div >
                            <input  type="submit" value="Envoyer">
                        </div>
                    </form>
                </div>
            <!-- End Car Review Form-->

Hopefully you will find where I've have made the mistakes.

CodePudding user response:

First you have to add the car ID to your URL patterns and the AddComment view.

Second I would suggest to display the form error messages, to see if the input is valid or if there are any issues.

Third you should use create() instead of update_or_create(), as you like to add new comments if the form was sent and not update existing ones.

Assigning the ForeignKey value instead of the related object

app_name = 'website'
urlpatterns = [
    path('', views.HompePage, name='home_page'),
    path('about_page/', views.AboutPage, name='about_page'),
    path('contact_page/', views.ContactPage, name='contact_page'),
    path('service_page/', views.ServicePage, name='service_page'),
    path('liste_voiture/', views.ListeVoiture, name='liste_voirute'),
    path('vehicule/<int:id>/detail/', views.DetailsVoiture, name='vehicule_detail'),
    path('vehicule/<int:car_id>/addComments/', views.AddComment, name='add_comments'),
]
def AddComment(request, car_id):
    detail=get_object_or_404(tb_CARS_CONDITIONS,id=car_id)
    form=CARS_COMMENTForm(request.POST or None)
    if request.method == 'POST':
        if form.is_valid():
            print('Hello chef')
            obj = tb_CARS_COMMENTS.objects.create(
                vehicule_id=detail.vehicule_id,
                nom_client=request.GET.get('nom_client'),
                qualite=request.GET.get('qualite'),
                prix=request.GET.get('prix'),
                confort=request.GET.get('confort'),
                conduite=request.GET.get('conduite'),
                email=request.GET.get('email'),
                site_web=request.GET.get('site_web'),
                Commentaires=request.GET.get('Commentaires')
            )
        else:
            print('We are not reaching here')
            
    context = {'form': form}
    return render(request,'Cars/comments.html', context )
<!-- Car Review Form-->
<div >
    <h2 >Rédiger un commentaire</h2>
    <form action='' method="post">
        {% csrf_token %}

        <!-- error reporting -->
        {{ form.non_field_errors }}
        {% for field in form %}
          {% if field.errors %}
            <p >{{ field.errors }}</p>
          {% endif %}
        {% endfor %}

        <!-- ... rest of your form template -->

    </form>
</div>
<!-- End Car Review Form-->
  • Related