Django redirect url работает не так, как ожидалось
Итак, я делаю простой проект на django, в котором я, как суперпользователь, могу создавать экземпляры ресторанов, и он будет делать посадочную страницу для каждого ресторана. У меня есть две панели администратора, одна - главная, которая предназначена для суперпользователя, а другая - для владельцев ресторанов, у которых параметр is_restaurant_admin
установлен в true. Теперь проблема в том, что после stripe onboarding, когда я создаю экземпляр ресторана из панели администратора, он перенаправляет меня на http://127.0.0.1:8000/restaurant-admin/login/?next=/restaurant-admin/%3Fstripe_onboarding_completed%3Dtrue
, хотя я явно написал логику, чтобы перенаправить меня на главную страницу администратора. Может ли кто-нибудь указать, где проблема, пожалуйста? Спасибо!
Мой models.py:
class Restaurant(models.Model):
name = models.CharField(max_length=100)
email = models.EmailField()
description = models.TextField()
image = models.ImageField(upload_to='restaurant_images/')
banner_image = models.ImageField(upload_to='restaurant_images/', null=True)
primary_color = models.CharField(max_length=7) # Hex color code
secondary_color = models.CharField(max_length=7) # Hex color code
favicon = models.FileField(upload_to='restaurant_favicons/', null=True, blank=True)
about_text = models.TextField(blank=True, null=True)
map_iframe_src = models.TextField(blank=True, null=True)
slug = models.SlugField(unique=True, max_length=100, null=True)
stripe_account_id = models.CharField(max_length=255, null=True, blank=True)
stripe_account_completed = models.BooleanField(default=False)
def save(self, *args, **kwargs):
if not self.slug:
self.slug = slugify(self.name)
super().save(*args, **kwargs)
def __str__(self):
return self.name
class RestaurantUser(AbstractUser):
restaurant = models.OneToOneField(Restaurant, on_delete=models.CASCADE, null=True, blank=True)
is_restaurant_admin = models.BooleanField(default=False)
def save(self, *args, **kwargs):
if self.is_restaurant_admin:
self.is_staff = True
super().save(*args, **kwargs)
Мой admin.py:
class RestaurantAdmin(admin.ModelAdmin):
list_display = ('name', 'description', 'stripe_account_id', 'stripe_account_completed')
search_fields = ('name', 'description')
def save_model(self, request, obj, form, change):
if not obj.stripe_account_id:
account = stripe.Account.create(
type="express",
country="AU",
email=obj.email,
capabilities={"card_payments": {"requested": True}, "transfers": {"requested": True}},
)
obj.stripe_account_id = account.id
super().save_model(request, obj, form, change)
def redirect_to_stripe_onboarding(self, request, obj):
account_link = stripe.AccountLink.create(
account=obj.stripe_account_id,
refresh_url=request.build_absolute_uri(reverse('admin:index')),
return_url=request.build_absolute_uri(reverse('admin:index') + '?stripe_onboarding_completed=true'),
type='account_onboarding',
)
return redirect(account_link.url)
def response_add(self, request, obj, post_url_continue=None):
if obj.stripe_account_id and not obj.stripe_account_completed:
return self.redirect_to_stripe_onboarding(request, obj)
return super().response_add(request, obj, post_url_continue)
def response_change(self, request, obj):
if 'stripe_onboarding_completed' in request.GET:
obj.stripe_account_completed = True
obj.save()
messages.success(request, 'Stripe onboarding completed successfully!')
return redirect('admin:index')
if obj.stripe_account_id and not obj.stripe_account_completed:
return self.redirect_to_stripe_onboarding(request, obj)
return super().response_change(request, obj)
Мой admin_sites.py:
from django.contrib.admin import AdminSite
from django.contrib import admin
from .models import (
RestaurantUser, Order, Restaurant, Menu, MenuItem, OrderItem, Topping, Side, Drink, Addon, MenuItemOption, MenuItemSize
)
from django.utils.html import format_html
class RestaurantAdminSite(AdminSite):
site_header = "Restaurant Admin"
site_title = "Restaurant Admin Portal"
index_title = "Welcome to Restaurant Admin Portal"
def has_permission(self, request):
return request.user.is_active and request.user.is_restaurant_admin
restaurant_admin_site = RestaurantAdminSite(name='restaurant_admin')
Мое приложение urls.py:
from django.urls import path
from . import views
from .admin import main_admin_site
from .admin_sites import restaurant_admin_site
urlpatterns = [
path('', views.home, name="home"),
path('restaurant/<slug:restaurant_slug>/', views.restaurant_landing_page, name='restaurant_landing_page'),
path('get-menu-item-details/<int:item_id>/', views.get_menu_item_details, name='get_menu_item_details'),
path('create-order/', views.create_order, name='create_order'),
path('accounts/login/', views.UserLoginView.as_view(), name='login'),
path('accounts/register/', views.register, name='register'),
path('accounts/owner-login/', views.OwnerLoginView.as_view(), name='owner_login'),
path('accounts/logout/', views.UserLogoutView.as_view(), name='logout'),
path('accounts/owner-logout/', views.OwnerLogoutView.as_view(), name='owner_logout'),
path('admin/', main_admin_site.urls),
path('restaurant-admin/', restaurant_admin_site.urls),
path('restaurant-admins/dashboard/', views.restaurant_admin_dashboard, name='restaurant_admin_dashboard'),
path('restaurant-admins/manage-menu-items/', views.manage_menu_items, name='manage_menu_items'),
path('restaurant-admins/manage-orders/', views.manage_orders, name='manage_orders'),
]
Мой основной urls.py:
from django.contrib import admin
from django.urls import path, include
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('', include('restaurant.urls')),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)