How can I change the url of allauth AddEmailForm?
I have a UserDetail page that includes several forms.
from allauth.account.forms import ChangePasswordForm, AddEmailForm
User = get_user_model()
class UserDetailView(LoginRequiredMixin, DetailView):
model = User
slug_field = "username"
slug_url_kwarg = "username"
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
# context["form_info_username"] =
context["form_add_mail"] = AddEmailForm(user=self.request.user)
context["form_change_password"] = ChangePasswordForm(user=self.request.user)
return context
When I add a new email:
<form method="post" action="{% url 'account_email' %}" class="add_email mt-2">
{% csrf_token %}
{{ form_add_mail|crispy }}
<div class="flex justify-end mt-2">
<button type="submit"
name="action_add"
class="bg-green-600 hover:bg-green-800 dark:bg-green-600 dark:hover:bg-green-800 font-semibold text-white rounded-sm p-2 text-xs sm:text-sm sm:px-8 ">
{% translate "Add E-mail" %}
</button>
</div>
</form>
The form/view({% url 'account_email' %}
) redirects to http://localhost:8000/de/accounts/email/, but I would prefer it to redirect to the same page where I submitted instead.
I fixed it myself.
I have created a CustomEmailView that inherits from allauth where I have overwritten the success_url.
from allauth.account.views import EmailView
class CustomEmailView(EmailView):
def get_success_url(self):
return reverse('users:detail', kwargs={'username': self.request.user.username})
Then I added this view to my app urls.py
:
app_name = "users"
urlpatterns = [
path('accounts/email/', CustomEmailView.as_view(), name='account_email')]
And changed the url in form to users:account_email
:
<form method="post" action="{% url 'users:account_email' %}"
class="add_email mt-2">
{% csrf_token %}
{{ form_add_mail|crispy }}
<div class="flex justify-end mt-2">
<button type="submit"
name="action_add"
class="bg-green-600 hover:bg-green-800 dark:bg-green-600 dark:hover:bg-green-800 font-semibold text-white rounded-sm p-2 text-xs sm:text-sm sm:px-8 ">
{% translate "Add E-mail" %}
</button>
</div>
</form>