Home > Software design >  Unable to save data in django model
Unable to save data in django model

Time:11-03

below mentioned are code complete details I have tried everything and also applied methods available on the internet but the problem still continues. I did not get any errors while submitting the form.

Model:

class Subscriber(models.Model):
    id = models.BigAutoField(primary_key=True)
    email = models.EmailField(null=False, default=1)
    date = models.DateTimeField(auto_now_add=True)

View:

from .models import Subscriber

def subscriber_view(request):
    if request.method == 'POST':
        email = request.POST.get('email')
        subscriber = Subscriber(email=email)
        subscriber.save()
    return render(request, 'homepage')

urls.py

path('', views.subscriber_view, name='subscriber'),

base.html

{% load static %}

<div class="footer-newsletter">
    <div class="container">
        <div class="row justify-content-center">
            <div class="col-lg-6">
                <h4>Join Our Newsletter</h4>
                <p>Tamen quem nulla quae legam multos aute sint culpa legam noster magna</p>
                <form method="POST" action="{% url 'subscriber' %}" id="subscriber" role="form" novalidate="novalidate" >
                    {% csrf_token %}

                    <input class="form-control" id="email" placeholder="Email Address" type="email" name="email">
                    <input type="submit" value="Subscribe">
                </form>
            </div>
        </div>
    </div>
</div>

CodePudding user response:

from the Django document https://docs.djangoproject.com/en/dev/ref/models/querysets/#create:

create(**kwargs)

A convenience method for creating an object and saving it all in one step. Thus:

p = Person.objects.create(first_name="Bruce", last_name="Springsteen")

and:

p = Person(first_name="Bruce", last_name="Springsteen")
p.save(force_insert=True)

are equivalent.

The force_insert parameter is documented elsewhere, but all it means is that a new object will always be created. Normally you won’t need to worry about this. However, if your model contains a manual primary key value that you set and if that value already exists in the database, a call to create() will fail with an IntegrityError since primary keys must be unique. Be prepared to handle the exception if you are using manual primary keys.

Due to your Subscriber model manually setting primary key as so:

class Subscriber(models.Model):
    id = models.BigAutoField(primary_key=True)

You either have to use create() or save(force_insert=True) for adding new subscriber

CodePudding user response:

I got the solution for my problem actually everything is fine with the code. I have two views that route to the same URL and it seems that due to conflicts between both the first view runs but not the second one.

  • Related