2009-11-30 9 views
0

문제점을 볼 수 있으며 코드 및 오류 페이지가 첨부되어 있습니다. 내 템플릿에서Django 리디렉션이 작동하지 않습니다.

, 내가 가진 내보기에서

{% if user.get_profile.is_store %} 
    <!--DO SOME LOGIC--> 
{%endif%} 

을, 내가 가진 :

def downloads(request): 
""" 
Downloads page, a user facing page for the trade members to downloads POS etc 
""" 
if not authenticated_user(request): 
     return HttpResponseRedirect("/professional/") 

if request.user.get_profile().is_store(): 
     return HttpResponseRedirect("/") 

user = request.user 
account = user.get_profile() 

downloads_list = TradeDownloads.objects.filter(online=1)[:6] 
downloads_list[0].get_thumbnail() 
data = {} 
data['download_list'] = downloads_list 

return render_to_response('downloads.html', data, RequestContext(request)) 

환경 :

Request Method: GET 
    Request URL: http://localhost:8000/professional/downloads 
    Django Version: 1.1.1 
    Python Version: 2.6.2 
    Installed Applications: 
    ['django.contrib.auth', 
    'django.contrib.admin', 
    'django.contrib.contenttypes', 
    'django.contrib.sessions', 
    'django.contrib.sites', 
    'sico.news', 
    'sico.store_locator', 
    'sico.css_switch', 
    'sico.professional', 
    'sico.contact', 
    'sico.shop', 
    'tinymce', 
    'captcha'] 
    Installed Middleware: 
    ('django.middleware.common.CommonMiddleware', 
    'django.contrib.sessions.middleware.SessionMiddleware', 

내 오류 보고서 :

Traceback: 
    File "/usr/local/lib/python2.6/dist-packages/django/core/handlers/base.py" in get_response 
     92.     response = callback(request, *callback_args, **callback_kwargs) 
    File "/var/www/sico/src/sico/../sico/professional/views.py" in downloads 
     78. if request.user.get_profile().is_store(): 
    File "/var/www/sico/src/sico/../sico/shop/models.py" in is_store 
     988.   return not self.account is None 
    File "/usr/local/lib/python2.6/dist-packages/django/db/models/fields/related.py" in __get__ 
     191.    rel_obj = self.related.model._base_manager.get(**params) 
    File "/usr/local/lib/python2.6/dist-packages/django/db/models/manager.py" in get 
     120.   return self.get_query_set().get(*args, **kwargs) 
    File "/usr/local/lib/python2.6/dist-packages/django/db/models/query.py" in get 
     305.      % self.model._meta.object_name) 

    Exception Type: DoesNotExist at /professional/downloads 
    Exception Value: Account matching query does not exist. 
,

내 BaseAccount 클래스

class BaseAccount(models.Model): 
user = models.ForeignKey(User, unique=True) 

def __unicode__(self): 
    """ 
    Return the unicode representation of this customer, which is the user's 
    full name, if set, otherwise, the user's username 
    """ 
    fn = self.user.get_full_name() 
    if fn: 
     return fn 
    return self.user.username 

def user_name(self): 
    """ 
    Returns the full name of the related user object 
    """ 
    return self.user.get_full_name() 

def email(self): 
    """ 
    Return the email address of the related user object 
    """ 
    return self.user.email 

def is_store(self): 
    return not self.account is None 

def is_professional(self): 
    return not self.professional is None 

