Check if record exists in model

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 page to see how Django will handle a majority of the work you’re doing manually.

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

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

?

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

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

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.

<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:

        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.

@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 :slight_smile:

Many thanks again for all your time and effort.

Tom

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.)

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

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

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.

Which fields? What choices?

In general, see:

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 :slight_smile:

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 ?

@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

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

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

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

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

@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')

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.)