LINUX.ORG.RU

ввод даты в форме Django


0

1

вобщем заюзал такую штуку для создания профилей https://bitbucket.org/ubernostrum/django-profiles/wiki/Home но теперь выходит одна проблема , в профиле есть поле Birth_day ,его тип датетайм вот как сделать чтоб там в форме какая сама генерируется был не инпут в какой можна втулить чего угодно а выбор: месяц, дата,год.


Ответ на: комментарий от o

widget это для форм вобщето, а мне нужно как то там указать. вот собственно сам кусок виевс, я не шарю как он там понимает где какое поле и что нужно подставить


def create_profile(request, form_class=None, success_url=None,
                   template_name='profiles/create_profile.html',
                   extra_context=None):
    """
    Create a profile for the current user, if one doesn't already
    exist.
    
    If the user already has a profile, as determined by
    ``request.user.get_profile()``, a redirect will be issued to the
    :view:`profiles.views.edit_profile` view. If no profile model has
    been specified in the ``AUTH_PROFILE_MODULE`` setting,
    ``django.contrib.auth.models.SiteProfileNotAvailable`` will be
    raised.
    
    **Optional arguments:**
    
    ``extra_context``
        A dictionary of variables to add to the template context. Any
        callable object in this dictionary will be called to produce
        the end result which appears in the context.

    ``form_class``
        The form class to use for validating and creating the user
        profile. This form class must define a method named
        ``save()``, implementing the same argument signature as the
        ``save()`` method of a standard Django ``ModelForm`` (this
        view will call ``save(commit=False)`` to obtain the profile
        object, and fill in the user before the final save). If the
        profile object includes many-to-many relations, the convention
        established by ``ModelForm`` of using a method named
        ``save_m2m()`` will be used, and so your form class should
        also define this method.
        
        If this argument is not supplied, this view will use a
        ``ModelForm`` automatically generated from the model specified
        by ``AUTH_PROFILE_MODULE``.
    
    ``success_url``
        The URL to redirect to after successful profile creation. If
        this argument is not supplied, this will default to the URL of
        :view:`profiles.views.profile_detail` for the newly-created
        profile object.
    
    ``template_name``
        The template to use when displaying the profile-creation
        form. If not supplied, this will default to
        :template:`profiles/create_profile.html`.
    
    **Context:**
    
    ``form``
        The profile-creation form.
    
    **Template:**
    
    ``template_name`` keyword argument, or
    :template:`profiles/create_profile.html`.
    
    """
    try:
        profile_obj = request.user.get_profile()
        return HttpResponseRedirect(reverse('profiles_edit_profile'))
    except ObjectDoesNotExist:
        pass
    
    #
    # We set up success_url here, rather than as the default value for
    # the argument. Trying to do it as the argument's default would
    # mean evaluating the call to reverse() at the time this module is
    # first imported, which introduces a circular dependency: to
    # perform the reverse lookup we need access to profiles/urls.py,
    # but profiles/urls.py in turn imports this module.
    #
    
    if success_url is None:
        success_url = reverse('profiles_profile_detail',
                              kwargs={ 'username': request.user.username })
    if form_class is None:
        form_class = utils.get_profile_form()
    if request.method == 'POST':
        form = form_class(data=request.POST, files=request.FILES)
        if form.is_valid():
            profile_obj = form.save(commit=False)
            profile_obj.user = request.user
            profile_obj.save()
            if hasattr(form, 'save_m2m'):
                form.save_m2m()
            return HttpResponseRedirect(success_url)
    else:
        form = form_class()
    
    if extra_context is None:
        extra_context = {}
    context = RequestContext(request)
    for key, value in extra_context.items():
        context[key] = callable(value) and value() or value
    
    return render_to_response(template_name,
                              { 'form': form },
                              context_instance=context)



megido
() автор топика
Ответ на: комментарий от megido

вот как сделать чтоб там в форме какая сама генерируется был не инпут

widget это для форм вобщето, а мне нужно как то там указать.

Попроси кого-нибудь из взрослых чтоб помогли тебе нормально вопрос задать :)

o
()
Ответ на: комментарий от megido

я не шарю как он там понимает где какое поле и что нужно подставить

Ну, во-первых, у тебя есть аргумент во вью form_class, во вотрых есть такое:

    if form_class is None:
        form_class = utils.get_profile_form()

В третьих, есть https://docs.djangoproject.com/en/1.3/ref/forms/widgets/#django.forms.extras....

Дальше давай сам.

provaton ★★★★★
()
Ответ на: комментарий от megido

Блин, ты когда код копипастишь хоть читай его:

        The form class to use for validating and creating the user
        profile. This form class must define a method named
        ``save()``, implementing the same argument signature as the
        ``save()`` method of a standard Django ``ModelForm`` (this
        view will call ``save(commit=False)`` to obtain the profile
        object, and fill in the user before the final save). If the
        profile object includes many-to-many relations, the convention
        established by ``ModelForm`` of using a method named
        ``save_m2m()`` will be used, and so your form class should
        also define this method.
        
        If this argument is not supplied, this view will use a
        ``ModelForm`` automatically generated from the model specified
        by ``AUTH_PROFILE_MODULE``.

