Dynamic Nested Formsets?
I have 3 Models: class Workflow(models.Model): name = models.CharField(max_length=255) company = models.ForeignKey(Company) class Meta: unique_together = ('name', 'company') class Milestone(models.Model): workflow = models.ForeignKey(Workflow) tasks = models.ManyToManyField(Task) class Task(models.Model): task = models.CharField(max_length=255) How could I create a form that allows me to add many milestones to a workflow and many tasks to a milestone? -- You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-users@googlegroups.com. To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com. For more options, visit this group at http://groups.google.com/group/django-users?hl=en.
Using class based views to autoassign certain values?
When I try to add new Attendee with a class based view I get the error matriculation_attendee.event_id may not be NULL with this code: class Event(models.Model): """ Model representing an event """ place = models.ForeignKey(Place, blank=True, null=True) slug = AutoSlugField(populate_from=('company', 'name')) name = models.CharField(max_length=200) company = models.ForeignKey(Company) description = models.TextField(null=True, blank=True) start_date = models.DateField() end_date = models.DateField() status = models.CharField(max_length=200, null=False, blank=True) currency = models.CharField(max_length=4, choices=currency_choices) payment_gateway = models.ForeignKey(PaymentGateway, blank=True, null=True) def registered(self): return self.attendee_set.count() def active(self): return self.attendee_set.filter(is_active=True).count() def cancelled(self): return self.attendee_set.filter(is_active=False).count() def __unicode__(self): return self.name class Meta: ordering = ['name'] def save(self, *args, **kwargs): if self.end_date < datetime.now().date(): self.status = 'Closed' elif datetime.now().date() >= self.start_date: self.status = 'Onsite' else: self.status = 'Active' super(Event, self).save(*args, **kwargs) class Attendee(CommonDataInfo): #TODO: Add prefix and suffix choices event = models.ForeignKey(Event) prefix = models.CharField(max_length=300, blank=True, null=True) first_name = models.CharField(max_length=300) last_name = models.CharField(max_length=300) suffix = models.CharField(max_length=300, blank=True, null=True) badge_name = models.CharField(max_length=300, blank=True, null=True) birthdate = models.DateField(blank=True, null=True) reg_date = models.DateTimeField(default=datetime.now()) email = models.CharField(max_length=300, blank=True, null=True) gender = models.CharField(max_length=1, choices=gender_choices, blank=True, null=True) location = models.ForeignKey(Place, blank=True, null=True) def __unicode__(self): return "%s %s" % (self.first_name, self.last_name) class Meta: ordering = ['last_name', 'first_name', 'is_active'] class EventContextMixIn(object): def get_context_data(self, **kwargs): event = get_object_or_404(Event, slug=self.kwargs['event_id']) # Call the base implementation first to get a context context = super(EventContextMixIn, self).get_context_data(**kwargs) context['event'] = event return context def get_form_kwargs(self, **kwargs): context = self.get_context_data() kwargs = super(EventContextMixIn, self).get_form_kwargs(**kwargs) kwargs['initial']['event'] = context['event'] return kwargs class EventCreateView(EventContextMixIn, CreateView): pass class EventUpdateView(EventContextMixIn, UpdateView): pass class EventListView(EventContextMixIn, ListView): context_object_name = "model_list" class EventDetailView(EventContextMixIn, DetailView): context_object_name = 'model' url(r'^events/(?P[-\w]+)/attendees/add/$', EventCreateView.as_view(form_class=AttendeeForm, template_name='matriculation/attendee_update.html'), name='matriculation_attendees_add'), Am I using this wrong? I'm basically trying to set this up so I the url defines the event and then I can create models for the specific event. -- You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-users@googlegroups.com. To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com. For more options, visit this group at http://groups.google.com/group/django-users?hl=en.
Re: Need a tip on how to architect this code to be more extensible
I still haven't came up with a creative solution on this, is there anyone that might be able to give me some ideas? On Nov 29, 12:25 am, Sontek <son...@gmail.com> wrote: > I wrote this open source project that allows you to use the django > admin pop-ups in your own views but I want to give it the ability to > have the view extended so they can pass excludes and instances to the > form before its display... currently the code looks like this: > > from django.contrib.auth.decorators import login_required > from django.shortcuts import render_to_response > from django.template import RequestContext > from django.http import HttpResponse > from django.utils.html import escape > from tekextensions.forms import get_model_form, normalize_model_name > > def add_new_model(request, model_name, form=None): > normal_model_name = normalize_model_name(model_name) > > if not form: > form = get_model_form(normal_model_name) > > if request.method == 'POST': > form = form(request.POST) > if form.is_valid(): > try: > new_obj = form.save() > except forms.ValidationError, error: > new_obj = None > > if new_obj: > return HttpResponse('
Need a tip on how to architect this code to be more extensible
I wrote this open source project that allows you to use the django admin pop-ups in your own views but I want to give it the ability to have the view extended so they can pass excludes and instances to the form before its display... currently the code looks like this: from django.contrib.auth.decorators import login_required from django.shortcuts import render_to_response from django.template import RequestContext from django.http import HttpResponse from django.utils.html import escape from tekextensions.forms import get_model_form, normalize_model_name def add_new_model(request, model_name, form=None): normal_model_name = normalize_model_name(model_name) if not form: form = get_model_form(normal_model_name) if request.method == 'POST': form = form(request.POST) if form.is_valid(): try: new_obj = form.save() except forms.ValidationError, error: new_obj = None if new_obj: return HttpResponse('opener.dismissAddAnotherPopup(window, "%s", "%s");' % \ (escape(new_obj._get_pk_val()), escape(new_obj))) else: form = form() page_context = {'form': form, 'field': normal_model_name} return render_to_response('popup.html', page_context, context_instance=RequestContext(request)) So I'd still like to allow them to get the automatic adding of the javascript httpresponse and autocreation of the form using the model_form_factory but would allow them to get the form and pass instance=... and exclude = ('whatever', )so that they can customize/tweak the generated form -- You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-us...@googlegroups.com. To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com. For more options, visit this group at http://groups.google.com/group/django-users?hl=en.
Re: Model Form crashing on Foreign Key
On Jan 10, 6:17 pm, Sontek <son...@gmail.com> wrote: > On Jan 10, 12:23 pm, Sontek <son...@gmail.com> wrote: > > > So I'm trying to create a new feed within the Admin page and its > > crashing with the error IntegrityError: lifestream_feed.lifestream_id > > may not be NULL, the call stack is... form['lifestream'] is set but > > form.instance.lifestream is not. Here is the code: This is a bug in HEAD -- You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-us...@googlegroups.com. To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com. For more options, visit this group at http://groups.google.com/group/django-users?hl=en.
Re: Model Form crashing on Foreign Key
On Jan 10, 12:23 pm, Sontek <son...@gmail.com> wrote: > So I'm trying to create a new feed within the Admin page and its > crashing with the error IntegrityError: lifestream_feed.lifestream_id > may not be NULL, the call stack is... form['lifestream'] is set but > form.instance.lifestream is not. Here is the code: > Its not returning the empty returns, its reaching the return self.cleaned_data: -> return self.cleaned_data (Pdb) list 85 self.cleaned_data['name'] = feed_info['title'] 86 self.instance.name = self.cleaned_data['name'] 87 self.cleaned_data['domain'] = get_url_domain(feed_url) 88 self.instance.domain = self.cleaned_data['domain'] 89 90 -> return self.cleaned_data 91 92 class FeedAdmin(admin.ModelAdmin): 93 list_display= ('name', 'lifestream', 'domain', 'fetchable') 94 list_filter = ('domain', 'lifestream') 95 actions = ['make_fetchable', 'make_unfetchable'] (Pdb) self.cleaned_data {'url': u'http://twitter.com/statuses/user_timeline/6166742.rss', 'domain': u'twitter.com', 'lifestream': , 'name': u'Twitter / sontek', 'plugin_class_name': u'lifestream.plugins.twitter.TwitterPlugin'} -- You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-us...@googlegroups.com. To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com. For more options, visit this group at http://groups.google.com/group/django-users?hl=en.
Model Form crashing on Foreign Key
So I'm trying to create a new feed within the Admin page and its crashing with the error IntegrityError: lifestream_feed.lifestream_id may not be NULL, the call stack is... form['lifestream'] is set but form.instance.lifestream is not. Here is the code: class FeedCreationForm(forms.ModelForm): class Meta: model = Feed exclude = ['name', 'domain', 'fetchable'] def parse_feed(self, feed_url): feed = feedparser.parse(feed_url) # Does the feed have errors if feed['bozo']: if feed['feed'].has_key("links"): for link in feed['feed']['links']: if link["type"] == "application/rss+xml": feed = self.parse_feed(link['href']) if not feed['bozo']: return feed else: return feed return None def clean(self): """ Checks to make sure a feed url is valid and gets the feed title and domain. """ feed_url = self.cleaned_data.get('url') if not feed_url: # Feed url was not validated by the field validator return feed = self.parse_feed(feed_url) if feed: feed_url = feed['url'] self.cleaned_data['url'] = feed_url else: # the feed was not parsed correctly. import logging self._errors['url'] = ErrorList(["This is not a valid feed: %s" % feed['bozo_exception']]) logging.error(feed['bozo_exception']) # This field is no longer valid. Remove from cleaned_data del self.cleaned_data['url'] return # Check if the feed has a title field feed_info = feed.get('feed') if not feed_info.get('title'): self._errors['url'] = ErrorList(["This is not a valid feed: The feed is empty"]) # This field is no longer valid. Remove from cleaned_data del self.cleaned_data['url'] return self.cleaned_data['name'] = feed_info['title'] self.instance.name = self.cleaned_data['name'] self.cleaned_data['domain'] = get_url_domain(feed_url) self.instance.domain = self.cleaned_data['domain'] return self.cleaned_data class FeedAdmin(admin.ModelAdmin): list_display= ('name', 'lifestream', 'domain', 'fetchable') list_filter = ('domain', 'lifestream') actions = ['make_fetchable', 'make_unfetchable'] add_form = FeedCreationForm model = Feed def make_unfetchable(self, request, queryset): queryset.update(fetchable=False) make_unfetchable.short_description = _(u"Mark as unfetchable") def make_fetchable(self, request, queryset): queryset.update(fetchable=True) make_fetchable.short_description = _(u"Mark as fetchable") def add_view(self, request): if not self.has_change_permission(request): raise PermissionDenied if request.method == 'POST': form = self.add_form(request.POST) if form.is_valid(): new_feed = form.save() msg = _('The %(name)s "%(obj)s" was added successfully.') % {'name': 'user', 'obj': new_feed} self.log_addition(request, new_feed) if "_addanother" in request.POST: request.user.message_set.create(message=msg) return HttpResponseRedirect(request.path) elif '_popup' in request.REQUEST: return self.response_add(request, new_feed) else: request.user.message_set.create(message=msg + ' ' + ugettext("You may edit it again below.")) # TODO: use reversed url return HttpResponseRedirect('../%s/' % new_feed.id) else: form = self.add_form() return render_to_response('admin/lifestream/feed/ add_form.html', { 'title': _('Add feed'), 'form': form, 'is_popup': '_popup' in request.REQUEST, 'add': True, 'change': False, 'has_add_permission': True, 'has_delete_permission': False, 'has_change_permission': True, 'has_file_field': False, 'has_absolute_url': False, 'auto_populated_fields': (), 'opts': self.model._meta, 'save_as': False, #'username_help_text': self.model._meta.get_field ('username').help_text, 'root_path': self.admin_site.root_path, 'app_label': self.model._meta.app_label, }, context_instance=template.RequestContext(request)) def queryset(self, request): return self.model.objects.feeds() admin.site.register(Feed, FeedAdmin) class Lifestream(models.Model): """ A lifestream. Lifestreams can be created per user. """ site = models.ForeignKey(Site,