Django 1.10 Python 3.5.3
使用CBV,我可以将用户登录到该站点。但是,登录后我无法让用户重定向到他们的个人资料。我希望他们在登录后转到此页面:https://example.com/profiles/user。相反,我得到了这个错误:
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
bio = models.TextField(max_length=500, blank=True)
location = models.CharField(max_length=30, blank=True)
birth_date = models.DateField(null=True, blank=True)
username = models.CharField(max_length=30,
unique = True,
default='')
email = models.EmailField(default='',
unique = True,
max_length=100)
profile_image = models.ForeignKey(Image, null=True)
slug = models.SlugField(default='')
is_active = models.BooleanField(default=True)
is_authenticated = models.BooleanField(default=True)
is_anonymous = models.BooleanField(default=False)
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['name']
@receiver(post_save, sender=User)
def create_user_profile(sender, instance, created, **kwargs):
if created:
Profile.objects.create(user=instance)
@receiver(post_save, sender=User)
def save_user_profile(sender, instance, **kwargs):
instance.profile.save()
def next_birthday(born):
today = date.today()
return today.year - born.year - ((today.month, today.day) < (born.month, born.day))
def get_absolute_url(self):
return reverse('profiles:profile', kwargs={'slug': self.slug})
def __str__(self):
return self.username
如何将用户名传递给网址?
models.py
class LoginView(FormView):
template_name = 'registration/login.html'
"""
Provides the ability to login as a user with a username and password
"""
success_url = 'profile/<slug>'
form_class = AuthenticationForm
redirect_field_name = REDIRECT_FIELD_NAME
@method_decorator(sensitive_post_parameters('password'))
@method_decorator(csrf_protect)
@method_decorator(never_cache)
def dispatch(self, request, *args, **kwargs):
# Sets a test cookie to make sure the user has cookies enabled
request.session.set_test_cookie()
return super(LoginView, self).dispatch(request, *args, **kwargs)
def form_valid(self, form):
auth_login(self.request, form.get_user())
# If the test cookie worked, go ahead and
# delete it since its no longer needed
if self.request.session.test_cookie_worked():
self.request.session.delete_test_cookie()
return super(LoginView, self).form_valid(form)
def get_success_url(self):
redirect_to = self.request.GET.get(self.redirect_field_name)
if not is_safe_url(url=redirect_to, host=self.request.get_host()):
redirect_to = self.success_url
return redirect_to
views.py
urlpatterns = [
url(r'^(?P<slug>[\w-]+)/$',
ProfileView.as_view(),
name = 'profile'),
urls.py
LOGIN_REDIRECT_URL = 'profiles:profile'
settings.py
class Program
{
static void Main(string[] args)
{
string srcfile = @"C:\Workspace\tmp\TestSTuff\bank\transactions.txt";
string transactionstr;
using (FileStream fs = new FileStream(srcfile, FileMode.Open, FileAccess.Read))
{
byte[] buffer = new byte[fs.Length];
int numtoread = (int)fs.Length;
int numread = 0;
while (numtoread > 0)
{
int n = fs.Read(buffer, numread, numtoread);
if (n == 0)
break;
numread += n;
numtoread -= n;
}
transactionstr = Encoding.Default.GetString(buffer);
}
char[] newline = { '\r','\n' };
char delim = ',';
string[] transactionstrs = transactionstr.Split(newline);
List<Transaction> transactions = new List<Transaction>();
foreach (var t in transactionstrs)
{
try
{
string[] fields = t.Split(delim);
DateTime.Parse(fields[1]);
transactions.Add(new Transaction
{
AccountNumber = int.Parse(fields[0]),
TransactionDate = DateTime.Parse(fields[1]),
TransactionAmount = double.Parse(fields[2])
});
}
catch
{
continue;
}
}
}
}
public class Transaction
{
public int AccountNumber { get; set; }
public DateTime TransactionDate { get; set; }
public double TransactionAmount { get; set; }
}
提前致谢。
答案 0 :(得分:1)
尝试在您的
中使用此功能LOGIN_REDIRECT_URL = '/accounts/home_page/<username>/'
from .views import *
from . import views
from django.conf import settings
from django.conf.urls import url
urlpatterns = [
url(r'^accounts/home_page/(?P<username>[\w-]+)/$', UserProfileView.as_view(), name='user_profile_view'),
]
class UserProfileView(View):
@method_decorator(login_required)
def get(self, request, username):
if request.user.username == username:
profile = get_object_or_404(User, user=request.user)
return render(request, 'registration/home.html', {'profile': profile})
else:
raise Http404
警告:如果对于我仍在处理的用户没有临时页面,它可能会给您404错误...