сделай ModelForm из auth.models.User, в ней пропиши соответствующий виджет, и передай эту функцию как form_class во view.

provaton ★★★★★
()
Ответ на: комментарий от provaton
import datetime
from profiles import utils
from django.forms.extras.widgets import SelectDateWidget
from django.utils.translation import ugettext as _  

year = datetime.date.today().year
  
class Bd(forms.Form):
    birth_date = forms.DateField(label=_('Birth date'), initial=datetime.date.today,  
        widget=SelectDateWidget(years=range(year, year-100, -1)))

вот такая штука работает если подтставить ее вместо

form = form_class()

но как сделать вместе с старой формой я хз

megido
() автор топика
Ответ на: комментарий от megido
        class xz(form_class):
            form_class.birth_day = forms.DateField(label=_('birth day'), initial=datetime.date.today,  
        widget=SelectDateWidget(years=range(year, year-100, -1)))

так тоже не появляется виждет

megido
() автор топика
Ответ на: комментарий от provaton
        class xz(ModelForm):
            form_class.birth_day = forms.DateField(label=_('birth_day'), initial=datetime.date.today,  
        widget=SelectDateWidget(years=range(year, year-100, -1)))

ModelForm has no model class specified.

куда там эту долбаную модель указывать?

megido
() автор топика
Ответ на: комментарий от provaton

блин неужели так трудно написать хоть что примерно нужно сделать??? у меня либо выходит ошибка , либо нет изменений

megido
() автор топика
Ответ на: комментарий от megido

С такими темпами на то, что ты там делаешь, у тебя годы уйдут.

Bers
()
Ответ на: комментарий от megido

Прежде чем пытаться использовать сторонние приложения, нужно научиться работать с основами джанги.

Нужно сделать примерно так (ты даже не показал модель профиля):

class YourProfileForm(forms.ModelForm):
  class Meta:
    model = YourProfileModel
    exclude = ('user',)
    widgets = {'date_field': SelectDateWidget()}
И передаешь это класс в качестве аргумента form_class.

gruy ★★★★★
()
Ответ на: комментарий от gruy

как в убунту перезагружусь попробую , а пока спасибо

megido
() автор топика
Ответ на: комментарий от gruy

class YourProfileForm(forms.ModelForm): class Meta: model = UserProfile exclude = ('birth_day',) widgets = {'birth_day': SelectDateWidget()}

def create_profile(request, form_class=None, success_url=None, template_name='profiles/create_profile.html', extra_context=None): if success_url is None: success_url = reverse('profiles_profile_detail', kwargs={ 'username': request.user.username }) if form_class is None: form_class = utils.get_profile_form() # form_class = AuthorForm()

# form_class = AuthorForm()

if request.method == 'POST': form = form_class(YourProfileForm,data=request.POST, files=request.FILES)

if form.is_valid(): profile_obj = form.save(commit=False) profile_obj.user = request.user profile_obj.save() if hasattr(form, 'save_m2m'): form.save_m2m() return HttpResponseRedirect(success_url) else: form = form_class()

if extra_context is None: extra_context = {} context = RequestContext(request) for key, value in extra_context.items(): context[key] = callable(value) and value() or value return render_to_response(template_name, { 'form': form }, context_instance=context)

megido
() автор топика
Ответ на: комментарий от megido

аргументом функции я тоже ставил , но тогда в форме появляется вобще хз откуда взявшийся выбор юзеров

megido
() автор топика
Ответ на: комментарий от megido

в форме появляется вобще хз откуда взявшийся выбор юзеров

Вот для скрытия этого и существует поле exclude в классе Meta.

все, работает

Покажи хоть как сделал, интересно же становится :)

gruy ★★★★★
()
Ответ на: комментарий от gruy

[code=python] class YourProfileForm(forms.ModelForm): class Meta: model = YourProfileModel exclude = ('user',) widgets = {'date_field': SelectDateWidget()} [/code]

в exclude не зная че вбивать вбил birth_day ну и вкинул YourProfileFofm как параметр, увидел список выбора юзеров, ну подумал не то. затем попробовал все таки вбить обратно user и увидел все как надо)))

megido
() автор топика
Ответ на: комментарий от gruy
class YourProfileForm(forms.ModelForm):
  class Meta:
    model = YourProfileModel
    exclude = ('user',)
    widgets = {'date_field': SelectDateWidget()}

в exclude не зная че вбивать вбил birth_day ну и вкинул YourProfileFofm как параметр, увидел список выбора юзеров, ну подумал не то. затем попробовал все таки вбить обратно user и увидел все как надо)))

megido
() автор топика
Вы не можете добавлять комментарии в эту тему. Тема перемещена в архив.