Search Results

Search found 126 results on 6 pages for 'manytomanyfield'.

Page 5/6 | < Previous Page | 1 2 3 4 5 6  | Next Page >

  • django/python: is one view that handles two sibling models a good idea?

    - by clime
    I am using django multi-table inheritance: Video and Image are models derived from Media. I have implemented two views: video_list and image_list, which are just proxies to media_list. media_list returns images or videos (based on input parameter model) for a certain object, which can be of type Event, Member, or Crag. The view alters its behaviour based on input parameter action (better name would be mode), which can be of value "edit" or "view". The problem is that I need to ask whether the input parameter model contains Video or Image in media_list so that I can do the right thing. Similar condition is also in helper method media_edit_list that is called from the view. I don't particularly like it but the only alternative I can think of is to have separate (but almost the same) logic for video_list and image_list and then probably also separate helper methods for videos and images: video_edit_list, image_edit_list, video_view_list, image_view_list. So four functions instead of just two. That I like even less because the video functions would be very similar to the respective image functions. What do you recommend? Here is extract of relevant parts: http://pastebin.com/07t4bdza. I'll also paste the code here: #urls url(r'^media/images/(?P<rel_model_tag>(event|member|crag))/(?P<rel_object_id>\d+)/(?P<action>(view|edit))/$', views.image_list, name='image-list') url(r'^media/videos/(?P<rel_model_tag>(event|member|crag))/(?P<rel_object_id>\d+)/(?P<action>(view|edit))/$', views.video_list, name='video-list') #views def image_list(request, rel_model_tag, rel_object_id, mode): return media_list(request, Image, rel_model_tag, rel_object_id, mode) def video_list(request, rel_model_tag, rel_object_id, mode): return media_list(request, Video, rel_model_tag, rel_object_id, mode) def media_list(request, model, rel_model_tag, rel_object_id, mode): rel_model = tag_to_model(rel_model_tag) rel_object = get_object_or_404(rel_model, pk=rel_object_id) if model == Image: star_media = rel_object.star_image else: star_media = rel_object.star_video filter_params = {} if rel_model == Event: filter_params['event'] = rel_object_id elif rel_model == Member: filter_params['members'] = rel_object_id elif rel_model == Crag: filter_params['crag'] = rel_object_id media_list = model.objects.filter(~Q(id=star_media.id)).filter(**filter_params).order_by('date_added').all() context = { 'media_list': media_list, 'star_media': star_media, } if mode == 'edit': return media_edit_list(request, model, rel_model_tag, rel_object_id, context) return media_view_list(request, model, rel_model_tag, rel_object_id, context) def media_view_list(request, model, rel_model_tag, rel_object_id, context): if request.is_ajax(): context['base_template'] = 'boxes/base-lite.html' return render(request, 'media/list-items.html', context) def media_edit_list(request, model, rel_model_tag, rel_object_id, context): if model == Image: get_media_edit_record = get_image_edit_record else: get_media_edit_record = get_video_edit_record media_list = [get_media_edit_record(media, rel_model_tag, rel_object_id) for media in context['media_list']] if context['star_media']: star_media = get_media_edit_record(context['star_media'], rel_model_tag, rel_object_id) else: star_media = None json = simplejson.dumps({ 'star_media': star_media, 'media_list': media_list, }) return HttpResponse(json, content_type=json_response_mimetype(request)) def get_image_edit_record(image, rel_model_tag, rel_object_id): record = { 'url': image.image.url, 'name': image.title or image.filename, 'type': mimetypes.guess_type(image.image.path)[0] or 'image/png', 'thumbnailUrl': image.thumbnail_2.url, 'size': image.image.size, 'id': image.id, 'media_id': image.media_ptr.id, 'starUrl':reverse('image-star', kwargs={'image_id': image.id, 'rel_model_tag': rel_model_tag, 'rel_object_id': rel_object_id}), } return record def get_video_edit_record(video, rel_model_tag, rel_object_id): record = { 'url': video.embed_url, 'name': video.title or video.url, 'type': None, 'thumbnailUrl': video.thumbnail_2.url, 'size': None, 'id': video.id, 'media_id': video.media_ptr.id, 'starUrl': reverse('video-star', kwargs={'video_id': video.id, 'rel_model_tag': rel_model_tag, 'rel_object_id': rel_object_id}), } return record # models class Media(models.Model, WebModel): title = models.CharField('title', max_length=128, default='', db_index=True, blank=True) event = models.ForeignKey(Event, null=True, default=None, blank=True) crag = models.ForeignKey(Crag, null=True, default=None, blank=True) members = models.ManyToManyField(Member, blank=True) added_by = models.ForeignKey(Member, related_name='added_images') date_added = models.DateTimeField('date added', auto_now_add=True, null=True, default=None, editable=False) class Image(Media): image = ProcessedImageField(upload_to='uploads', processors=[ResizeToFit(width=1024, height=1024, upscale=False)], format='JPEG', options={'quality': 75}) thumbnail_1 = ImageSpecField(source='image', processors=[SmartResize(width=178, height=134)], format='JPEG', options={'quality': 75}) thumbnail_2 = ImageSpecField(source='image', #processors=[SmartResize(width=256, height=192)], processors=[ResizeToFit(height=164)], format='JPEG', options={'quality': 75}) class Video(Media): url = models.URLField('url', max_length=256, default='') embed_url = models.URLField('embed url', max_length=256, default='', blank=True) author = models.CharField('author', max_length=64, default='', blank=True) thumbnail = ProcessedImageField(upload_to='uploads', processors=[ResizeToFit(width=1024, height=1024, upscale=False)], format='JPEG', options={'quality': 75}, null=True, default=None, blank=True) thumbnail_1 = ImageSpecField(source='thumbnail', processors=[SmartResize(width=178, height=134)], format='JPEG', options={'quality': 75}) thumbnail_2 = ImageSpecField(source='thumbnail', #processors=[SmartResize(width=256, height=192)], processors=[ResizeToFit(height=164)], format='JPEG', options={'quality': 75}) class Crag(models.Model, WebModel): name = models.CharField('name', max_length=64, default='', db_index=True) normalized_name = models.CharField('normalized name', max_length=64, default='', editable=False) type = models.IntegerField('crag type', null=True, default=None, choices=crag_types) description = models.TextField('description', default='', blank=True) country = models.ForeignKey('country', null=True, default=None) #TODO: make this not null when db enables it latitude = models.FloatField('latitude', null=True, default=None) longitude = models.FloatField('longitude', null=True, default=None) location_index = FixedCharField('location index', length=24, default='', editable=False, db_index=True) # handled by db, used for marker clustering added_by = models.ForeignKey('member', null=True, default=None) #route_count = models.IntegerField('route count', null=True, default=None, editable=False) date_created = models.DateTimeField('date created', auto_now_add=True, null=True, default=None, editable=False) last_modified = models.DateTimeField('last modified', auto_now=True, null=True, default=None, editable=False) star_image = models.ForeignKey('Image', null=True, default=None, related_name='star_crags', on_delete=models.SET_NULL) star_video = models.ForeignKey('Video', null=True, default=None, related_name='star_crags', on_delete=models.SET_NULL)

    Read the article

  • django/python: is one view that handles two separate models a good idea?

    - by clime
    I am using django multi-table inheritance: Video and Image are models derived from Media. I have implemented two views: video_list and image_list, which are just proxies to media_list. media_list returns images or videos (based on input parameter model) for a certain object, which can be of type Event, Member, or Crag. It alters its behaviour based on input parameter action, which can be either "edit" or "view". The problem is that I need to ask whether the input parameter model contains Video or Image in media_list so that I can do the right thing. Similar condition is also in helper method media_edit_list that is called from the view. I don't particularly like it but the only alternative I can think of is to have separate logic for video_list and image_list and then probably also separate helper methods for videos and images: video_edit_list, image_edit_list, video_view_list, image_view_list. So four functions instead of just two. That I like even less because the video functions would be very similar to the respective image functions. What do you recommend? Here is extract of relevant parts: http://pastebin.com/07t4bdza. I'll also paste the code here: #urls url(r'^media/images/(?P<rel_model_tag>(event|member|crag))/(?P<rel_object_id>\d+)/(?P<action>(view|edit))/$', views.video_list, name='image-list') url(r'^media/videos/(?P<rel_model_tag>(event|member|crag))/(?P<rel_object_id>\d+)/(?P<action>(view|edit))/$', views.image_list, name='video-list') #views def image_list(request, rel_model_tag, rel_object_id, action): return media_list(request, Image, rel_model_tag, rel_object_id, action) def video_list(request, rel_model_tag, rel_object_id, action): return media_list(request, Video, rel_model_tag, rel_object_id, action) def media_list(request, model, rel_model_tag, rel_object_id, action): rel_model = tag_to_model(rel_model_tag) rel_object = get_object_or_404(rel_model, pk=rel_object_id) if model == Image: star_media = rel_object.star_image else: star_media = rel_object.star_video filter_params = {} if rel_model == Event: filter_params['media__event'] = rel_object_id elif rel_model == Member: filter_params['media__members'] = rel_object_id elif rel_model == Crag: filter_params['media__crag'] = rel_object_id media_list = model.objects.filter(~Q(id=star_media.id)).filter(**filter_params).order_by('media__date_added').all() context = { 'media_list': media_list, 'star_media': star_media, } if action == 'edit': return media_edit_list(request, model, rel_model_tag, rel_model_id, context) return media_view_list(request, model, rel_model_tag, rel_model_id, context) def media_view_list(request, model, rel_model_tag, rel_object_id, context): if request.is_ajax(): context['base_template'] = 'boxes/base-lite.html' return render(request, 'media/list-items.html', context) def media_edit_list(request, model, rel_model_tag, rel_object_id, context): if model == Image: get_media_record = get_image_record else: get_media_record = get_video_record media_list = [get_media_record(media, rel_model_tag, rel_object_id) for media in context['media_list']] if context['star_media']: star_media = get_media_record(star_media, rel_model_tag, rel_object_id) star_media['starred'] = True else: star_media = None json = simplejson.dumps({ 'star_media': star_media, 'media_list': media_list, }) return HttpResponse(json, content_type=json_response_mimetype(request)) # models class Media(models.Model, WebModel): title = models.CharField('title', max_length=128, default='', db_index=True, blank=True) event = models.ForeignKey(Event, null=True, default=None, blank=True) crag = models.ForeignKey(Crag, null=True, default=None, blank=True) members = models.ManyToManyField(Member, blank=True) added_by = models.ForeignKey(Member, related_name='added_images') date_added = models.DateTimeField('date added', auto_now_add=True, null=True, default=None, editable=False) def __unicode__(self): return self.title def get_absolute_url(self): return self.image.url if self.image else self.video.embed_url class Image(Media): image = ProcessedImageField(upload_to='uploads', processors=[ResizeToFit(width=1024, height=1024, upscale=False)], format='JPEG', options={'quality': 75}) thumbnail_1 = ImageSpecField(source='image', processors=[SmartResize(width=178, height=134)], format='JPEG', options={'quality': 75}) thumbnail_2 = ImageSpecField(source='image', #processors=[SmartResize(width=256, height=192)], processors=[ResizeToFit(height=164)], format='JPEG', options={'quality': 75}) class Video(Media): url = models.URLField('url', max_length=256, default='') embed_url = models.URLField('embed url', max_length=256, default='', blank=True) author = models.CharField('author', max_length=64, default='', blank=True) thumbnail = ProcessedImageField(upload_to='uploads', processors=[ResizeToFit(width=1024, height=1024, upscale=False)], format='JPEG', options={'quality': 75}, null=True, default=None, blank=True) thumbnail_1 = ImageSpecField(source='thumbnail', processors=[SmartResize(width=178, height=134)], format='JPEG', options={'quality': 75}) thumbnail_2 = ImageSpecField(source='thumbnail', #processors=[SmartResize(width=256, height=192)], processors=[ResizeToFit(height=164)], format='JPEG', options={'quality': 75}) class Crag(models.Model, WebModel): name = models.CharField('name', max_length=64, default='', db_index=True) normalized_name = models.CharField('normalized name', max_length=64, default='', editable=False) type = models.IntegerField('crag type', null=True, default=None, choices=crag_types) description = models.TextField('description', default='', blank=True) country = models.ForeignKey('country', null=True, default=None) #TODO: make this not null when db enables it latitude = models.FloatField('latitude', null=True, default=None) longitude = models.FloatField('longitude', null=True, default=None) location_index = FixedCharField('location index', length=24, default='', editable=False, db_index=True) # handled by db, used for marker clustering added_by = models.ForeignKey('member', null=True, default=None) #route_count = models.IntegerField('route count', null=True, default=None, editable=False) date_created = models.DateTimeField('date created', auto_now_add=True, null=True, default=None, editable=False) last_modified = models.DateTimeField('last modified', auto_now=True, null=True, default=None, editable=False) star_image = models.OneToOneField('Image', null=True, default=None, related_name='star_crags', on_delete=models.SET_NULL) star_video = models.OneToOneField('Video', null=True, default=None, related_name='star_crags', on_delete=models.SET_NULL)

    Read the article

  • How to filter queryset in changelist_view in django admin?

    - by minder
    Let's say I have a site where Users can add Entries through admin panel. Each User has his own Category he is responsible for (each Category has an Editor assigned through ForeingKey/ManyToManyField). When User adds Entry, I limit the choices by using EntryAdmin like this: class EntryAdmin(admin.ModelAdmin): (...) def formfield_for_foreignkey(self, db_field, request, **kwargs): if db_field.name == 'category': if request.user.is_superuser: kwargs['queryset'] = Category.objects.all() else: kwargs['queryset'] = Category.objects.filter(editors=request.user) return db_field.formfield(**kwargs) return super(EntryAdmin, self).formfield_for_foreignkey(db_field, request, **kwargs) This way I can limit the categories to which a User can add Entry and it works perfect. Now the tricky part: On the Entry changelist/action page I want to show only those Entries which belong to current User's Category. I tried to do this using this method: def changelist_view(self, request, extra_context=None): if not request.user.is_superuser: self.queryset = self.queryset.filter(editors=request.user) But I get this error: AttributeError: 'function' object has no attribute 'filter' This is strange, because I thought it should be a typical QuerySet. Basically such methods are not well documented and digging through tons of Django code is not my favourite sport. Any ideas how can I achieve my goal?

    Read the article

  • Django User M2M relationship

    - by Antonio
    When trying to syncdb with the following models: class Contact(models.Model): user_from = models.ForeignKey(User,related_name='from_user') user_to = models.ForeignKey(User, related_name='to_user') class Meta: unique_together = (('user_from', 'user_to'),) User.add_to_class('following', models.ManyToManyField('self', through=Contact, related_name='followers', symmetrical=False)) I get the following error: Error: One or more models did not validate: auth.user: Accessor for m2m field 'following' clashes with related m2m field 'User.followers'. Add a related_name argument to the definition for 'following'. auth.user: Reverse query name for m2m field 'following' clashes with related m2m field 'User.followers'. Add a related_name argument to the definition for 'following'. auth.user: The model User has two manually-defined m2m relations through the model Contact, which is not permitted. Please consider using an extra field on your intermediary model instead. auth.user: Accessor for m2m field 'following' clashes with related m2m field 'User.followers'. Add a related_name argument to the definition for 'following'. auth.user: Reverse query name for m2m field 'following' clashes with related m2m field 'User.followers'. Add a related_name argument to the definition for 'following'.

    Read the article

  • Migration for creating and deleting model in South

    - by Almad
    I've created a model and created initial migration for it: db.create_table('tvguide_tvguide', ( ('id', models.AutoField(primary_key=True)), ('date', models.DateField(_('Date'), auto_now=True, db_index=True)), )) db.send_create_signal('tvguide', ['TVGuide']) models = { 'tvguide.tvguide': { 'channels': ('models.ManyToManyField', ["orm['tvguide.Channel']"], {'through': "'ChannelInTVGuide'"}), 'date': ('models.DateField', ["_('Date')"], {'auto_now': 'True', 'db_index': 'True'}), 'id': ('models.AutoField', [], {'primary_key': 'True'}) } } complete_apps = ['tvguide'] Now, I'd like to drop it: db.drop_table('tvguide_tvguide') However, I have also deleted corresponding model. South (at least 0.6.2) is however trying to access it: (venv)[almad@eva-03 project]$ ./manage.py migrate tvguide Running migrations for tvguide: - Migrating forwards to 0002_removemodels. > tvguide: 0001_initial Traceback (most recent call last): File "./manage.py", line 27, in <module> execute_from_command_line() File "/usr/lib/python2.6/site-packages/django/core/management/__init__.py", line 353, in execute_from_command_line utility.execute() File "/usr/lib/python2.6/site-packages/django/core/management/__init__.py", line 303, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/usr/lib/python2.6/site-packages/django/core/management/base.py", line 195, in run_from_argv self.execute(*args, **options.__dict__) File "/usr/lib/python2.6/site-packages/django/core/management/base.py", line 222, in execute output = self.handle(*args, **options) File "/home/almad/projects/mypage-all/lib/python2.6/site-packages/south/management/commands/migrate.py", line 91, in handle skip = skip, File "/home/almad/projects/mypage-all/lib/python2.6/site-packages/south/migration.py", line 581, in migrate_app result = run_forwards(mapp, [mname], fake=fake, db_dry_run=db_dry_run, verbosity=verbosity) File "/home/almad/projects/mypage-all/lib/python2.6/site-packages/south/migration.py", line 388, in run_forwards verbosity = verbosity, File "/home/almad/projects/mypage-all/lib/python2.6/site-packages/south/migration.py", line 287, in run_migrations orm = klass.orm File "/home/almad/projects/mypage-all/lib/python2.6/site-packages/south/orm.py", line 62, in __get__ self.orm = FakeORM(*self._args) File "/home/almad/projects/mypage-all/lib/python2.6/site-packages/south/orm.py", line 45, in FakeORM _orm_cache[args] = _FakeORM(*args) File "/home/almad/projects/mypage-all/lib/python2.6/site-packages/south/orm.py", line 106, in __init__ self.models[name] = self.make_model(app_name, model_name, data) File "/home/almad/projects/mypage-all/lib/python2.6/site-packages/south/orm.py", line 307, in make_model tuple(map(ask_for_it_by_name, bases)), File "/home/almad/projects/mypage-all/lib/python2.6/site-packages/south/utils.py", line 23, in ask_for_it_by_name ask_for_it_by_name.cache[name] = _ask_for_it_by_name(name) File "/home/almad/projects/mypage-all/lib/python2.6/site-packages/south/utils.py", line 17, in _ask_for_it_by_name return getattr(module, bits[-1]) AttributeError: 'module' object has no attribute 'TVGuide' Is there a way around?

    Read the article

  • How do I reference Django Model from another model

    - by user313943
    Im looking to create a view in the admin panel for a test program which logs Books, publishers and authors (as on djangoproject.com) I have the following two models defined. class Author(models.Model): first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) email = models.EmailField() def __unicode__(self): return u'%s %s' % (self.first_name, self.last_name) class Book(models.Model): title = models.CharField(max_length=100) authors = models.ManyToManyField(Author) publisher = models.ForeignKey(Publisher) publication_date = models.DateField() def __unicode__(self): return self.title What I want to do, is change the Book model to reference the first_name of any authors and show this using admin.AdminModels. #Here is the admin model I've created. class BookAdmin(admin.ModelAdmin): list_display = ('title', 'publisher', 'publication_date') # Author would in here list_filter = ('publication_date',) date_hierarchy = 'publication_date' ordering = ('-publication_date',) fields = ('title', 'authors', 'publisher', 'publication_date') filter_horizontal = ('authors',) raw_id_fields = ('publisher',) As I understand it, you cannot have two ForeignKeys in the same model. Can anyone give me an example of how to do this? I've tried loads of different things and its been driving me mad all day. Im pretty new to Python/Django. Just to be clear - I'd simply like the Author(s) First/Last name to appear alongside the book title and publisher name. Thanks

    Read the article

  • Django Forms - change the render multiple select widget

    - by John
    Hi, In my model I have a manytomany field mentors = models.ManyToManyField(MentorArea, verbose_name='Areas', blank=True) In my form I want to render this as: drop down box with list of all MentorArea objects which has not been associated with the object. Next to that an add button which will call a javascript function which will add it to the object. Then under that a ul list which has each selected MentorArea object with a x next to it which again calls a javascript function which will remove the MentorArea from the object. I know that to change how an field element is rendered you create a custom widget and override the render function and I have done that to create the add button. class AreaWidget(widgets.Select): def render(self, name, value, attrs=None, choices=()): jquery = u''' <input class="button def" type="button" value="Add" id="Add Area" />''' output = super(AreaWidget, self).render(name, value, attrs, choices) return output + mark_safe(jquery) However I don't know how to list the currently selected ones underneath as a list. Can anyone help me? Also what is the best way to filter down the list so that it only shows MentorArea objects which have not been added? I currently have the field as mentors = forms.ModelMultipleChoiceField(queryset=MentorArea.objects.all(), widget = AreaWidget, required=False) but this shows all mentors no matter if they have been added or not. Thanks

    Read the article

  • Formatting inline many-to-many related models presented in django admin

    - by Jonathan
    I've got two django models (simplified): class Product(models.Model): name = models.TextField() price = models.IntegerField() class Invoice(models.Model): company = models.TextField() customer = models.TextField() products = models.ManyToManyField(Product) I would like to see the relevant products as a nice table (of product fields) in an Invoice page in admin and be able to link to the individual respective Product pages. My first thought was using the admin's inline - but django used a select box widget per related Product. This isn't linked to the Product pages, and also as I have thousands of products, and each select box independently downloads all the product names, it quickly becomes unreasonably slow. So I turned to using ModelAdmin.filter_horizontal as suggested here, which used a single instance of a different widget, where you have a list of all Products and another list of related Products and you can add\remove products in the later from the former. This solved the slowness, but it still doesn't show the relevant Product fields, and it ain't linkable. So, what should I do? tweak views? override ModelForms? I Googled around and couldn't find any example of such code...

    Read the article

  • Django form linking 2 models by many to many field.

    - by Ed
    I have two models: class Actor(models.Model): name = models.CharField(max_length=30, unique = True) event = models.ManyToManyField(Event, blank=True, null=True) class Event(models.Model): name = models.CharField(max_length=30, unique = True) long_description = models.TextField(blank=True, null=True) I want to create a form that allows me to identify the link between the two models when I add a new entry. This works: class ActorForm(forms.ModelForm): class Meta: model = Actor The form includes both name and event, allowing me to create a new Actor and simultaneous link it to an existing Event. On the flipside, class EventForm(forms.ModelForm): class Meta: model = Event This form does not include an actor association. So I am only able to create a new Event. I can't simultaneously link it to an existing Actor. I tried to create an inline formset: EventFormSet = forms.models.inlineformset_factory(Event, Actor, can_delete = False, extra = 2, form = ActorForm) but I get an error <'class ctg.dtb.models.Actor'> has no ForeignKey to <'class ctg.dtb.models.Event'> This isn't too surprising. The inlineformset worked for another set of models I had, but this is a different example. I think I'm going about it entirely wrong. Overall question: How can I create a form that allows me to create a new Event and link it to an existing Actor?

    Read the article

  • How make this special many2many fields validation using Django ORM?

    - by e-satis
    I have the folowing model: class Step(models.Model): order = models.IntegerField() latitude = models.FloatField() longitude = models.FloatField() date = DateField(blank=True, null=True) class Journey(models.Model): boat = models.ForeignKey(Boat) route = models.ManyToManyField(Step) departure = models.ForeignKey(Step, related_name="departure_of", null=True) arrival = models.ForeignKey(Step, related_name="arrival_of", null=True) I would like to implement the following check: # If a there is less than one step, raises ValidationError. routes = tuple(self.route.order_by("date")) if len(routes) <= 1: raise ValidationError("There must be at least two setps in the route") # save the first and the last step as departure and arrival self.departure = routes[0] self.arrival = routes[-1] # departure and arrival must at least have a date if not (self.departure.date or self.arrival.date): raise ValidationError("There must be an departure and an arrival date. " "Please set the date field for the first and last Step of the Journey") # departure must occurs before arrival if not (self.departure.date > self.arrival.date): raise ValidationError("Departure must take place the same day or any date before arrival. " "Please set accordingly the date field for the first and last Step of the Journey") I tried to do that by overloading save(). Unfortunately, Journey.route is empty in save(). What's more, Journey.id doesn't exists yet. I didn't try django.db.models.signals.post_save but suppose it will fail because Journey.route is empty as well (when does this get filled anyway?). I see a solution in django.db.models.signals.m2m_changed but there are a lot of steps (thousands), and I want to avoid to perform an operation for every single of them.

    Read the article

  • Django ModelForm is giving me a validation error that doesn't make sense

    - by River Tam
    I've got a ModelForm based on a Picture. class Picture(models.Model): name = models.CharField(max_length=100) pub_date = models.DateTimeField('date published') tags = models.ManyToManyField('Tag', blank=True) content = models.ImageField(upload_to='instaton') def __unicode__(self): return self.name class PictureForm(forms.ModelForm): class Meta: model = Picture exclude = ('pub_date','tags') That's the model and the ModelForm, of course. def submit(request): if request.method == 'POST': # if the form has been submitted form = PictureForm(request.POST) if form.is_valid(): return HttpResponseRedirect('/django/instaton') else: form = PictureForm() # blank form return render_to_response('instaton/submit.html', {'form': form}, context_instance=RequestContext(request)) That's the view (which is being correctly linked to by urls.py) Right now, I do nothing when the form submits. I just check to make sure it's valid. If it is, I forward to the main page of the app. <form action="/django/instaton/submit/" method="post"> {% csrf_token %} {{ form.as_p }} <input type="submit" value"Submit" /> </form> And there's my template (in the correct location). When I try to actually fill out the form and just validate it, even if I do so correctly, it sends me back to the form and says "This field is required" between Name and Content. I assume it's referring to Content, but I'm not sure. What's my problem? Is there a better way to do this?

    Read the article

  • Django m2m form appearing fields

    - by dana
    I have a classroom application,and a follow relation. Users can follow each other and can create classrooms.When a user creates a classroom, he can invite only the people that are following him. The Classroom model is a m2m to User table. i have in models. py: class Classroom(models.Model): creator = models.ForeignKey(User) classname = models.CharField(max_length=140, unique = True) date = models.DateTimeField(auto_now=True) open_class = models.BooleanField(default=True) members = models.ManyToManyField(User,related_name="list of invited members") and in models.py of the follow application: class Relations(models.Model): initiated_by = models.ForeignKey(User, editable=False) date_initiated = models.DateTimeField(auto_now=True, editable = False) follow = models.ForeignKey(User, editable = False, related_name = "follow") date_follow = models.DateTimeField(auto_now=True, editable = False) and in views.py of the classroom app: def save_classroom(request, username): if request.method == 'POST': u = User.objects.get(username=username) form = ClassroomForm(request.POST, request.FILES) if form.is_valid(): new_obj = form.save(commit=False) new_obj.creator = request.user r = Relations.objects.filter(initiated_by = request.user) # new_obj.members = new_obj.save() return HttpResponseRedirect('.') else: form = ClassroomForm() return render_to_response('classroom/classroom_form.html', { 'form': form, }, context_instance=RequestContext(request)) i'm using a ModelForm for the classroom form, and the default view, taking in consideration my many to many relation with User table, in the field Members, is a list of all Users in my database. But i only want in that list the users that are in a follow relationship with the logged in user - the one who creates the classroom. How can i do that? Thanks!

    Read the article

  • Creating form using Generic_inlineformset_factory from the Model Form

    - by Prateek
    hello dear all, I wanted to create a edit form with the help of ModelForm. and my models contain a Generic relation b/w classes, so if any one could suggest me the view and a bit of template for the purpose I would be very thankful, as I am new to the language. My models look like:- class Employee(Person): nickname = models.CharField(_('nickname'), max_length=25, null=True, blank=True) blood_type = models.CharField(_('blood group'), max_length=3, null=True, blank=True, choices=BLOOD_TYPE_CHOICES) marital_status = models.CharField(_('marital status'), max_length=1, null=True, blank=True, choices=MARITAL_STATUS_CHOICES) nationality = CountryField(_('nationality'), default='IN', null=True, blank=True) about = models.TextField(_('about'), blank=True, null=True) dependent = models.ManyToManyField(Dependent, through='DependentRelationship') pan_card_number = models.CharField(_('PAN card number'), max_length=50, blank=True, null=True) policy_number = models.CharField(_('policy number'), max_length=50, null=True, blank=True) # code specific details user = models.OneToOneField(User, blank=True, null=True, verbose_name=_('user')) class Person(models.Model): """Person model""" title = models.CharField(_('title'), max_length=20, null=True, blank=True) first_name = models.CharField(_('first name'), max_length=100) middle_name = models.CharField(_('middle name'), max_length=100, null=True, blank=True) last_name = models.CharField(_('last name'), max_length=100, null=True, blank=True) suffix = models.CharField(_('suffix'), max_length=20, null=True, blank=True) slug = models.SlugField(_('slug'), max_length=50, unique=True) class PhoneNumber(models.Model) : phone_number = generic.GenericRelation('PhoneNumber') email_address = generic.GenericRelation('EmailAddress') address = generic.GenericRelation('Address') date_of_birth = models.DateField(_('date of birth'), null=True, blank=True) gender = models.CharField(_('gender'), max_length=1, null=True, blank=True, choices=GENDER_CHOICES) content_type = models.ForeignKey(ContentType, If anyone could suggest me a link or so. it would be a great help........

    Read the article

  • django class with an array of "parent" foreignkeys issue

    - by user298032
    Let's say I have a class called Fruit with child classes of the different kinds of Fruit with their own specific attributes, and I want to collect them in a FruitBasket: class Fruit(models.Model):     type = models.CharField(max_length=120,default='banana',choices=FRUIT_TYPES)     ... class Banana(Fruit):     """banana (fruit type)"""     length = models.IntegerField(blank=True, null=True)     ... class Orange(Fruit):     """orange (fruit type)"""     diameter = models.IntegerField(blank=True, null=True)     ... class FruitBasket(models.Model):     fruits = models.ManyToManyField(Fruit)     ... The problem I seem to be having is when I retrieve and inspect the Fruits in a FruitBasket, I only retrieve the Fruit base class and can't get at the Fruit child class attributes. I think I understand what is happening--when the array is retrieved from the database, the only fields that are retrieved are the Fruit base class fields. But is there some way to get the child class attributes as well without multiple expensive database transactions? (For example, I could get the array, then retrieve the child Fruit classes by the id of each array element). thanks in advance, Chuck

    Read the article

  • Select those objects whose related objects IDs are *all* in given string

    - by Jannis
    Hi Django people, I want to build a frontend to a recipe database which enables the user to search for a list of recipes which are cookable with the ingredients the user supplies. I have the following models class Ingredient(models.Model): name = models.CharField(max_length=100, unique=True) slug = models.SlugField(max_length=100, unique=True) importancy = models.PositiveSmallIntegerField(default=4) […] class Amount(models.Model): recipe = models.ForeignKey('Recipe') ingredient = models.ForeignKey(Ingredient) […] class Rezept(models.Model): name = models.CharField(max_length=100) slug = models.SlugField() instructions = models.TextField() ingredients = models.ManyToManyField(Ingredient, through=Amount) […] and a rawquery which does exactly what I want: It gets all the recipes whose required ingredients are all contained in the list of strings that the user supplies. If he supplies more than necessary, it's fine too. query = "SELECT *, COUNT(amount.zutat_id) AS selected_count_ingredients, (SELECT COUNT(*) FROM amount WHERE amount.recipe_id = amount.id) AS count_ingredients FROM amount LEFT OUTER JOIN amount ON (recipe.id = recipe.recipe_id) WHERE amount.ingredient_id IN (%s) GROUP BY amount.id HAVING count_ingredient=selected_count_ingredient" % ",".join([str(ingredient.id) for ingredient in ingredients]) rezepte = Rezept.objects.raw(query) Now, what I'm looking for is a way that does not rely on .raw() as I would like to do it purely with Django's queryset methods. Additionally, it would be awesome if you guys knew a way of including the ingredient's importancy in the lookup so that a recipe is still shown as a result even though one of its ingredients (that has an importancy of 0) is not supplied by the user.

    Read the article

  • Django Database design -- Is this a good stragety for overriding defaults

    - by rh0dium
    Hi SO's I have a question on good database design practices and I would like to leverage you guys for pointers. The project started out simple. Hey we have a bunch of questions we want answered for every project (no problem) Which turned into... Hey we have so many questions can we group them into sections (yup we can do that) Which lead into.. Can we weight these questions and I don't really want some of these questions for my project (Yes but we are getting difficult) And then I'm thinking they will want to have each section have it's own weight.. Requirements So there's the requirements - For n number of project Allow a admin member the ability select the questions for a project Allow the admin member to re-weigh or use the default weights for the questions Allow the admin member to re-weight the sections Allow team members to answer the questions. So here is what I came up with. Please feel free to comment and provide better examples models.py from django.db import models from django.contrib.sites.models import Site from django.conf import settings class Section(models.Model): """ This describes the various sections for a checklist: """ name = models.CharField(max_length=64) description = models.TextField() class Question(models.Model): """ This simply provides a simple way to list out the questions. """ question = models.CharField(max_length=255) answer_type = models.CharField(max_length=16) description = models.TextField() section = models.ForeignKey(Section) class ProjectQuestion(models.Model): """ These are the questions relevant to the project """ question = models.ForeignKey(Question) answer = models.CharField(max_length=255) required = models.BooleanField(default=True) weight = models.FloatField(default = XXX) class Project(models.Model): """ Here is where we want to gather our questions """ questions = models.ManyToManyField(ProjectQuestion) Immediate questions: - When I start a project - any ideas on how to "pre-populate" the questions (and ultimately the weights) for the project? - Is there a generally accepted method for doing this process that I am missing? Basically the idea that you refer to the questions overide your own default weight, and store the answer? - It appears that a good chuck of the work will be done in the views and that a lot of checking will need to occur there? Is that OK? Again - feel free to give me better strategies!! Thanks

    Read the article

  • Working with extra fields in an Inline form - save_model, save_formset, can't make sense of the diff

    - by magicrebirth
    Suppose I am in the usual situation where there're extra fields in the many2many relationship: class Person(models.Model): name = models.CharField(max_length=128) class Group(models.Model): name = models.CharField(max_length=128) members = models.ManyToManyField(Person, through='Membership') class Membership(models.Model): person = models.ForeignKey(Person) group = models.ForeignKey(Group) date_joined = models.DateField() invite_reason = models.CharField(max_length=64) # other models which are unrelated to the ones above.. class Trip(models.Model): placeVisited = models.ForeignKey(Place) visitor = models.ForeignKey(Person) pleasuretrip = models.Boolean() class Place(models.Model): name = models.CharField(max_length=128) I want to add some extra fields in the Membership form that gets displayed through the Inline. These fields basically are a shortcut to the instantiation of another model (Trip). Trip can have its own admin views, but these shortcuts are needed because when my project partners are entering 'Membership' data in the system they happen to have also the 'Trip' information handy (and also because some of the info in Membership can just be copied over to Trip etc. etc.). So all I want to have is two extra fields in the Membership Inline - placeVisited and pleasuretrip - which together with the Person instance will let me instantiate the Trip model in the background... I found out I can easily add extra fields to the inline view by defining my own form. But once the data have been entered, how and when to reference to them in order to perform the save operations I need to do? class MyForm(forms.ModelForm): place = forms.ModelChoiceField(required=False, queryset=Place.objects.all(), label="place",) pleasuretrip = forms.BooleanField(required=False, label="...") class MembershipInline(admin.TabularInline): model = Membership form = MyForm def save_model(self, request, obj, form, change): place = form.place pleasuretrip = form.pleasuretrip person = form.person .... # now I can create Trip instances with those data .... obj.save() class GroupAdmin(admin.ModelAdmin): model = Group .... inlines = (MembershipInline,) This doesn't seem to work... I'm also a bit puzzled by the save_formset method... maybe is that the one I should be using? Many thanks in advance for the help!!!!

    Read the article

  • Dynamically setting the queryset of a ModelMultipleChoiceField to a custom recordset

    - by Daniel Quinn
    I've seen all the howtos about how you can set a ModelMultipleChoiceField to use a custom queryset and I've tried them and they work. However, they all use the same paradigm: the queryset is just a filtered list of the same objects. In my case, I'm trying to get the admin to draw a multiselect form that instead of using usernames as the text portion of the , I'd like to use the name field from my account class. Here's a breakdown of what I've got: # models.py class Account(models.Model): name = models.CharField(max_length=128,help_text="A display name that people understand") user = models.ForeignKey(User, unique=True) # Tied to the User class in settings.py class Organisation(models.Model): administrators = models.ManyToManyField(User) # admin.py from django.forms import ModelMultipleChoiceField from django.contrib.auth.models import User class OrganisationAdminForm(forms.ModelForm): def __init__(self, *args, **kwargs): from ethico.accounts.models import Account self.base_fields["administrators"] = ModelMultipleChoiceField( queryset=User.objects.all(), required=False ) super(OrganisationAdminForm, self).__init__(*args, **kwargs) class Meta: model = Organisation This works, however, I want queryset above to draw a selectbox with the Account.name property and the User.id property. This didn't work: queryset=Account.objects.all().order_by("name").values_list("user","name") It failed with this error: 'tuple' object has no attribute 'pk' I figured that this would be easy, but it's turned into hours of dead-ends. Anyone care to shed some light?

    Read the article

  • How to get a template tag to auto-check a checkbox in Django

    - by Daniel Quinn
    I'm using a ModelForm class to generate a bunch of checkboxes for a ManyToManyField but I've run into one problem: while the default behaviour automatically checks the appropriate boxes (when I'm editing an object), I can't figure out how to get that information in my own custom templatetag. Here's what I've got in my model: ... from django.forms import CheckboxSelectMultiple, ModelMultipleChoiceField interests = ModelMultipleChoiceField(widget=CheckboxSelectMultiple(), queryset=Interest.objects.all(), required=False) ... And here's my templatetag: @register.filter def alignboxes(boxes, cls): """ Details on how this works can be found here: http://docs.djangoproject.com/en/1.1/howto/custom-template-tags/ """ r = "" i = 0 for box in boxes.field.choices.queryset: r += "<label for=\"id_%s_%d\" class=\"%s\"><input type=\"checkbox\" name=\"%s\" value=\"%s\" id=\"id_%s_%d\" /> %s</label>\n" % ( boxes.name, i, cls, boxes.name, box.id, boxes.name, i, box.name ) i = i + 1 return mark_safe(r) The thing is, I'm only doing this so I can wrap some simpler markup around these boxes, so if someone knows how to make that happen in an easier way, I'm all ears. I'd be happy with knowing a way to access whether or not a box should be checked though.

    Read the article

  • How to provide an inline model field with a queryset choices without losing field value for inline r

    - by Judith Boonstra
    The code displayed below is providing the choices I need for the app field, and the choices I need for the attr field when using Admin. I am having a problem with the attr field on the inline form for already saved records. The attr selected for these saved does show in small print above the field, but not within the field itself. # MODELS: Class Vocab(models.Model): entity = models.Charfield, max_length = 40, unique = True) Class App(models.Model): name = models.ForeignKey(Vocab, related_name = 'vocab_appname', unique = True) app = SelfForeignKey('self, verbose_name = 'parent', blank = True, null = True) attr = models.ManyToManyField(Vocab, related_name = 'vocab_appattr', through ='AppAttr' def parqs(self): a method that provides a queryset consisting of available apps from vocab, excluding self and any apps within the current app's dependent line. def attrqs(self): a method that provides a queryset consisting of available attr from vocab excluding those already selected by current app, 2) those already selected by any apps within the current app's parent line, and 3) those selected by any apps within the current app's dependent line. Class AppAttr(models.Model): app = models.ForeignKey(App) attr = models.ForeignKey(Vocab) # FORMS: from models import AppAttr def appattr_form_callback(instance, field, *args, **kwargs) if field.name = 'attr': if instance: return field.formfield(queryset = instance.attrqs(), *kwargs) return field.formfield(*kwargs) # ADMIN: necessary imports class AppAttrInline(admin.TabularInline): model = AppAttr def get_formset(self, request, obj = None, **kwargs): kwargs['formfield_callback'] = curry(appattr_form_callback, obj) return super(AppAttrInline, self).get_formset(request, obj, **kwargs) class AppForm(forms.ModelForm): class Meta: model = App def __init__(self, *args, **kwargs): super(AppForm, self).__init__(*args, **kwargs) if self.instance.id is None: working = App.objects.all() else: thisrec = App.objects.get(id = self.instance.id) working = thisrec.parqs() self.fields['par'].queryset = working class AppAdmin(admin.ModelAdmin): form = AppForm inlines = [AppAttrInline,] fieldsets = .......... necessary register statements

    Read the article

  • Connecting a django application to a drupal database?

    - by Hans
    I have a 3 - 4000 nodes in a drupal 6 installation on mysql and want to access these data through my django application. I have used manage.py inspectdb to get a skeleton of a model structure. I guess that there are good/historical reasons for drupal's database schemes, but find that there are some hard to understand structure and that there are some challenges in applying django models on the database. Some experiences this far are: node and node revision are intertwined and I solved this by using a OneToOneField (don't need the versions). This meens that the node's body gets accessible through node.vid.body, but it works. Foreign keys need to define the proper db_column to sort out the primary keys. Terms need to use an intermediary table with ManyToManyField.through. Drupal stores both the original and the thumbnailed/resized versions of any image as files in the files table. Does anyone have experiences in accessing drupal data in django? Are there better solution to for example the node <- node revision relationship? Drupal stores time/dates as unix-style timestamps in integerfields. Any recommendations? How about time zones?

    Read the article

  • reverse many to many fields in Django + count them

    - by cleliodpaula
    I'm trying to figure out how to solve this class Item(models.Model): type = models.ForeignKey(Type) name = models.CharField(max_lenght = 10) ... class List(models.Model): items = models.ManyToManyField(Item) ... I want to count how many an Item appears in another Lists, and show on template. view def items_by_list(request, id_): list = List.objects.get(id = id_) qr = list.items.all() #NOT TESTED num = [] i = 0 for item in qr: num[i] = List.objects.filter(items__id = item__id ).count() #FINISH NOT TESTED c = {} c.update(csrf(request)) c = {'request':request, 'list' : qr, 'num' : num} return render_to_response('items_by_list.html', c, context_instance=RequestContext(request)) template {% for dia in list %} <div class="span4" > <div> <h6 style="color: #9937d8">{{item.type.description}}</h6> <small style="color: #b2e300">{{ item.name }}</small> <small style="color: #b2e300">{{COUNT HOW MANY TIMES THE ITEM APPEAR ON OTHER LISTS}}</small> </div> {% endfor %} This seems to be easy, but I could not implement yet. If anyone has some glue to me, please help me. Thanks in advance.

    Read the article

  • Django: What's an awesome plugin to maintain images in the admin?

    - by meder
    I have an articles entry model and I have an excerpt and description field. If a user wants to post an image then I have a separate ImageField which has the default standard file browser. I've tried using django-filebrowser but I don't like the fact that it requires django-grappelli nor do I necessarily want a flash upload utility - can anyone recommend a tool where I can manage image uploads, and basically replace the file browse provided by django with an imagepicking browser? In the future I'd probably want it to handle image resizing and specify default image sizes for certain article types. Edit: I'm trying out adminfiles now but I'm having issues installing it. I grabbed it and added it to my python path, added it to INSTALLED_APPS, created the databases for it, uploaded an image. I followed the instructions to modify my Model to specify adminfiles_fields and registered but it's not applying in my admin, here's my admin.py for articles: from django.contrib import admin from django import forms from articles.models import Category, Entry from tinymce.widgets import TinyMCE from adminfiles.admin import FilePickerAdmin class EntryForm( forms.ModelForm ): class Media: js = ['/media/tinymce/tiny_mce.js', '/media/tinymce/load.js']#, '/media/admin/filebrowser/js/TinyMCEAdmin.js'] class Meta: model = Entry class CategoryAdmin(admin.ModelAdmin): prepopulated_fields = { 'slug': ['title'] } class EntryAdmin( FilePickerAdmin ): adminfiles_fields = ('excerpt',) prepopulated_fields = { 'slug': ['title'] } form = EntryForm admin.site.register( Category, CategoryAdmin ) admin.site.register( Entry, EntryAdmin ) Here's my Entry model: class Entry( models.Model ): LIVE_STATUS = 1 DRAFT_STATUS = 2 HIDDEN_STATUS = 3 STATUS_CHOICES = ( ( LIVE_STATUS, 'Live' ), ( DRAFT_STATUS, 'Draft' ), ( HIDDEN_STATUS, 'Hidden' ), ) status = models.IntegerField( choices=STATUS_CHOICES, default=LIVE_STATUS ) tags = TagField() categories = models.ManyToManyField( Category ) title = models.CharField( max_length=250 ) excerpt = models.TextField( blank=True ) excerpt_html = models.TextField(editable=False, blank=True) body_html = models.TextField( editable=False, blank=True ) article_image = models.ImageField(blank=True, upload_to='upload') body = models.TextField() enable_comments = models.BooleanField(default=True) pub_date = models.DateTimeField(default=datetime.datetime.now) slug = models.SlugField(unique_for_date='pub_date') author = models.ForeignKey(User) featured = models.BooleanField(default=False) def save( self, force_insert=False, force_update= False): self.body_html = markdown(self.body) if self.excerpt: self.excerpt_html = markdown( self.excerpt ) super( Entry, self ).save( force_insert, force_update ) class Meta: ordering = ['-pub_date'] verbose_name_plural = "Entries" def __unicode__(self): return self.title Edit #2: To clarify I did move the media files to my media path and they are indeed rendering the image area, I can upload fine, the <<<image>>> tag is inserted into my editable MarkItUp w/ Markdown area but it isn't rendering in the MarkItUp preview - perhaps I just need to apply the |upload_tags into that preview. I'll try adding it to my template which posts the article as well.

    Read the article

  • django image upload forms

    - by gramware
    I am having problems with django forms and image uploads. I have googled, read the documentations and even questions ere, but cant figure out the issue. Here are my files my models class UserProfile(User): """user with app settings. """ DESIGNATION_CHOICES=( ('ADM', 'Administrator'), ('OFF', 'Club Official'), ('MEM', 'Ordinary Member'), ) onames = models.CharField(max_length=30, blank=True) phoneNumber = models.CharField(max_length=15) regNo = models.CharField(max_length=15) designation = models.CharField(max_length=3,choices=DESIGNATION_CHOICES) image = models.ImageField(max_length=100,upload_to='photos/%Y/%m/%d', blank=True, null=True) course = models.CharField(max_length=30, blank=True, null=True) timezone = models.CharField(max_length=50, default='Africa/Nairobi') smsCom = models.BooleanField() mailCom = models.BooleanField() fbCom = models.BooleanField() objects = UserManager() #def __unicode__(self): # return '%s %s ' % (User.Username, User.is_staff) def get_absolute_url(self): return u'%s%s/%s' % (settings.MEDIA_URL, settings.ATTACHMENT_FOLDER, self.id) def get_download_url(self): return u'%s%s/%s' % (settings.MEDIA_URL, settings.ATTACHMENT_FOLDER, self.name) ... class reports(models.Model): repID = models.AutoField(primary_key=True) repSubject = models.CharField(max_length=100) repRecepients = models.ManyToManyField(UserProfile) repPoster = models.ForeignKey(UserProfile,related_name='repposter') repDescription = models.TextField() repPubAccess = models.BooleanField() repDate = models.DateField() report = models.FileField(max_length=200,upload_to='files/%Y/%m/%d' ) deleted = models.BooleanField() def __unicode__(self): return u'%s ' % (self.repSubject) my forms from django import forms from django.http import HttpResponse from cms.models import * from django.contrib.sessions.models import Session from django.forms.extras.widgets import SelectDateWidget class UserProfileForm(forms.ModelForm): class Meta: model= UserProfile exclude = ('designation','password','is_staff', 'is_active','is_superuser','last_login','date_joined','user_permissions','groups') ... class reportsForm(forms.ModelForm): repPoster = forms.ModelChoiceField(queryset=UserProfile.objects.all(), widget=forms.HiddenInput()) repDescription = forms.CharField(widget=forms.Textarea(attrs={'cols':'50', 'rows':'5'}),label='Enter Report Description here') repDate = forms.DateField(widget=SelectDateWidget()) class Meta: model = reports exclude = ('deleted') my views @login_required def reports_media(request): user = UserProfile.objects.get(pk=request.session['_auth_user_id']) if request.user.is_staff== True: repmedform = reportsForm(request.POST, request.FILES) if repmedform.is_valid(): repmedform.save() repmedform = reportsForm(initial = {'repPoster':user.id,}) else: repmedform = reportsForm(initial = {'repPoster':user.id,}) return render_to_response('staffrepmedia.html', {'repfrm':repmedform, 'rep_media': reports.objects.all()}) else: return render_to_response('reports_&_media.html', {'rep_media': reports.objects.all()}) ... @login_required def settingchng(request): user = UserProfile.objects.get(pk=request.session['_auth_user_id']) form = UserProfileForm(instance = user) if request.method == 'POST': form = UserProfileForm(request.POST, request.FILES, instance = user) if form.is_valid(): form.save() return HttpResponseRedirect('/settings/') else: form = UserProfileForm(instance = user) if request.user.is_staff== True: return render_to_response('staffsettingschange.html', {'form': form}) else: return render_to_response('settingschange.html', {'form': form}) ... @login_required def useradd(request): if request.method == 'POST': form = UserAddForm(request.POST,request.FILES ) if form.is_valid(): password = request.POST['password'] request.POST['password'] = set_password(password) form.save() else: form = UserAddForm() return render_to_response('staffadduser.html', {'form':form}) Example of my templates {% if form.errors %} <ol> {% for field in form %} <H3 class="title"> <p class="error"> {% if field.errors %}<li>{{ field.errors|striptags }}</li>{% endif %}</p> </H3> {% endfor %} </ol> {% endif %} <form method="post" id="form" action="" enctype="multipart/form-data" class="infotabs accfrm"> {{ repfrm.as_p }} <input type="submit" value="Submit" /> </form>

    Read the article

  • How Can I Populate Default Form Data with a ManyToMany Field?

    - by b14ck
    Ok, I've been crawling google and Django documentation for over 2 hours now (as well as the IRC channel on freenode), and haven't been able to figure this one out. Basically, I have a model called Room, which is displayed below: class Room(models.Model): """ A `Partyline` room. Rooms on the `Partyline`s are like mini-chatrooms. Each room has a variable amount of `Caller`s, and usually a moderator of some sort. Each `Partyline` has many rooms, and it is common for `Caller`s to join multiple rooms over the duration of their call. """ LIVE = 0 PRIVATE = 1 ONE_ON_ONE = 2 UNCENSORED = 3 BULLETIN_BOARD = 4 CHILL = 5 PHONE_BOOTH = 6 TYPE_CHOICES = ( ('LR', 'Live Room'), ('PR', 'Private Room'), ('UR', 'Uncensored Room'), ) type = models.CharField('Room Type', max_length=2, choices=TYPE_CHOICES) number = models.IntegerField('Room Number') partyline = models.ForeignKey(Partyline) owner = models.ForeignKey(User, blank=True, null=True) bans = models.ManyToManyField(Caller, blank=True, null=True) def __unicode__(self): return "%s - %s %d" % (self.partyline.name, self.type, self.number) I've also got a forms.py which has the following ModelForm to represent my Room model: from django.forms import ModelForm from partyline_portal.rooms.models import Room class RoomForm(ModelForm): class Meta: model = Room I'm creating a view which allows administrators to edit a given Room object. Here's my view (so far): def edit_room(request, id=None): """ Edit various attributes of a specific `Room`. Room owners do not have access to this page. They cannot edit the attributes of the `Room`(s) that they control. """ room = get_object_or_404(Room, id=id) if not room.is_owner(request.user): return HttpResponseForbidden('Forbidden.') if is_user_type(request.user, ['admin']): form_type = RoomForm elif is_user_type(request.user, ['lm']): form_type = LineManagerEditRoomForm elif is_user_type(request.user, ['lo']): form_type = LineOwnerEditRoomForm if request.method == 'POST': form = form_type(request.POST, instance=room) if form.is_valid(): if 'owner' in form.cleaned_data: room.owner = form.cleaned_data['owner'] room.save() else: defaults = {'type': room.type, 'number': room.number, 'partyline': room.partyline.id} if room.owner: defaults['owner'] = room.owner.id if room.bans: defaults['bans'] = room.bans.all() ### this does not work properly! form = form_type(defaults, instance=room) variables = RequestContext(request, {'form': form, 'room': room}) return render_to_response('portal/rooms/edit.html', variables) Now, this view works fine when I view the page. It shows all of the form attributes, and all of the default values are filled in (when users do a GET)... EXCEPT for the default values for the ManyToMany field 'bans'. Basically, if an admins clicks on a Room object to edit, the page they go to will show all of the Rooms default values except for the 'bans'. No matter what I do, I can't find a way to get Django to display the currently 'banned users' for the Room object. Here is the line of code that needs to be changed (from the view): defaults = {'type': room.type, 'number': room.number, 'partyline': room.partyline.id} if room.owner: defaults['owner'] = room.owner.id if room.bans: defaults['bans'] = room.bans.all() ### this does not work properly! There must be some other syntax I have to use to specify the default value for the 'bans' field. I've really been pulling my hair out on this one, and would definitely appreciate some help. Thanks!

    Read the article

< Previous Page | 1 2 3 4 5 6  | Next Page >