Maddie Graham
Maddie Graham

Reputation: 2177

The form editing the existing form does not save and redirects to wrong. Django

I'm trying to add an edit form to an existing model, but it does not save every time and redirects me to the home page instead of the 'account' page. What am I doing wrong? why changes in the existing model are not visible? any help will be appreciated.

views.py

def account(request):
    data_now = datetime.datetime.now().strftime("%Y-%m-%d")
    #my form
    time = get_object_or_404(Time, pk=52)
    if request.method == "POST":
        form = TimeEditForm(request.POST, instance=time)
        if form.is_valid():
            time = form.save(commit=False)
            time.save()
            return redirect('account')
    else:
        form = TimeEditForm(instance=time)


    context = {'data_now': data_now, 'time_edit_form': form}
    return render(request, 'account.html', context)

forms.py

class TimeEditForm(forms.ModelForm):
    class Meta:
        model = Time
        fields = ('compartment',)
        labels ={
            'free_or_no': 'field name in my language?'
        }

models.py

class Time(models.Model):
    day_time = models.ForeignKey(DayTime, on_delete=models.CASCADE)
    compartment = models.CharField(max_length=11)
    free_or_no = models.BooleanField(default=True)
    time_equivalent = models.IntegerField()

urls.py

urlpatterns = [
    url(r'^$', views.masseur_detail, name='masseur_detail'),
    url(r'^account$', views.account, name='account')
]

account.html

                <form action="." method="post">
                    {% csrf_token %}
                    {{ time_edit_form|crispy }}
                    <button type="submit" class="btn btn-block btn-primary"> Save</button>
                </form>

Upvotes: 0

Views: 138

Answers (1)

Daniel Roseman
Daniel Roseman

Reputation: 599490

This is quite a subtle issue.

Usually in Django it's recommended to use URLs that end with a slash - eg "/account/" - but your URL is just "/account", without the slash.

Now, when you put action="." in your form, the browser interprets this as "post to the root of the current directory". If your URL did end with a slash, that would be resolve to the same page. But because it doesn't, the browser posts to the root itself, ie "/".

The best solution is to change your URL pattern to r'^account/$'; alternatively (but not recommended) you could change your form to use action="".

Upvotes: 2

Related Questions