Can't display DateField on form with auto_now = True

后端 未结 2 707
無奈伤痛
無奈伤痛 2021-01-25 00:59

I have a model with auto_now, and auto_now_add set for Update and Create fields:

class HotelProfiles(models.Model):
  fe_result_id = models.AutoField(primary_key         


        
相关标签:
2条回答
  • 2021-01-25 01:10

    For the benefit of others, I figured out a way to do this. I'm new to Django, so if there is a better way, I'd be interested in hearing it. The view code is below. I wasn't sure if Django was not returning the fields from the query, and I found out that it was. So, something in the renderering of the form that I don't understand removed those fields so they couldn't be rendered. So, I copied them to a dict called read_only before rendering and passed it along.

    try:
        hotel_profile = HotelProfiles.objects.get(pk=hotel_id)
        read_only["created_on"] = hotel_profile.fe_created_date
        read_only["updated_on"] = hotel_profile.fe_updated_date
        f = HotelProfileForm(instance=hotel_profile)
        #f.save()
    except:
        f = HotelProfileForm()
        print 'rendering blank form'
    return render_to_response('hotels/hotelprofile_form.html', {'f' : f, 'read_only': read_only}, context_instance=RequestContext(request))
    
    0 讨论(0)
  • 2021-01-25 01:25
    • Make the fields you want readonly
    • explicitly override what fields are available in this admin form (readonly fields will be present but readonly)

    Example:

    from django.contrib import admin
    
    class HotelProfilesAdmin(admin.ModelAdmin) :
        # Keep the fields readonly
        readonly_fields = ['fe_created_date','fe_updated_date']
    
        # The fields in the order you want them
        fieldsets = (
            (None, {
                'fields': ('fe_created_date', 'fe_updated_date', ...other fields)
            }),
        )
    
    # Add your new adminform to the site
    admin.site.register(HotelProfiles, HotelProfilesAdmin)
    
    0 讨论(0)
提交回复
热议问题