# Check if record exists in model

**URL:** <https://forum.djangoproject.com/t/check-if-record-exists-in-model/10712>\
**Category:** Using Django\
**Created:** [November 28, 2021, 7:09pm UTC](https://forum.djangoproject.com/t/check-if-record-exists-in-model/10712 "2021-11-28T19:09:48Z")\
**Posts on this page:** 12\
**Page:** 4

<div class="post-metadata">

**Author:** ![KenWhitesell](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/kenwhitesell/32/280_2.png) [@KenWhitesell](https://forum.djangoproject.com/u/KenWhitesell)\
**Post date:** [December 2, 2021, 6:19pm UTC](https://forum.djangoproject.com/t/check-if-record-exists-in-model/10712/61 "2021-12-02T18:19:28Z")

</div>

Also as a side note - you’re making things a lot more difficult for yourself overall by manually rendering _all_ these form fields.

At this point you should re-review the entire [Working with forms | Django documentation | Django](https://docs.djangoproject.com/en/3.2/topics/forms/) page to see how Django will handle a majority of the work you’re doing manually.

---

<div class="post-metadata">

**Author:** ![TommyQuality](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/tommyquality/32/6302_2.png) [@TommyQuality](https://forum.djangoproject.com/u/TommyQuality)\
**Post date:** [December 2, 2021, 6:28pm UTC](https://forum.djangoproject.com/t/check-if-record-exists-in-model/10712/62 "2021-12-02T18:28:41Z")

</div>

I know, but i tried with Crispy forms and i couldn’t get the layout right. I’d much prefer to let Django render the forms for me if i could get this styling right. Although i have found a good video on this.

For some reason when i was trying to apply the css styles to crispy it wouldn’t work the same as when i apply directly in html.

w.r.t the changes.  
do i need to do this  
`Remove the project_name field from the Form class Meta. (Yes, that means replacing the __all__ with the list of fields you want editable.)`

as well as one of these

```auto
Change the attribute of this field from readonly to disabled
Change this from an input field to just a block of text

```

?

---

<div class="post-metadata">

**Author:** ![KenWhitesell](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/kenwhitesell/32/280_2.png) [@KenWhitesell](https://forum.djangoproject.com/u/KenWhitesell)\
**Post date:** [December 2, 2021, 6:37pm UTC](https://forum.djangoproject.com/t/check-if-record-exists-in-model/10712/63 "2021-12-02T18:37:34Z")

</div>

You don’t need to use Crispy forms. In fact, the form docs that I referred you to don’t involve Crispy.

> [@TommyQuality](#):
>
> w.r.t the changes.

Yes. You need to do the first, and then one of the other two.

---

<div class="post-metadata">

**Author:** ![TommyQuality](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/tommyquality/32/6302_2.png) [@TommyQuality](https://forum.djangoproject.com/u/TommyQuality)\
**Post date:** [December 2, 2021, 10:50pm UTC](https://forum.djangoproject.com/t/check-if-record-exists-in-model/10712/64 "2021-12-02T22:50:23Z")

</div>

Hi Ken,

I’ve decided to re-create all the forms etc using `ModelForm`, i just want to get your view on this so i know im going down the right route.

```auto
<form action="/your-name/" method="POST">
    {% csrf_token %}
    {{ form.non_field_errors }}
    <div class="row">
        <div class="col-lg-3">
            <div class="mb-3">
                {{ form.subject.errors }}
                <label for="{{ form.project_name.id_for_label }}">Project Name</label>
                {{ form.project_name }}
            </div>
        </div>
        <div class="col-lg-3">
            {{ form.subject.errors }}
            <label for="{{ form.project_website.id_for_label }}">Project Website</label>
            {{ form.project_website }}
        </div>
        <div class = "row align-items-center">
            <div class="col-lg-12">
                <div class="mb-3">
                    {{ form.subject.errors }}
                    <label for="{{ form.ckeditor_classic.id_for_label }}">Project Description</label>
                    {{ form.ckeditor_classic }}
                </div>
            </div>
        </div>

```

This is not the completed form, but is this correct way to do it? As i still want to use bootstrap to style? and i know i have correct the `{{ form.subject.erros }}`

Within the form im styling like this:

```auto
        widgets = {
            'project_name': forms.TextInput(attrs={'class': 'form-control'}),
            'project_website': forms.URLInput(attrs={'class': 'form-control'}),
            'project_description': forms.Textarea(attrs={'class': 'form-control'}),

```

and these views would still be valid.

```auto
@login_required
def add_fundamentals_view(request, project_id):
    project = get_object_or_404(Project, pk=project_id)
    if request.method == 'POST':
        form = AddFundamentalsForm(request.POST)
        if form.is_valid():
           fundamental = form.save(commit=False)
           fundamental.project_name = project
           fundamental.save()
           return redirect('dashboard.html')
    else:
        form = AddFundamentalsForm()
    return render(request, 'pages/add_fundamentals.html', {'project': project, "form": form})

```

But by doing this i have got the forms styled how i want them 🙂

Many thanks again for all your time and effort.

Tom

---

<div class="post-metadata">

**Author:** ![KenWhitesell](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/kenwhitesell/32/280_2.png) [@KenWhitesell](https://forum.djangoproject.com/u/KenWhitesell)\
**Post date:** [December 2, 2021, 11:02pm UTC](https://forum.djangoproject.com/t/check-if-record-exists-in-model/10712/65 "2021-12-02T23:02:32Z")

</div>

One minor question - you’re trying to render a field named `ckeditor_classic`. Unless your form field is named that, that wouldn’t be the correct reference.  
(I’m guessing that you’re trying to use the CKeditor on that field. The reference should be to the form field - the editor is the widget being used. If my guess is wrong and you do have a FormField named ckeditor, then you’re ok.)

---

<div class="post-metadata">

**Author:** ![TommyQuality](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/tommyquality/32/6302_2.png) [@TommyQuality](https://forum.djangoproject.com/u/TommyQuality)\
**Post date:** [December 4, 2021, 6:45pm UTC](https://forum.djangoproject.com/t/check-if-record-exists-in-model/10712/66 "2021-12-04T18:45:09Z")

</div>

Hi Ken,

I’ve gone back through all of my forms and recreated using `ModelForms`. Its so much quicker and easier. Thanks for pointing me in the right direction.

I am back on the fundamentals update form. The redirect is working now so if no records exist it will take me to the add page, otherwise to the update page, but for some reason the update view isn’t showing the existing values?

Im using `{{ form.project_tier_entry_level }}`

My view is

```auto
def update_fundamentals_view(request, project_id):
    project= Project.objects.get(pk=project_id)
    form = FundamentalsForm(request.POST or None, instance=project)
    if form.is_valid():
        form.save()
        return redirect('dashboard.html')
    return render(request, 'pages/update_fundamentals.html', {'project': project, "form": form})

```

I’ve made sure i’ve removed the `project_name` from the `Meta` which has worked on all my other forms. But some reason this one doesn’t see to work and it wont update the values if i make a change.

Sorry to ask for help again, but could you let me know what i am doing wrong?

And also  
within my forms i have a select feild. Where the user can choose `Yes` or `No` but i’m not sure how i pass in the choices.

`'project_tier_entry_level': forms.Select(attrs={'class': 'form-control'}),`

Thanks

---

<div class="post-metadata">

**Author:** ![TommyQuality](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/tommyquality/32/6302_2.png) [@TommyQuality](https://forum.djangoproject.com/u/TommyQuality)\
**Post date:** [December 4, 2021, 10:59pm UTC](https://forum.djangoproject.com/t/check-if-record-exists-in-model/10712/67 "2021-12-04T22:59:43Z")

</div>

Forget the view issue. i worked that out.

I should have been executing the `GET` against `Fundamentals` not `Project`

So i just need a bit of help on passing in `choices` for the `forms.Select` fields.

---

<div class="post-metadata">

**Author:** ![KenWhitesell](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/kenwhitesell/32/280_2.png) [@KenWhitesell](https://forum.djangoproject.com/u/KenWhitesell)\
**Post date:** [December 5, 2021, 12:16am UTC](https://forum.djangoproject.com/t/check-if-record-exists-in-model/10712/68 "2021-12-05T00:16:00Z")

</div>

Which fields? What choices?

In general, see:

- [Choice field](https://docs.djangoproject.com/en/3.2/ref/forms/fields/#choicefield)  
and
- [Choices](https://docs.djangoproject.com/en/3.2/ref/models/fields/#choices)

---

<div class="post-metadata">

**Author:** ![TommyQuality](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/tommyquality/32/6302_2.png) [@TommyQuality](https://forum.djangoproject.com/u/TommyQuality)\
**Post date:** [December 5, 2021, 12:20pm UTC](https://forum.djangoproject.com/t/check-if-record-exists-in-model/10712/69 "2021-12-05T12:20:41Z")

</div>

Thanks again ken. For some reason the doc i was reading it looked like i was meant to apply the choices to the form not the models. This is working now 🙂

And for my very last question…

Within my view i want present data on the screens that is only relevent to the project.  
for example, i have loads of events all relating to different projects. When i load the project details page i’d like to only show events that are related to that project ?

```auto
@login_required
def show_project_details(request,project_id):
    today = now().date()
    project = Project.objects.get(pk=project_id)
    events = Event.objects.get(pk=project_id).event_list = Event.objects.filter(event_date__gte=today).order_by('event_date')
    form = AddProjectForm(request.POST or None, instance=project)

    return render(request, 'pages/project_details.html', {"project": project, "form": form, "events": events})

```

This view returns the events in date order, but at the moment all events are being shown.

`events = Event.objects.get(pk=project_id).event_list = Event.objects.filter(event_date__gte=today).order_by('event_date')`

I tried adding the `get(pk-project_id).event_list but this didn't work. should the `project\_id` be within the filter statement?

Thanks

---

<div class="post-metadata">

**Author:** ![KenWhitesell](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/kenwhitesell/32/280_2.png) [@KenWhitesell](https://forum.djangoproject.com/u/KenWhitesell)\
**Post date:** [December 5, 2021, 12:49pm UTC](https://forum.djangoproject.com/t/check-if-record-exists-in-model/10712/70 "2021-12-05T12:49:25Z")

</div>

I’m sorry, I’m kinda lost here. What is this “Event” object? What objects are referring to it?  
I can’t find an Event model in what you’ve posted so far or what it’s related to or what’s related to it.

As far as a reverse access through a foreign key relationship goes, the primary documentation for that is here: [Related objects reference | Django documentation | Django](https://docs.djangoproject.com/en/3.2/ref/models/relations/#related-objects-reference)

---

<div class="post-metadata">

**Author:** ![TommyQuality](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/tommyquality/32/6302_2.png) [@TommyQuality](https://forum.djangoproject.com/u/TommyQuality)\
**Post date:** [December 5, 2021, 1:04pm UTC](https://forum.djangoproject.com/t/check-if-record-exists-in-model/10712/71 "2021-12-05T13:04:21Z")

</div>

Sorry Ken, this goes back to a convo we had ages ago. I forget you help out everyone.🙂

Basically i have an events model and form that enables me to add events to a project  
The event has a FK to Project, same way as fundamentals now

```auto
class Event(models.Model):

    project_name = models.ForeignKey(Project, on_delete=models.CASCADE)
    event_name = models.CharField(max_length=100)
    event_date = models.DateTimeField(blank=True)
    event_url = models.URLField(max_length=100, blank=True)

    def __str__ (self):
        return str(self.event_name)

```

and then i have a project details template that i want to show the events for this project. At the momen the events are show but for every project.

The `show_project_details` view is used to present data only relating to `project`

```auto
@login_required
def show_project_details(request,project_id):
    today = now().date()
    project = Project.objects.get(pk=project_id)
    events = Event.objects.get(pk=project_id).event_list = Event.objects.filter(event_date__gte=today).order_by('event_date')
    form = AddProjectForm(request.POST or None, instance=project)

    return render(request, 'pages/project_details.html', {"project": project, "form": form, "events": events})

```

I’m try to figure out a way to only show events relating to that project using this query?  
` events = Event.objects.get(pk=project_id).event_list = Event.objects.filter(event_date__gte=today).order_by('event_date')`

---

<div class="post-metadata">

**Author:** ![KenWhitesell](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/kenwhitesell/32/280_2.png) [@KenWhitesell](https://forum.djangoproject.com/u/KenWhitesell)\
**Post date:** [December 5, 2021, 1:58pm UTC](https://forum.djangoproject.com/t/check-if-record-exists-in-model/10712/72 "2021-12-05T13:58:19Z")

</div>

Ok, so given a project:  
`project = Project.objects.get(pk=project_id)`

The events associated with that project are:  
`event_list = project.event_set.all()`

(As documented in the link of my response prior to this one.)

[Previous page](https://forum.djangoproject.com/t/check-if-record-exists-in-model/10712.md?page=3)
