Home > Net >  Deleting a value from database based on data coming sent from a form - Django
Deleting a value from database based on data coming sent from a form - Django

Time:03-05

I am trying to implement newsletter/email subscription for my project. I created a model which only stores the email and the timestamp and uses SendGrid to send emails to the users who subscribed.

I want to include an unsubscribe button inside the emails I send them. When the user clicks unsubscribe link in the mail it appends the id of the value in db to the url and redirects to cancelsub.html where I am accessing it.

In cancelsub.html I have a form with a submit button which when a user clicks should delete the value from db. It is not working for some reason.

Models.py--

class NewsletterUser(models.Model):
    email = models.EmailField(null=True)
    date_added =  models.DateTimeField(default=datetime.now)


    def __str__(self):
        return self.email

Views.py--

def NewsLetter(request):
    if request.method == 'POST':
        email_input = request.POST.get('email_value')
        new = NewsletterUser(email=email_input)
        new.save()
        sendEmail(email_input)
   return render(request,"pages/index.html")

def DeleteNewsLetter(request):
    if request.method == 'POST':
        del_id = request.POST.get('id_value')
        NewsletterUser.objects.filter(id= del_id).delete()
    return render(request, "newsletter/CancelSubscription.html")

cancelsub.html--

<form id="cancel-subscription-form" method="POST">
  {% csrf_token %}
  <div >
  <button  id="cancel-btn" type="submit" value="">Yes, Cancel It</button>
  </div>   
</form>

<script src="https://code.jquery.com/jquery-1.9.1.js"></script>
        
<script>
  var current_url = window.location.href
  var id = current_url.split('?')[1]
  id_int = parseInt(id)
  $("#cancel-btn").val(id_int);

  $(document).on('submit','#cancel-subscription-form',function(e){
    e.preventDefault();
    $.ajax({
                type:'POST',
                url:'{% url "DeleteNewsLetter" %}',
                data:
                {
                    id_value: parseInt($("#cancel-btn").val()),
                    csrfmiddlewaretoken:$('input[name=csrfmiddlewaretoken]').val(),
                },
                success:function(){
            
                }
                })
            });
        </script>
    </div>

urls.py--

urlpatterns = [
    path('', views.NewsLetter, name='NewsLetter'),
    path('CancelSubscription', views.CancelSubscription, name='CancelSubscription'),
    path('', views.DeleteNewsLetter, name='DeleteNewsLetter'),
]

When I execute this code out, instead of deleting the value from database, it adds a blank value into the db. I'm confused as to why this is happening.

It'd be really helpful if anyone guide me where I went wrong!. Thanks in advance!!

CodePudding user response:

I understand that the URL that you send on the email is something like this: http://mywebsite.com/unsubscribe/?9

So you get the "9" with the javascript code. You don't need the javascript if you give a name to your value like this: http://mywebsite.com/unsubscribe/?user_id=9

Now, you can just doing this:

<form id="cancel-subscription-form" method="POST" action="{% url "DeleteNewsLetter" %}">
    {% csrf_token %}
    <div >
        <button name="id_value"  id="cancel-btn" type="submit" value="{{request.GET.user_id}}">Yes, Cancel It</button>
    </div>   
</form>

I think that your problem is in the javascript code, so simplify and deleting it probably your system works.

  • Related