내 계정 class`

lass Account(BaseAccount): 
""" 
The account is an extension of the Django user and serves as the profile 
object in user.get_profile() for shop purchases and sessions 
""" 
telephone = models.CharField(max_length=32) 
default_address = models.ForeignKey(Address, related_name='billing_account', blank=True, null=True) 
security_question = models.ForeignKey(SecurityQuestion) 
security_answer = models.CharField(max_length=200) 
how_heard = models.CharField("How did you hear about us?", max_length=100) 
feedback = models.TextField(blank=True) 
opt_in = models.BooleanField("Subscribe to mailing list", help_text="Please tick here if you would like to receive updates from %s" % Site.objects.get_current().name) 
temporary = models.BooleanField() 

def has_placed_orders(self): 
    """ 
    Returns True if the user has placed at least one order, False otherwise 
    """ 
    return self.order_set.count() > 0 

def get_last_order(self): 
    """ 
    Returns the latest order that this customer has placed. If no orders 
    have been placed, then None is returned 
    """ 
    try: 
     return self.order_set.all().order_by('-date')[0] 
    except IndexError: 
     return None 

def get_currency(self): 
    """ 
    Get the currency for this customer. If global currencies are enabled 
    (settings.ENABLE_GLOBAL_CURRENCIES) then this function will return 
    the currency related to their default address, otherwise, it returns 
    the site default 
    """ 
    if settings.ENABLE_GLOBAL_CURRENCIES: 
     return self.default_address.country.currency 
    return Currency.get_default_currency() 
currency = property(get_currency) 

def get_gateway_currency(self): 
    """ 
    Get the currency that an order will be put through protx with. If protx 
    currencies are enabled (settings.ENABLE_PROTX_CURRENCIES), then the 
    currency will be the same returned by get_currency, otherwise, the 
    site default is used 
    """ 
    if settings.ENABLE_PROTX_CURRENCIES and settings.ENABLE_GLOBAL_CURRENCIES: 
     return self.currency 
    return Currency.get_default_currency() 
gateway_currency = property(get_gateway_currency) 

`

+0

서식 파일에 템플릿 태그 ({% if ...)와 실제 다운로드보기가 모두 있습니까? 이 비트가 다른 위치에 있으면 질문에 별도의 코드 블록을 사용하십시오. 그렇지 않으면 매우 혼란스러워 보입니다. –

+0

죄송합니다. 리디렉션이 다운로드 뷰에 있으며 페이지가로드 될 때 확인이 잘못되었습니다. – Udders

+0

아마도 그럴 것입니다. 그러나 다른 코드 블록으로 보여지는 코드를 분리 할 수 ​​있다면 더 좋을 것입니다. 그렇지 않으면 혼란 스러울 것입니다. –

답변

3

self.accountis_store()을 처리하려고 할 때 존재하지 않는 Account 개체를 가리 킵니다. 외래 키 * 기침 * MySQL * 기침 *을 시행하지 않는 데이터베이스를 사용하고 있으며 데이터가 엉망이되었습니다.

0

그것은 user.get_profile() 반환 값이 비어있는 것처럼 보이고, 따라서 다음 is_store 실패() 전화 :

return not self.account is None 

비어 있습니다 (예 : 없음).

[편집] this (프로필 아래)을 읽은 후에는 해당 사용자의 프로필이 존재하지 않아서 DoesNotExist 예외가 발생합니다.

+0

스택 트레이스를 제외하면'DoesNotExist'가'is_store()'메쏘드에서 나오고'get_profile()'메쏘드에서는 나오지 않습니다. – jcdyer

+0

그게 무슨 뜻입니까? – Udders

+0

@jcd : 좋은 지적. sico87이 자신의 Account 프로필 객체 코드를 게시 할 수 있다면 좋을 것입니다. –

0

작동하지 않는 리디렉션이 아닙니다. is_store() 프로 시저 또는 존재하지 않는 프로필입니다. 정확히 self.account가 무엇인지를 확인해야합니다.
코드를 살펴보면 데이터베이스에 두 개의 테이블이 있습니다. 하나는 baseaccount로, 사용자 ID 만 저장하고 account는 account + baseaccount id와 관련된 모든 필드를 저장합니다. 당신은 내가 더는 장고 전문가 의미로 생각하지 않습니다이

def is_store(self): 
try: 
    return self.account is None 
except Account.DoesNotExist: 
    return False 

처럼 뭔가 is_store 대체하기 위해 시도 할 수 있습니다,하지만 난이 트릭을 할 수 있다고 생각.

+0

죄송합니다.이 코드를 상속했으며 장고에 익숙하지 않아서 배우고 있습니다. 어떻게 계정을 참조하는지, ObjectDoesNotExist로 어떤 작업을 수행 할 수 있습니까? – Udders

관련 문제