Re: Initial data doesn't go complelely in the modelformset
In line 58 you can see me adding "print_report_check":True, my form class PrintReportModelForm(ModelForm): print_report_check = forms.BooleanField(widget=forms.CheckboxInput(), required=False) class Meta: fields = ["PAN_ID", "print_report_check"] model = User widgets = {"PAN_ID": forms.HiddenInput()} def __init__(self,*args, **kwargs): super().__init__(*args, **kwargs) self.fields["PAN_ID"].disabled = True # self.fields["print_report_check"].initial = True def save(self, commit=True): logger.info(" Method not meant to save anything ") pass On Monday, June 14, 2021 at 12:09:49 AM UTC+5:30 VISHESH MANGLA wrote: > in line 38 i have that print statement, it's output is at the top , I dont > know why that initial data is not going into that model formset. > actually one data the PAN_ID actually went into the modelform, but the > checkbox's "checked" didnt. You can see the html of the formset and the > checkbox field doesnt has a checked. > > > Code in paste > https://bpa.st/FOUQ > > GET > id="id_form-TOTAL_FORMS"> value="1" id="id_form-INITIAL_FORMS"> name="form-MIN_NUM_FORMS" value="0" id="id_form-MIN_NUM_FORMS"> type="hidden" name="form-MAX_NUM_FORMS" value="1000" > id="id_form-MAX_NUM_FORMS"> > Print report > check: name="form-0-print_report_check" id="id_form-0-print_report_check"> type="hidden" name="form-0-PAN_ID" value="10012000" disabled > id="id_form-0-PAN_ID"> > [{'PAN_ID': '10012000', 'print_report_check': True}] > > > > > > > class ListFormSetView(ListView): > context_formset_name = "formset" > > > def get_factory_object(self): > > return modelformset_factory( > self.model, > form=self.form_class, > extra=0, > ) > > def get_context_data(self, *, object_list=None, **kwargs): > > context_formset_name = getattr( > self, "context_formset_name") > > context_data = super().get_context_data(**kwargs) > > > object_list = context_data["object_list"] > > initial_data = self.get_initial(object_list) > context_data[context_formset_name] = self.get_factory_object()( > queryset=object_list, initial=initial_data > ) > > print(self.request.method , "\n", > context_data[context_formset_name], "\n" ,initial_data ) > > return context_data > > def get_initial(self, queryset=None): > """Generate the initial data for the paginated queryset for the > current page""" > > if queryset is None: > queryset = [] > > try: > return self.initial > except AttributeError: > > data = [ > {**{ > field_name: getattr(item, field_name) > for field_name in self.form_class._meta.fields > if hasattr(item, field_name) > }, "print_report_check":True} > for item in queryset > ] > > if self.request.method == "GET": > try: > userids_for_checked_boxes = > PrintStatementData["to_download"][ > > PrintStatementData["list-formset-view_previous-page"] > ] > except KeyError: > pass > else: > for i in data: > if i["PAN_ID"] in userids_for_checked_boxes: > i["print_report_check"] = True > > return data > > def get_formset_for_previous_page(self): > """Set the `page_kwarg` 's value to the previous page's value > because > the formset's data needs to be compared to the previous page's > data. > The `paginate_queryset` method uses self.kwargs["page_kwarg"] > to get the queryset corresponding to a page.So just to get the > initial data corresponding to the previous page through > `self.get_form_kwargs` we first need to do this.""" > > PrintStatementData[ > "list-formset-view_current-page"] = int(self.request.GET.get( > self.page_kwarg)) > > self.kwargs[self.page_kwarg] = PrintStatementData.get( > "list-formset-view_previous-page") > > formset = self.get_factory_object()(**self.get_form_kwargs()) > > self.kwargs[self.page_kwarg] = PrintStatementData.get( > "list-formset-view_current-page") > > return formset > > > -- You received this message because you are subscribed to the Google Groups "Django users" group. To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscr...@googlegroups.com. To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/5e95b909-3b25-4e28-a9aa-292dc09c2d59n%40googlegroups.com.
Initial data doesn't go complelely in the modelformset
in line 38 i have that print statement, it's output is at the top , I dont know why that initial data is not going into that model formset. actually one data the PAN_ID actually went into the modelform, but the checkbox's "checked" didnt. You can see the html of the formset and the checkbox field doesnt has a checked. Code in paste https://bpa.st/FOUQ GET Print report check: [{'PAN_ID': '10012000', 'print_report_check': True}] class ListFormSetView(ListView): context_formset_name = "formset" def get_factory_object(self): return modelformset_factory( self.model, form=self.form_class, extra=0, ) def get_context_data(self, *, object_list=None, **kwargs): context_formset_name = getattr( self, "context_formset_name") context_data = super().get_context_data(**kwargs) object_list = context_data["object_list"] initial_data = self.get_initial(object_list) context_data[context_formset_name] = self.get_factory_object()( queryset=object_list, initial=initial_data ) print(self.request.method , "\n", context_data[context_formset_name], "\n" ,initial_data ) return context_data def get_initial(self, queryset=None): """Generate the initial data for the paginated queryset for the current page""" if queryset is None: queryset = [] try: return self.initial except AttributeError: data = [ {**{ field_name: getattr(item, field_name) for field_name in self.form_class._meta.fields if hasattr(item, field_name) }, "print_report_check":True} for item in queryset ] if self.request.method == "GET": try: userids_for_checked_boxes = PrintStatementData["to_download"][ PrintStatementData["list-formset-view_previous-page"] ] except KeyError: pass else: for i in data: if i["PAN_ID"] in userids_for_checked_boxes: i["print_report_check"] = True return data def get_formset_for_previous_page(self): """Set the `page_kwarg` 's value to the previous page's value because the formset's data needs to be compared to the previous page's data. The `paginate_queryset` method uses self.kwargs["page_kwarg"] to get the queryset corresponding to a page.So just to get the initial data corresponding to the previous page through `self.get_form_kwargs` we first need to do this.""" PrintStatementData[ "list-formset-view_current-page"] = int(self.request.GET.get( self.page_kwarg)) self.kwargs[self.page_kwarg] = PrintStatementData.get( "list-formset-view_previous-page") formset = self.get_factory_object()(**self.get_form_kwargs()) self.kwargs[self.page_kwarg] = PrintStatementData.get( "list-formset-view_current-page") return formset -- You received this message because you are subscribed to the Google Groups "Django users" group. To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscr...@googlegroups.com. To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/f38a5d27-34bb-4346-ad0c-6ad564a55002n%40googlegroups.com.
initial data inlineAdmin
Hi, what is the best way fill all extra data inline, my code is model.py ModelA(models.Model): name = charfield(...) CHOICE_OPTION = ((1,'One'),(2,'Two'),(3, 'Three') ModelB(models.Model): fk(ModelA) option = integerfield(choice=CHOICE_OPTION) field1 = boolfield() field2 = boolfield() field3 = boolfield() forms.py class ModelBInlineAdminForm(forms.ModelForm): class Meta: model = ModelB fields = '__all__' def __init__(self, *args, **kwargs): super(ModelBInlineAdminForm, self).__init__(*args, **kwargs) self.initial = { 'option': 1, 'option': 2, 'option': 3, } admin.py class InlineModelB(admin.TabularInline): form = ModelBInlineAdminForm model = ModelB extra = 3 max_num = 3 class ModelAAdmin(admin.ModelAdmin): inlines = [InlineModelB] but the result is not as expected, I repeat only the last option, i need One, Two, Three my inline look like this option | field1 | field2 | field3 Three | [] | [] | [] Three | [] | [] | [] Three | [] | [] | [] i use django 1.11.18, python3.6 What is the best way to do this, some link to read to guide me in the right way Cheers -- att. Carlos Rocha -- You received this message because you are subscribed to the Google Groups "Django users" group. To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscr...@googlegroups.com. To post to this group, send email to django-users@googlegroups.com. Visit this group at https://groups.google.com/group/django-users. To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/CAM-7rO3kybHJ1OQrnHYbhSGNmuBHV%2BZBpkh1%3DhZEnGNSX8s9Gw%40mail.gmail.com. For more options, visit https://groups.google.com/d/optout.
RE: How to get multi form initial data?
You are using a dictionary as your form_class. It should only be one form, as far as I know. I am quite interested to learn how you got the form working by specifying a dictionary. Please review documentation: https://docs.djangoproject.com/en/2.1/topics/class-based-views/generic-editing/ And for Classy Class-Based Views: http://ccbv.co.uk/projects/Django/2.0/django.views.generic.edit/CreateView/ From: django-users@googlegroups.com [mailto:django-users@googlegroups.com] On Behalf Of Django Lover Sent: Tuesday, September 11, 2018 4:16 AM To: Django users Subject: How to get multi form initial data? I have the view like this- The form is working good but i issue is not able to get from initial data. PLEASE HELP **formview.py** class AddProfile(LoginRequiredMixin, CreateView): template_name = 'users/add_user_details.html' form_class = { 'contactInformation': ContactInformationForm, 'additionalInfomation': AdditionalInfomationForm, 'userDetailsForm': UserDetailsForm, 'userBusinessDetailsForm':UserBusinessDetailsForm, } success_url = '/dashboard/' //HERE IS CODE TO GET INITIAL DATA BUT NOT ABLE TO GET IT. def get_initial(self): if self.request.GET: initial = super(AddProfile, self).get_initial() user = self.request.user initial['first_name'] = user.first_name initial['last_name'] = user.last_name initial['email'] = user.email return initial def form_valid(self, form): user = self.request.user # UserDetailsForm = form['userDetailsForm'].save(commit=False) userBusinessDetailsForm = form['userBusinessDetailsForm'].save( commit=False) contactInformation = form['contactInformation'].save(commit=False) additionalInfomation = form['additionalInfomation'].save(commit=False) is_business = self.request.POST.get('business_selection') status = False if is_business: status = True else: status = False user.first_name = form['userDetailsForm'].cleaned_data.get('first_name') user.last_name = form['userDetailsForm'].cleaned_data.get('last_name') user.email = form['userDetailsForm'].cleaned_data.get('email') user.save() # UserDetailsForm.user = user # UserDetailsForm.save() contactInformation.user = user contactInformation.save() contactInformation.business_or_individual = status contactInformation.save() additionalInfomation.user = user additionalInfomation.save() userBusinessDetailsForm.user = user userBusinessDetailsForm.save() messages.add_message(self.request, messages.SUCCESS, _('Profile details has been successfully updated.')) return super(AddProfile, self).form_valid(form) -- You received this message because you are subscribed to the Google Groups "Django users" group. To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscr...@googlegroups.com<mailto:django-users+unsubscr...@googlegroups.com>. To post to this group, send email to django-users@googlegroups.com<mailto:django-users@googlegroups.com>. Visit this group at https://groups.google.com/group/django-users. To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/4cef2a2c-52d2-4611-8ca6-af7473adf78c%40googlegroups.com<https://groups.google.com/d/msgid/django-users/4cef2a2c-52d2-4611-8ca6-af7473adf78c%40googlegroups.com?utm_medium=email_source=footer>. For more options, visit https://groups.google.com/d/optout. -- You received this message because you are subscribed to the Google Groups "Django users" group. To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscr...@googlegroups.com. To post to this group, send email to django-users@googlegroups.com. Visit this group at https://groups.google.com/group/django-users. To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/e6b5b7f4eb574bf2878cb70cfa1ca0b2%40ISS1.ISS.LOCAL. For more options, visit https://groups.google.com/d/optout.
How to get multi form initial data?
I have the view like this- The form is working good but i issue is not able to get from initial data. PLEASE HELP **formview.py** class AddProfile(LoginRequiredMixin, CreateView): template_name = 'users/add_user_details.html' form_class = { 'contactInformation': ContactInformationForm, 'additionalInfomation': AdditionalInfomationForm, 'userDetailsForm': UserDetailsForm, 'userBusinessDetailsForm':UserBusinessDetailsForm, } success_url = '/dashboard/' *//HERE IS CODE TO GET INITIAL DATA BUT NOT ABLE TO GET IT.* def get_initial(self): if self.request.GET: initial = super(AddProfile, self).get_initial() user = self.request.user initial['first_name'] = user.first_name initial['last_name'] = user.last_name initial['email'] = user.email return initial def form_valid(self, form): user = self.request.user # UserDetailsForm = form['userDetailsForm'].save(commit=False) userBusinessDetailsForm = form['userBusinessDetailsForm'].save( commit=False) contactInformation = form['contactInformation'].save(commit=False) additionalInfomation = form['additionalInfomation'].save(commit=False ) is_business = self.request.POST.get('business_selection') status = False if is_business: status = True else: status = False user.first_name = form['userDetailsForm'].cleaned_data.get( 'first_name') user.last_name = form['userDetailsForm'].cleaned_data.get('last_name' ) user.email = form['userDetailsForm'].cleaned_data.get('email') user.save() # UserDetailsForm.user = user # UserDetailsForm.save() contactInformation.user = user contactInformation.save() contactInformation.business_or_individual = status contactInformation.save() additionalInfomation.user = user additionalInfomation.save() userBusinessDetailsForm.user = user userBusinessDetailsForm.save() messages.add_message(self.request, messages.SUCCESS, _('Profile details has been successfully updated.')) return super(AddProfile, self).form_valid(form) -- You received this message because you are subscribed to the Google Groups "Django users" group. To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscr...@googlegroups.com. To post to this group, send email to django-users@googlegroups.com. Visit this group at https://groups.google.com/group/django-users. To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/4cef2a2c-52d2-4611-8ca6-af7473adf78c%40googlegroups.com. For more options, visit https://groups.google.com/d/optout.
Re: unable to render initial data in ModelForm called through CreateView
hmm.. i don't think so. the info about the jobs is meant to be gathered before creating the invoice. see, the app should let you register "jobs" with timing, client and wage information. after creating jobs you can select in a form "open" jobs, meaning they have not been part of an invoice. so you select the jobs and create the invoice, if saving the invoice is succesful, i create the ForeignKey relation from each job to point to the invoice. ... so the CreateView _is_ the right thing, right? or would you create the object "by hand" while processing the POST data and redirect it to an UpdateForm (and delete the instance if updating fails)? Am Mittwoch, 7. März 2018 19:18:03 UTC+1 schrieb Matthew Pava: > > Correct, post is for POST, get is for GET. > > When a form is POSTed successfully, the user is redirected to another URL, > typically a success page or something of your choosing. > > So after your POST, if you are simply redirecting back to this CreateView, > you no longer have access to the invoice that you just created in this > view. You are creating a completely new invoice using the GET method. > > Maybe you mean to be creating an UpdateView with this new information > about self.jobs? > > > > *From:* django...@googlegroups.com [mailto: > django...@googlegroups.com ] *On Behalf Of *furzihurzischleim > *Sent:* Wednesday, March 7, 2018 12:10 PM > *To:* Django users > *Subject:* Re: unable to render initial data in ModelForm called through > CreateView > > > > thanks for the link, i was aware of that but was unable to find my error > (that's why i turned to irc, and then to the list).. > > it is true self.jobs is set from the post() method. that's because the > CreateView should be called if there are jobs selected in a POST-form. so > post() sets self.jobs which get processed (and summed to > initial['amount'] and initial['currency']) in get_initial(), which itself > is printed to console correctly. it then instantiated a form, which gets > the right arguments (initial dict) with the right values. but they won't > show up :( > > just for clarification: post() gets called if the request uses > POST-method, and get() gets called on GET-requests, right? > > i know this is more of a beginner issue, but i'm unable to get further in > my work at this point. thanks for your time and your advice! > > > Am Mittwoch, 7. März 2018 18:44:40 UTC+1 schrieb Matthew Pava: > > Well, I see that you only set self.jobs in the post method in > CreateInvoice. How are you seeing proper console output for get_initial > when self.jobs is not even set in the get method? Are you sure you are > seeing exactly what you want to see? Please double-check. When presenting > the form for the first time, it will use the get method on CreateInvoice. > Since you did not override it, it will use the default implementation. You > didn’t set self.jobs anywhere else but in the post method. > > > > I also find this website helpful when dealing with class-based views: > > > https://ccbv.co.uk/projects/Django/1.11/django.views.generic.edit/CreateView/ > > > > > > *From:* django...@googlegroups.com [mailto:django...@googlegroups.com] *On > Behalf Of *furzihurzischleim > *Sent:* Wednesday, March 7, 2018 7:11 AM > *To:* Django users > *Subject:* Re: unable to render initial data in ModelForm called through > CreateView > > > > :) > > Invoice Form is "just" a normal Modelform - nothing fancy added. > > class InvoiceForm(forms.ModelForm): > class Meta: > model = Invoice > fields = '__all__' > def __init__(self,*args,**kwargs): > print("InvoiceForm.__init__();;;") > #print( self) > print( args) > print( kwargs) > return super(InvoiceForm, self).__init__( *args, **kwargs ) > > Am Dienstag, 6. März 2018 18:08:33 UTC+1 schrieb Matthew Pava: > > Let's see InvoiceForm. > Also, it doesn't make much of a different, but I wouldn't call copy on the > super.get_initial() method. > > > -Original Message- > From: django...@googlegroups.com [mailto:django...@googlegroups.com] On > Behalf Of Gabriel Wicki > Sent: Sunday, March 4, 2018 2:48 PM > To: django...@googlegroups.com > Subject: unable to render initial data in ModelForm called through > CreateView > > hello list > > i ran into some weird stuff and neither i nor 2 gentle folks down at the > irc-chat could find any obvious problems. task should have been easy: > calculate some special initial data and present it as initials in a form. &g
RE: unable to render initial data in ModelForm called through CreateView
Correct, post is for POST, get is for GET. When a form is POSTed successfully, the user is redirected to another URL, typically a success page or something of your choosing. So after your POST, if you are simply redirecting back to this CreateView, you no longer have access to the invoice that you just created in this view. You are creating a completely new invoice using the GET method. Maybe you mean to be creating an UpdateView with this new information about self.jobs? From: django-users@googlegroups.com [mailto:django-users@googlegroups.com] On Behalf Of furzihurzischleim Sent: Wednesday, March 7, 2018 12:10 PM To: Django users Subject: Re: unable to render initial data in ModelForm called through CreateView thanks for the link, i was aware of that but was unable to find my error (that's why i turned to irc, and then to the list).. it is true self.jobs is set from the post() method. that's because the CreateView should be called if there are jobs selected in a POST-form. so post() sets self.jobs which get processed (and summed to initial['amount'] and initial['currency']) in get_initial(), which itself is printed to console correctly. it then instantiated a form, which gets the right arguments (initial dict) with the right values. but they won't show up :( just for clarification: post() gets called if the request uses POST-method, and get() gets called on GET-requests, right? i know this is more of a beginner issue, but i'm unable to get further in my work at this point. thanks for your time and your advice! Am Mittwoch, 7. März 2018 18:44:40 UTC+1 schrieb Matthew Pava: Well, I see that you only set self.jobs<http://self.jobs> in the post method in CreateInvoice. How are you seeing proper console output for get_initial when self.jobs<http://self.jobs> is not even set in the get method? Are you sure you are seeing exactly what you want to see? Please double-check. When presenting the form for the first time, it will use the get method on CreateInvoice. Since you did not override it, it will use the default implementation. You didn’t set self.jobs<http://self.jobs> anywhere else but in the post method. I also find this website helpful when dealing with class-based views: https://ccbv.co.uk/projects/Django/1.11/django.views.generic.edit/CreateView/ From: django...@googlegroups.com [mailto:django...@googlegroups.com] On Behalf Of furzihurzischleim Sent: Wednesday, March 7, 2018 7:11 AM To: Django users Subject: Re: unable to render initial data in ModelForm called through CreateView :) Invoice Form is "just" a normal Modelform - nothing fancy added. class InvoiceForm(forms.ModelForm): class Meta: model = Invoice fields = '__all__' def __init__(self,*args,**kwargs): print("InvoiceForm.__init__();;;") #print( self) print( args) print( kwargs) return super(InvoiceForm, self).__init__( *args, **kwargs ) Am Dienstag, 6. März 2018 18:08:33 UTC+1 schrieb Matthew Pava: Let's see InvoiceForm. Also, it doesn't make much of a different, but I wouldn't call copy on the super.get_initial() method. -Original Message- From: django...@googlegroups.com<mailto:django...@googlegroups.com> [mailto:django...@googlegroups.com] On Behalf Of Gabriel Wicki Sent: Sunday, March 4, 2018 2:48 PM To: django...@googlegroups.com<mailto:django...@googlegroups.com> Subject: unable to render initial data in ModelForm called through CreateView hello list i ran into some weird stuff and neither i nor 2 gentle folks down at the irc-chat could find any obvious problems. task should have been easy: calculate some special initial data and present it as initials in a form. the form is showed correctly, and the right values are printed in console.. and, of course, there is no error raised.. thank you for any hints! i've been stuck here gabriel # models.py class AmountModel(models.Model): class Meta: abstract = True currencies = ( ('CHF', "Swiss Francs"), ('EUR', "Euros"), ) amount = models.FloatField(); currency = models.CharField( max_length=3, choices=currencies, default='CHF' ) def __str__(self): return "{} {}".format(self.amount, [ j[1] for i,j in enumerate(self.currencies) if j[0] == self.currency][0] ) def short(self): return "{} {}".format([ j[0] for i,j in enumerate(self.currencies) if j[0] == self.currency][0], self.amount ) def __add__(self, other): return AmountModel(amount=self.amount+other.amount, currency=self.currency) class DocumentModel(models.Model): class Meta: abstract = True tex = models.FileField(verbose_name = "TeX") pdf = models.FileField(verbose_name = "PDF") def generate_pdf( self ): return class In
RE: unable to render initial data in ModelForm called through CreateView
Well, I see that you only set self.jobs in the post method in CreateInvoice. How are you seeing proper console output for get_initial when self.jobs is not even set in the get method? Are you sure you are seeing exactly what you want to see? Please double-check. When presenting the form for the first time, it will use the get method on CreateInvoice. Since you did not override it, it will use the default implementation. You didn’t set self.jobs anywhere else but in the post method. I also find this website helpful when dealing with class-based views: https://ccbv.co.uk/projects/Django/1.11/django.views.generic.edit/CreateView/ From: django-users@googlegroups.com [mailto:django-users@googlegroups.com] On Behalf Of furzihurzischleim Sent: Wednesday, March 7, 2018 7:11 AM To: Django users Subject: Re: unable to render initial data in ModelForm called through CreateView :) Invoice Form is "just" a normal Modelform - nothing fancy added. class InvoiceForm(forms.ModelForm): class Meta: model = Invoice fields = '__all__' def __init__(self,*args,**kwargs): print("InvoiceForm.__init__();;;") #print( self) print( args) print( kwargs) return super(InvoiceForm, self).__init__( *args, **kwargs ) Am Dienstag, 6. März 2018 18:08:33 UTC+1 schrieb Matthew Pava: Let's see InvoiceForm. Also, it doesn't make much of a different, but I wouldn't call copy on the super.get_initial() method. -Original Message- From: django...@googlegroups.com [mailto:django...@googlegroups.com] On Behalf Of Gabriel Wicki Sent: Sunday, March 4, 2018 2:48 PM To: django...@googlegroups.com Subject: unable to render initial data in ModelForm called through CreateView hello list i ran into some weird stuff and neither i nor 2 gentle folks down at the irc-chat could find any obvious problems. task should have been easy: calculate some special initial data and present it as initials in a form. the form is showed correctly, and the right values are printed in console.. and, of course, there is no error raised.. thank you for any hints! i've been stuck here gabriel # models.py class AmountModel(models.Model): class Meta: abstract = True currencies = ( ('CHF', "Swiss Francs"), ('EUR', "Euros"), ) amount = models.FloatField(); currency = models.CharField( max_length=3, choices=currencies, default='CHF' ) def __str__(self): return "{} {}".format(self.amount, [ j[1] for i,j in enumerate(self.currencies) if j[0] == self.currency][0] ) def short(self): return "{} {}".format([ j[0] for i,j in enumerate(self.currencies) if j[0] == self.currency][0], self.amount ) def __add__(self, other): return AmountModel(amount=self.amount+other.amount, currency=self.currency) class DocumentModel(models.Model): class Meta: abstract = True tex = models.FileField(verbose_name = "TeX") pdf = models.FileField(verbose_name = "PDF") def generate_pdf( self ): return class Invoice(AmountModel, DocumentModel): STATUS = ( ("o", "open"), # initialized ("c", "complete"), # completed (no info missing) ("s","sent"), # sent ("p","pending"), # sent but money not yet received ("pd","paid") # paid and archived ) client = models.ForeignKey( 'Client', on_delete=models.CASCADE ) title = models.CharField( max_length=200 ) status = models.CharField( max_length=2, choices = STATUS ) number = models.IntegerField( blank=True ) date_created = models.DateField( auto_now=True ) date_sent = models.DateField( blank=True ) date_paid = models.DateField( blank=True ) @property def jobs(self): return Job.objects.filter( invoice=self ) @property def expenses(self): return Expense.objects.filter( invoice=self ) def __str__(self): if self.status.startswith('p'): return '%d %s'.format(self.number, self.title ) return self.title def update_status(self): if (self.date_sent == None): self.status = STATUS[0][0] elif (self.date_paid == None): self.status = STATUS[1][0] else: self.status = STATUS[2][0] return def calculate_amount(self): amount = 0 for o in [ self.jobs<http://self.jobs>, self.expenses ].flatten: amount += o.amount self.amount = amount self.save() return def create_tex( self ): template_file = 'templates/invoice.tex' t = loader.get_template(template_file) context = { 'title': self.title, }
Re: unable to render initial data in ModelForm called through CreateView
:) Invoice Form is "just" a normal Modelform - nothing fancy added. class InvoiceForm(forms.ModelForm): class Meta: model = Invoice fields = '__all__' def __init__(self,*args,**kwargs): print("InvoiceForm.__init__();;;") #print( self) print( args) print( kwargs) return super(InvoiceForm, self).__init__( *args, **kwargs ) Am Dienstag, 6. März 2018 18:08:33 UTC+1 schrieb Matthew Pava: > > Let's see InvoiceForm. > Also, it doesn't make much of a different, but I wouldn't call copy on the > super.get_initial() method. > > > -Original Message- > From: django...@googlegroups.com [mailto: > django...@googlegroups.com ] On Behalf Of Gabriel Wicki > Sent: Sunday, March 4, 2018 2:48 PM > To: django...@googlegroups.com > Subject: unable to render initial data in ModelForm called through > CreateView > > hello list > > i ran into some weird stuff and neither i nor 2 gentle folks down at the > irc-chat could find any obvious problems. task should have been easy: > calculate some special initial data and present it as initials in a form. > the form is showed correctly, and the right values are printed in console.. > and, of course, there is no error raised.. > > thank you for any hints! i've been stuck here > > > gabriel > > > > > # models.py > class AmountModel(models.Model): > class Meta: > abstract = True > currencies = ( > ('CHF', "Swiss Francs"), > ('EUR', "Euros"), > ) > amount = models.FloatField(); > currency = models.CharField( max_length=3, choices=currencies, > default='CHF' ) > > def __str__(self): > return "{} {}".format(self.amount, [ j[1] for i,j in > enumerate(self.currencies) if j[0] == self.currency][0] ) > def short(self): > return "{} {}".format([ j[0] for i,j in > enumerate(self.currencies) if j[0] == self.currency][0], self.amount ) > def __add__(self, other): > return AmountModel(amount=self.amount+other.amount, > currency=self.currency) > > class DocumentModel(models.Model): > class Meta: > abstract = True > tex = models.FileField(verbose_name = "TeX") > pdf = models.FileField(verbose_name = "PDF") > def generate_pdf( self ): > return > > class Invoice(AmountModel, DocumentModel): > STATUS = ( > ("o", "open"), # initialized > ("c", "complete"), # completed (no info missing) > ("s","sent"), # sent > ("p","pending"), # sent but money not yet received > ("pd","paid") # paid and archived > ) > client = models.ForeignKey( 'Client', on_delete=models.CASCADE ) > title = models.CharField( max_length=200 ) > status = models.CharField( max_length=2, choices = STATUS ) > number = models.IntegerField( blank=True ) > date_created = models.DateField( auto_now=True ) > date_sent = models.DateField( blank=True ) > date_paid = models.DateField( blank=True ) > > @property > def jobs(self): > return Job.objects.filter( invoice=self ) > > @property > def expenses(self): > return Expense.objects.filter( invoice=self ) > > def __str__(self): > if self.status.startswith('p'): > return '%d %s'.format(self.number, self.title ) > return self.title > > def update_status(self): > if (self.date_sent == None): > self.status = STATUS[0][0] > elif (self.date_paid == None): > self.status = STATUS[1][0] > else: > self.status = STATUS[2][0] > return > > def calculate_amount(self): > amount = 0 > for o in [ self.jobs, self.expenses ].flatten: > amount += o.amount > self.amount = amount > self.save() > return > > def create_tex( self ): > template_file = 'templates/invoice.tex' > t = loader.get_template(template_file) > context = { > 'title': self.title, > } > filename = '%d %s'.format(self.number, slugify(self.title) ) > self.tex.file = open(filename+'.tex', 'w') > self.tex.file.write(smart_str( t.render(context) )) > return > > def send_to_client( self ): > return >
RE: unable to render initial data in ModelForm called through CreateView
Let's see InvoiceForm. Also, it doesn't make much of a different, but I wouldn't call copy on the super.get_initial() method. -Original Message- From: django-users@googlegroups.com [mailto:django-users@googlegroups.com] On Behalf Of Gabriel Wicki Sent: Sunday, March 4, 2018 2:48 PM To: django-users@googlegroups.com Subject: unable to render initial data in ModelForm called through CreateView hello list i ran into some weird stuff and neither i nor 2 gentle folks down at the irc-chat could find any obvious problems. task should have been easy: calculate some special initial data and present it as initials in a form. the form is showed correctly, and the right values are printed in console.. and, of course, there is no error raised.. thank you for any hints! i've been stuck here gabriel # models.py class AmountModel(models.Model): class Meta: abstract = True currencies = ( ('CHF', "Swiss Francs"), ('EUR', "Euros"), ) amount = models.FloatField(); currency = models.CharField( max_length=3, choices=currencies, default='CHF' ) def __str__(self): return "{} {}".format(self.amount, [ j[1] for i,j in enumerate(self.currencies) if j[0] == self.currency][0] ) def short(self): return "{} {}".format([ j[0] for i,j in enumerate(self.currencies) if j[0] == self.currency][0], self.amount ) def __add__(self, other): return AmountModel(amount=self.amount+other.amount, currency=self.currency) class DocumentModel(models.Model): class Meta: abstract = True tex = models.FileField(verbose_name = "TeX") pdf = models.FileField(verbose_name = "PDF") def generate_pdf( self ): return class Invoice(AmountModel, DocumentModel): STATUS = ( ("o", "open"), # initialized ("c", "complete"), # completed (no info missing) ("s","sent"), # sent ("p","pending"), # sent but money not yet received ("pd","paid") # paid and archived ) client = models.ForeignKey( 'Client', on_delete=models.CASCADE ) title = models.CharField( max_length=200 ) status = models.CharField( max_length=2, choices = STATUS ) number = models.IntegerField( blank=True ) date_created = models.DateField( auto_now=True ) date_sent = models.DateField( blank=True ) date_paid = models.DateField( blank=True ) @property def jobs(self): return Job.objects.filter( invoice=self ) @property def expenses(self): return Expense.objects.filter( invoice=self ) def __str__(self): if self.status.startswith('p'): return '%d %s'.format(self.number, self.title ) return self.title def update_status(self): if (self.date_sent == None): self.status = STATUS[0][0] elif (self.date_paid == None): self.status = STATUS[1][0] else: self.status = STATUS[2][0] return def calculate_amount(self): amount = 0 for o in [ self.jobs, self.expenses ].flatten: amount += o.amount self.amount = amount self.save() return def create_tex( self ): template_file = 'templates/invoice.tex' t = loader.get_template(template_file) context = { 'title': self.title, } filename = '%d %s'.format(self.number, slugify(self.title) ) self.tex.file = open(filename+'.tex', 'w') self.tex.file.write(smart_str( t.render(context) )) return def send_to_client( self ): return # views.py class CreateInvoice(CreateView): model = Invoice form_class = InvoiceForm template_name = 'standard_form.html' def get_initial(self): initial = super(CreateView, self).get_initial().copy() initial['title'] = "blablabla" amount = {'CHF': 0, 'EUR': 0} currency = self.jobs[0].worth.currency for j in self.jobs: amount[j.worth.currency] += j.worth.amount for a in amount.keys(): if not amount[a] == 0: try: initial['value'] is None except KeyError: initial['currency'] = a initial['amount'] = amount[a] print(initial) return initial def post(self, request, *args, **kwargs): print("post()") req = request.POST.copy() req.pop('csrfmiddlewaretoken') self.jobs = Job.objects.filter(id__in=req.keys(), client_id=kwargs['client_id']) return super(CreateView, self).post(request,*args,**kwargs) # standard_form.html {% extends 'main_form.html' %} {% block formaction %}{{ formaction }}{% endblock %} {% block 'title' %}{{ title }}{% endblock %} {% blo
unable to render initial data in ModelForm called through CreateView
hello list i ran into some weird stuff and neither i nor 2 gentle folks down at the irc-chat could find any obvious problems. task should have been easy: calculate some special initial data and present it as initials in a form. the form is showed correctly, and the right values are printed in console.. and, of course, there is no error raised.. thank you for any hints! i've been stuck here gabriel # models.py class AmountModel(models.Model): class Meta: abstract = True currencies = ( ('CHF', "Swiss Francs"), ('EUR', "Euros"), ) amount = models.FloatField(); currency = models.CharField( max_length=3, choices=currencies, default='CHF' ) def __str__(self): return "{} {}".format(self.amount, [ j[1] for i,j in enumerate(self.currencies) if j[0] == self.currency][0] ) def short(self): return "{} {}".format([ j[0] for i,j in enumerate(self.currencies) if j[0] == self.currency][0], self.amount ) def __add__(self, other): return AmountModel(amount=self.amount+other.amount, currency=self.currency) class DocumentModel(models.Model): class Meta: abstract = True tex = models.FileField(verbose_name = "TeX") pdf = models.FileField(verbose_name = "PDF") def generate_pdf( self ): return class Invoice(AmountModel, DocumentModel): STATUS = ( ("o", "open"), # initialized ("c", "complete"), # completed (no info missing) ("s","sent"), # sent ("p","pending"), # sent but money not yet received ("pd","paid") # paid and archived ) client = models.ForeignKey( 'Client', on_delete=models.CASCADE ) title = models.CharField( max_length=200 ) status = models.CharField( max_length=2, choices = STATUS ) number = models.IntegerField( blank=True ) date_created = models.DateField( auto_now=True ) date_sent = models.DateField( blank=True ) date_paid = models.DateField( blank=True ) @property def jobs(self): return Job.objects.filter( invoice=self ) @property def expenses(self): return Expense.objects.filter( invoice=self ) def __str__(self): if self.status.startswith('p'): return '%d %s'.format(self.number, self.title ) return self.title def update_status(self): if (self.date_sent == None): self.status = STATUS[0][0] elif (self.date_paid == None): self.status = STATUS[1][0] else: self.status = STATUS[2][0] return def calculate_amount(self): amount = 0 for o in [ self.jobs, self.expenses ].flatten: amount += o.amount self.amount = amount self.save() return def create_tex( self ): template_file = 'templates/invoice.tex' t = loader.get_template(template_file) context = { 'title': self.title, } filename = '%d %s'.format(self.number, slugify(self.title) ) self.tex.file = open(filename+'.tex', 'w') self.tex.file.write(smart_str( t.render(context) )) return def send_to_client( self ): return # views.py class CreateInvoice(CreateView): model = Invoice form_class = InvoiceForm template_name = 'standard_form.html' def get_initial(self): initial = super(CreateView, self).get_initial().copy() initial['title'] = "blablabla" amount = {'CHF': 0, 'EUR': 0} currency = self.jobs[0].worth.currency for j in self.jobs: amount[j.worth.currency] += j.worth.amount for a in amount.keys(): if not amount[a] == 0: try: initial['value'] is None except KeyError: initial['currency'] = a initial['amount'] = amount[a] print(initial) return initial def post(self, request, *args, **kwargs): print("post()") req = request.POST.copy() req.pop('csrfmiddlewaretoken') self.jobs = Job.objects.filter(id__in=req.keys(), client_id=kwargs['client_id']) return super(CreateView, self).post(request,*args,**kwargs) # standard_form.html {% extends 'main_form.html' %} {% block formaction %}{{ formaction }}{% endblock %} {% block 'title' %}{{ title }}{% endblock %} {% block form %} {% for field in form %} {{ field.errors }} {{ field.label_tag }} {{ field }} {% endfor %} {% endblock %} -- You received this message because you are subscribed to the Google Groups "Django users" group. To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscr...@googlegroups.com. To post to this group, send email to django-users@g
Re: Initial data, tests and migrations
I'm not trying to be antagonistic, sorry if I came off that way. I wanted to point out the difficulties that Django encountered trying to provide "integration" tests like django-otp does. As others suggested, if django-otp provided tools to build your own integration tests, that might be a better way forward. On Wednesday, February 22, 2017 at 10:14:26 AM UTC-5, Tom Evans wrote: > > On Wed, Feb 22, 2017 at 2:40 PM, Tim Graham> wrote: > > I'm curious if you feel that running django_otp's tests as part of your > > project's tests is adding value. > > I'm curious whether you think I commonly spend my time doing things > that I don't think add value... > > django_otp is simply an example of this issue, but yes, running those > tests would give my project value. > > These tests exercise parts of django_otp that interact with parts of > my code. Successful tests indicate that those two parts interoperate > correctly. The tests are successful when run individually, but fail > when run as a suite because data loaded as part of a migration is > flushed away before the second test. > -- You received this message because you are subscribed to the Google Groups "Django users" group. To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscr...@googlegroups.com. To post to this group, send email to django-users@googlegroups.com. Visit this group at https://groups.google.com/group/django-users. To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/751918fc-a96f-469b-bd3e-b19a10adf15a%40googlegroups.com. For more options, visit https://groups.google.com/d/optout.
Re: Initial data, tests and migrations
On Wednesday 22 February 2017 15:13:47 'Tom Evans' via Django users wrote: > These tests exercise parts of django_otp that interact with parts of > my code. Successful tests indicate that those two parts interoperate > correctly. The tests are successful when run individually, but fail > when run as a suite because data loaded as part of a migration is > flushed away before the second test. So they're different tests: they make use of the logic of the library's test suite, but operate on your data. Schoolbook example for inheritance: from django_otp.tests import SuperTest class SuperTestWithMyData(SuperTest): fixtures = ['my_data'] -- Melvyn Sopacua -- You received this message because you are subscribed to the Google Groups "Django users" group. To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscr...@googlegroups.com. To post to this group, send email to django-users@googlegroups.com. Visit this group at https://groups.google.com/group/django-users. To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/6963738.qIisf3konX%40devstation. For more options, visit https://groups.google.com/d/optout.
Re: Initial data, tests and migrations
On Wed, 2017-02-22 at 15:06 +, 'Tom Evans' via Django users wrote: > On Wed, Feb 22, 2017 at 2:41 PM, Adam Stein <a...@csh.rit.edu> wrote: > > > > On Wed, 2017-02-22 at 14:22 +, 'Tom Evans' via Django users > > wrote: > > > > The URL you refer to mentions about loading data for apps. Doesn't > > mention > > anything in regards to tests. Why are fixtures bad for tests? In > > fact, right > > above the "Providing initial data with migrations" section is a > > "See also" > > box that says "Fixtures are also used by the testing framework to > > help set > > up a consistent test environment". It would seem to me that the > > docs are > > telling you to use fixtures for tests and use migrations for real > > data. > OK. How do I load that data from a fixture in a TestCase I cannot > modify? Unfortunately, nothing easy comes to mind. My only thought was the possibility of putting your own wrapper around their tests. The idea being is that you call your wrapper which in turns loads the fixtures and calls their tests rather than having Django call their tests directly. This wrapper could be a unit test or be a derivative of the Django test runner. Don't know how feasible either is but I'm guessing neither would be trivial. Maybe I'm wrong, I didn't pursue the thought any more than having a wrapper of some kind. I was originally just going on your statements that fixtures weren't used in the tests because they weren't recommended (which is not really the case). Hope you figure something out. > Cheers > > Tom > > -- Adam (a...@csh.rit.edu) -- You received this message because you are subscribed to the Google Groups "Django users" group. To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscr...@googlegroups.com. To post to this group, send email to django-users@googlegroups.com. Visit this group at https://groups.google.com/group/django-users. To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/1487776952.29637.10.camel%40csh.rit.edu. For more options, visit https://groups.google.com/d/optout.
Re: Initial data, tests and migrations
On Wednesday 22 February 2017 14:22:36 'Tom Evans' via Django users wrote: > On Wed, Feb 22, 2017 at 12:47 AM, Melvyn Sopacua <m.r.sopa...@gmail.com> wrote: > > On Tuesday 21 February 2017 19:00:42 'Tom Evans' via Django users wrote: > >> What is the "correct" way of ensuring that these instances exist in > >> > >> the test database before any test is run? > > > > All explained in the docs. > > > > Either redeclare the same fixtures for different test cases or > > reorganize your testcases to share the same fixture(s). > > I think you have misunderstood: > > 1) The test cases belong to a library and cannot be modified So don't use them as is or prompt the authors to update to the new way of things. In transition, you can extend the test cases and simply add a fixture attribute. > 2) The initial data is populated from a data migration and not from a > fixture, as that is not recommended [1] Data migrations for the project are never relevant for tests, since the test database is empty. You're putting a label on "fixtures" that is only relevant for the provided context. Fixtures are not deprecated, not bad for you and do not mess up your aura. On one hand It is as Adam says: " It would seem to me that the docs are telling you to use fixtures for tests and use migrations for real data." Adding to that - fixtures are still a solid way to load application data - only the use of "initial" or "autloaded" data is discouraged. Fixtures should be used on production databases to selectively provide data, so that the user of the application can load "google_shopping.json" if it wants to publish it's products Google Shopping or not load it, if she doesn't. -- Melvyn Sopacua -- You received this message because you are subscribed to the Google Groups "Django users" group. To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscr...@googlegroups.com. To post to this group, send email to django-users@googlegroups.com. Visit this group at https://groups.google.com/group/django-users. To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/148821513.UZqiaWgqFf%40devstation. For more options, visit https://groups.google.com/d/optout.
Re: Initial data, tests and migrations
On Wed, Feb 22, 2017 at 2:40 PM, Tim Grahamwrote: > I'm curious if you feel that running django_otp's tests as part of your > project's tests is adding value. I'm curious whether you think I commonly spend my time doing things that I don't think add value... django_otp is simply an example of this issue, but yes, running those tests would give my project value. These tests exercise parts of django_otp that interact with parts of my code. Successful tests indicate that those two parts interoperate correctly. The tests are successful when run individually, but fail when run as a suite because data loaded as part of a migration is flushed away before the second test. -- You received this message because you are subscribed to the Google Groups "Django users" group. To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscr...@googlegroups.com. To post to this group, send email to django-users@googlegroups.com. Visit this group at https://groups.google.com/group/django-users. To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/CAFHbX1%2BHB_R6dY3LzEXVp_cu9G%3D%2Bo_KcX224hSG1PGNSqd5sFQ%40mail.gmail.com. For more options, visit https://groups.google.com/d/optout.
Re: Initial data, tests and migrations
On Wed, Feb 22, 2017 at 2:41 PM, Adam Stein <a...@csh.rit.edu> wrote: > On Wed, 2017-02-22 at 14:22 +, 'Tom Evans' via Django users wrote: > > The URL you refer to mentions about loading data for apps. Doesn't mention > anything in regards to tests. Why are fixtures bad for tests? In fact, right > above the "Providing initial data with migrations" section is a "See also" > box that says "Fixtures are also used by the testing framework to help set > up a consistent test environment". It would seem to me that the docs are > telling you to use fixtures for tests and use migrations for real data. OK. How do I load that data from a fixture in a TestCase I cannot modify? Cheers Tom -- You received this message because you are subscribed to the Google Groups "Django users" group. To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscr...@googlegroups.com. To post to this group, send email to django-users@googlegroups.com. Visit this group at https://groups.google.com/group/django-users. To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/CAFHbX1KsEwKmJzWgYxxFJRU8XiHBAY7u0djah6brLxjKU6yYNg%40mail.gmail.com. For more options, visit https://groups.google.com/d/optout.
Re: Initial data, tests and migrations
I'm curious if you feel that running django_otp's tests as part of your project's tests is adding value. All third-party apps that I've used (including tests for django.contrib apps*) have moved their tests to a separate directory so that they're not installed along with the application. It's quite difficult for a library to write tests that work with whatever settings a project might provide -- at least that's what we found with tests for contrib apps. * https://groups.google.com/d/topic/django-developers/nj_Zha341pA/discussion On Wednesday, February 22, 2017 at 9:23:25 AM UTC-5, Tom Evans wrote: > > On Wed, Feb 22, 2017 at 12:47 AM, Melvyn Sopacua <m.r.s...@gmail.com > > wrote: > > On Tuesday 21 February 2017 19:00:42 'Tom Evans' via Django users wrote: > > > > > > > >> Previously, these instances were loaded from a JSON fixtures file, > > > > > > > > And you can still do that. > > > > > > > >> which used to be the recommended way. For our own tests, we simply > > > >> load these fixtures in the setUp portion of the test; obviously we > > > >> can't go around modifying tests in third party libraries. > > > >> I tried taking them out of the fixtures, and adding them instead in a > > > >> data migration, but this also had the same effect - the instances were > > > >> there for the first test ran, and then missing for all the subsequent > > > >> ones. > > > > > > > > setUp is run between test methods of a test case. setupTestData is a > class > > method on the testcase run once per test case. > > > >> > > > >> > > > >> What is the "correct" way of ensuring that these instances exist in > > > >> the test database before any test is run? > > > > > > > > All explained in the docs. > > > > Either redeclare the same fixtures for different test cases or > reorganize > > your testcases to share the same fixture(s). > > > > I think you have misunderstood: > > 1) The test cases belong to a library and cannot be modified > 2) The initial data is populated from a data migration and not from a > fixture, as that is not recommended [1] > > Data is placed in to the test database using migrations, but after the > first test has been run the data is flushed out again, causing the > second test to fail. > I would like the all the tests to pass: > * I don't want to put the same data into fixtures as well as migrations > (DRY) > * I don't want to modify the 3rd party library. > > How? > > Cheers > > Tom > > [1] > https://docs.djangoproject.com/en/1.10/howto/initial-data/#providing-initial-data-with-migrations > > -- You received this message because you are subscribed to the Google Groups "Django users" group. To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscr...@googlegroups.com. To post to this group, send email to django-users@googlegroups.com. Visit this group at https://groups.google.com/group/django-users. To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/7d58066c-79fb-451a-9369-abf86101ccfc%40googlegroups.com. For more options, visit https://groups.google.com/d/optout.
Re: Initial data, tests and migrations
On Wed, 2017-02-22 at 14:22 +, 'Tom Evans' via Django users wrote: > On Wed, Feb 22, 2017 at 12:47 AM, Melvyn Sopacua > om> wrote: > > > > On Tuesday 21 February 2017 19:00:42 'Tom Evans' via Django users > > wrote: > > > > > > > > > > > > Previously, these instances were loaded from a JSON fixtures > > > file, > > > > > > And you can still do that. > > > > > > > > > > > > which used to be the recommended way. For our own tests, we > > > simply > > > > > > load these fixtures in the setUp portion of the test; obviously > > > we > > > > > > can't go around modifying tests in third party libraries. > > > > > > I tried taking them out of the fixtures, and adding them instead > > > in a > > > > > > data migration, but this also had the same effect - the instances > > > were > > > > > > there for the first test ran, and then missing for all the > > > subsequent > > > > > > ones. > > > > > > setUp is run between test methods of a test case. setupTestData is > > a class > > method on the testcase run once per test case. > > > > > > > > > > > > > > > > > > > > What is the "correct" way of ensuring that these instances exist > > > in > > > > > > the test database before any test is run? > > > > > > All explained in the docs. > > > > Either redeclare the same fixtures for different test cases or > > reorganize > > your testcases to share the same fixture(s). > > > I think you have misunderstood: > > 1) The test cases belong to a library and cannot be modified > 2) The initial data is populated from a data migration and not from a > fixture, as that is not recommended [1] > > Data is placed in to the test database using migrations, but after > the > first test has been run the data is flushed out again, causing the > second test to fail. > I would like the all the tests to pass: > * I don't want to put the same data into fixtures as well as > migrations (DRY) > * I don't want to modify the 3rd party library. > > How? > > Cheers > > Tom > > [1] https://docs.djangoproject.com/en/1.10/howto/initial-data/#provid > ing-initial-data-with-migrations > The URL you refer to mentions about loading data for apps. Doesn't mention anything in regards to tests. Why are fixtures bad for tests? In fact, right above the "Providing initial data with migrations" section is a "See also" box that says "Fixtures are also used by the testing framework to help set up a consistent test environment". It would seem to me that the docs are telling you to use fixtures for tests and use migrations for real data. -- Adam (a...@csh.rit.edu) -- You received this message because you are subscribed to the Google Groups "Django users" group. To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscr...@googlegroups.com. To post to this group, send email to django-users@googlegroups.com. Visit this group at https://groups.google.com/group/django-users. To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/1487774504.29637.5.camel%40csh.rit.edu. For more options, visit https://groups.google.com/d/optout.
Re: Initial data, tests and migrations
On Wed, Feb 22, 2017 at 12:47 AM, Melvyn Sopacua <m.r.sopa...@gmail.com> wrote: > On Tuesday 21 February 2017 19:00:42 'Tom Evans' via Django users wrote: > > > >> Previously, these instances were loaded from a JSON fixtures file, > > > > And you can still do that. > > > >> which used to be the recommended way. For our own tests, we simply > >> load these fixtures in the setUp portion of the test; obviously we > >> can't go around modifying tests in third party libraries. > >> I tried taking them out of the fixtures, and adding them instead in a > >> data migration, but this also had the same effect - the instances were > >> there for the first test ran, and then missing for all the subsequent > >> ones. > > > > setUp is run between test methods of a test case. setupTestData is a class > method on the testcase run once per test case. > >> > >> > >> What is the "correct" way of ensuring that these instances exist in > >> the test database before any test is run? > > > > All explained in the docs. > > Either redeclare the same fixtures for different test cases or reorganize > your testcases to share the same fixture(s). > I think you have misunderstood: 1) The test cases belong to a library and cannot be modified 2) The initial data is populated from a data migration and not from a fixture, as that is not recommended [1] Data is placed in to the test database using migrations, but after the first test has been run the data is flushed out again, causing the second test to fail. I would like the all the tests to pass: * I don't want to put the same data into fixtures as well as migrations (DRY) * I don't want to modify the 3rd party library. How? Cheers Tom [1] https://docs.djangoproject.com/en/1.10/howto/initial-data/#providing-initial-data-with-migrations -- You received this message because you are subscribed to the Google Groups "Django users" group. To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscr...@googlegroups.com. To post to this group, send email to django-users@googlegroups.com. Visit this group at https://groups.google.com/group/django-users. To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/CAFHbX1%2B9n%3DwvT7UVycDWr5vttHwgVeUJAD8BivNutXx9tf3d6A%40mail.gmail.com. For more options, visit https://groups.google.com/d/optout.
Re: Initial data, tests and migrations
On Tuesday 21 February 2017 19:00:42 'Tom Evans' via Django users wrote: > Previously, these instances were loaded from a JSON fixtures file, And you can still do that. > which used to be the recommended way. For our own tests, we simply > load these fixtures in the setUp portion of the test; obviously we > can't go around modifying tests in third party libraries. > I tried taking them out of the fixtures, and adding them instead in a > data migration, but this also had the same effect - the instances were > there for the first test ran, and then missing for all the subsequent > ones. setUp is run between test methods of a test case. setupTestData is a class method on the testcase run once per test case. > > > What is the "correct" way of ensuring that these instances exist in > the test database before any test is run? All explained in the docs[1]. Either redeclare the same fixtures for different test cases or reorganize your testcases to share the same fixture(s). -- Melvyn Sopacua [1] https://docs.djangoproject.com/en/1.10/topics/testing/tools/#django.test.TransactionTe stCase.fixtures -- You received this message because you are subscribed to the Google Groups "Django users" group. To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscr...@googlegroups.com. To post to this group, send email to django-users@googlegroups.com. Visit this group at https://groups.google.com/group/django-users. To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/3888092.mWS3N5nSI1%40devstation. For more options, visit https://groups.google.com/d/optout.
Initial data, tests and migrations
Hi all I'm having some difficulty working out how I am supposed to provide initial data for testing purposes, particularly when the initial data is not immediately pertinent to the test. For instance, our project uses django_otp, which has some simple tests. However, these tests create user objects, which then calls in to other parts of the project code. This code adds users to various auth.Group, depending upon the user attributes. This code fails after the first test has been run, because all the auth.Group model instances are flushed from the database. Previously, these instances were loaded from a JSON fixtures file, which used to be the recommended way. For our own tests, we simply load these fixtures in the setUp portion of the test; obviously we can't go around modifying tests in third party libraries. I tried taking them out of the fixtures, and adding them instead in a data migration, but this also had the same effect - the instances were there for the first test ran, and then missing for all the subsequent ones. What is the "correct" way of ensuring that these instances exist in the test database before any test is run? How can I stop them getting wiped out after any test has run? Cheers Tom -- You received this message because you are subscribed to the Google Groups "Django users" group. To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscr...@googlegroups.com. To post to this group, send email to django-users@googlegroups.com. Visit this group at https://groups.google.com/group/django-users. To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/CAFHbX1JKCugKaijhD6_wX-M-2nN04eTqDuFG08%3D%2BtUNBW3o5hA%40mail.gmail.com. For more options, visit https://groups.google.com/d/optout.
Re: Initial data with migrations vs fixtures
Calling loaddata in a migration will work until you modify the model's fields. You can read more on Trac: https://code.djangoproject.com/ticket/24778 On Thursday, December 1, 2016 at 12:09:49 PM UTC-5, Tom Evans wrote: > > Hi all > > We're moving a project over to the latest release (well, we're at 1.7 > now, but that's the end goal anyway) and replacing South migrations > with Django migrations. > > It looks like that fixtures are no longer thought of as the correct > way of providing initial data. Is this because Run{SQL,Python} can > have "reverse" instructions included, or is it some other reason? I > couldn't see anything pertinent in the docs. > > Given that we have an existing project and fixture files, is it very > bad and wrong to simply have a data migration that runs loaddata on > our required fixtures? It would not be reversible, but it would be > massively simpler. > > Cheers > > Tom > -- You received this message because you are subscribed to the Google Groups "Django users" group. To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscr...@googlegroups.com. To post to this group, send email to django-users@googlegroups.com. Visit this group at https://groups.google.com/group/django-users. To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/d24855cb-4640-4cbd-849e-03d05058debe%40googlegroups.com. For more options, visit https://groups.google.com/d/optout.
Initial data with migrations vs fixtures
Hi all We're moving a project over to the latest release (well, we're at 1.7 now, but that's the end goal anyway) and replacing South migrations with Django migrations. It looks like that fixtures are no longer thought of as the correct way of providing initial data. Is this because Run{SQL,Python} can have "reverse" instructions included, or is it some other reason? I couldn't see anything pertinent in the docs. Given that we have an existing project and fixture files, is it very bad and wrong to simply have a data migration that runs loaddata on our required fixtures? It would not be reversible, but it would be massively simpler. Cheers Tom -- You received this message because you are subscribed to the Google Groups "Django users" group. To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscr...@googlegroups.com. To post to this group, send email to django-users@googlegroups.com. Visit this group at https://groups.google.com/group/django-users. To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/CAFHbX1KqGdMEgHsY2WyLSS1LZHQ1k-oBfFtSQ68JZNb%2BVA_yrA%40mail.gmail.com. For more options, visit https://groups.google.com/d/optout.
Re: Entering initial data into django database
Ok..thanks..it worked...Created a script to create the fixture file and update it with every record...what a community this is! On Sunday, March 20, 2016 at 12:50:30 PM UTC-7, ludovic coues wrote: > > First, you should create a fixture file with some sample data. Two > entry, just like in the documentation is good. This way, you know you > have a working fixture file. > > Then, you write a python function which take a list of bet and output > a fixture file just like the exemple you have done. > > Finally, you adjust you scraper to build the list, use the function to > transform the list into a fixture file and import the fixture file. > > 2016-03-20 20:02 GMT+01:00 Lawrence Muriuki>: > > > > Thanks ludovic, here is my code for the scraper.. > > > > > > > > > > > > from .models import Betting > > > > import re > > import requests > > import urllib > > from bs4 import BeautifulSoup > > > > > > urls= "https://sms.betyetu.co.ke/tomorrow.html; > > htmlfile = urllib.urlopen(urls) > > htmltext = htmlfile.read() > > soup = BeautifulSoup(htmltext, "html.parser") > > > > > > for i in soup.findAll("table"): > > print i.contents[1].contents[1].findAll("th")[0].text > > print i.contents[1].contents[3].findAll("th")[0].text > > > > > > > > > > > > > > > > try: > > momo = 1 > > a = len( i.contents[3].contents) > > while momo <= a: > > print i.contents[3].contents[momo].findAll("td")[2].text > > > > foo = > > Betting(matches=i.contents[3].contents[momo].findAll("td")[2].text) > > > > momo += 2 > > > > > > foo.save() > > > > > > > > > > except: > > momo = 1 > > > > > > > > > > > > > > > > I have a model called "betting" which has only one field "matches"..For > it > > to work, I have placed it in init.py which is a wrong way to do > it..Wanted > > to understand where this code should be placed..ie..which file and how > to > > interact with it > > > >> > > -- > > You received this message because you are subscribed to the Google > Groups > > "Django users" group. > > To unsubscribe from this group and stop receiving emails from it, send > an > > email to django-users...@googlegroups.com . > > To post to this group, send email to django...@googlegroups.com > . > > Visit this group at https://groups.google.com/group/django-users. > > To view this discussion on the web visit > > > https://groups.google.com/d/msgid/django-users/d3677ab5-06eb-47aa-bdf8-d789a4c454b7%40googlegroups.com. > > > > > > For more options, visit https://groups.google.com/d/optout. > > > > -- > > Cordialement, Coues Ludovic > +336 148 743 42 > -- You received this message because you are subscribed to the Google Groups "Django users" group. To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscr...@googlegroups.com. To post to this group, send email to django-users@googlegroups.com. Visit this group at https://groups.google.com/group/django-users. To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/f95da39d-c5b7-4c06-ae8b-e817d416d444%40googlegroups.com. For more options, visit https://groups.google.com/d/optout.
Re: Entering initial data into django database
First, you should create a fixture file with some sample data. Two entry, just like in the documentation is good. This way, you know you have a working fixture file. Then, you write a python function which take a list of bet and output a fixture file just like the exemple you have done. Finally, you adjust you scraper to build the list, use the function to transform the list into a fixture file and import the fixture file. 2016-03-20 20:02 GMT+01:00 Lawrence Muriuki: > > Thanks ludovic, here is my code for the scraper.. > > > > > > from .models import Betting > > import re > import requests > import urllib > from bs4 import BeautifulSoup > > > urls= "https://sms.betyetu.co.ke/tomorrow.html; > htmlfile = urllib.urlopen(urls) > htmltext = htmlfile.read() > soup = BeautifulSoup(htmltext, "html.parser") > > > for i in soup.findAll("table"): > print i.contents[1].contents[1].findAll("th")[0].text > print i.contents[1].contents[3].findAll("th")[0].text > > > > > > > > try: > momo = 1 > a = len( i.contents[3].contents) > while momo <= a: > print i.contents[3].contents[momo].findAll("td")[2].text > > foo = > Betting(matches=i.contents[3].contents[momo].findAll("td")[2].text) > > momo += 2 > > > foo.save() > > > > > except: > momo = 1 > > > > > > > > I have a model called "betting" which has only one field "matches"..For it > to work, I have placed it in init.py which is a wrong way to do it..Wanted > to understand where this code should be placed..ie..which file and how to > interact with it > >> > -- > You received this message because you are subscribed to the Google Groups > "Django users" group. > To unsubscribe from this group and stop receiving emails from it, send an > email to django-users+unsubscr...@googlegroups.com. > To post to this group, send email to django-users@googlegroups.com. > Visit this group at https://groups.google.com/group/django-users. > To view this discussion on the web visit > https://groups.google.com/d/msgid/django-users/d3677ab5-06eb-47aa-bdf8-d789a4c454b7%40googlegroups.com. > > For more options, visit https://groups.google.com/d/optout. -- Cordialement, Coues Ludovic +336 148 743 42 -- You received this message because you are subscribed to the Google Groups "Django users" group. To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscr...@googlegroups.com. To post to this group, send email to django-users@googlegroups.com. Visit this group at https://groups.google.com/group/django-users. To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/CAEuG%2BTaw7p8nH_iv2c0UBDHC5%3De4-wjAQJvZ89Qc493Scx2Jjw%40mail.gmail.com. For more options, visit https://groups.google.com/d/optout.
Re: Entering initial data into django database
Thanks ludovic, here is my code for the scraper.. from .models import Betting import re import requests import urllib from bs4 import BeautifulSoup urls= "https://sms.betyetu.co.ke/tomorrow.html; htmlfile = urllib.urlopen(urls) htmltext = htmlfile.read() soup = BeautifulSoup(htmltext, "html.parser") for i in soup.findAll("table"): print i.contents[1].contents[1].findAll("th")[0].text print i.contents[1].contents[3].findAll("th")[0].text try: momo = 1 a = len( i.contents[3].contents) while momo <= a: print i.contents[3].contents[momo].findAll("td")[2].text foo = Betting(matches=i.contents[3].contents[momo].findAll("td" )[2].text) momo += 2 foo.save() except: momo = 1 I have a model called "betting" which has only one field "matches"..For it to work, I have placed it in init.py which is a wrong way to do it..Wanted to understand where this code should be placed..ie..which file and how to interact with it > -- You received this message because you are subscribed to the Google Groups "Django users" group. To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscr...@googlegroups.com. To post to this group, send email to django-users@googlegroups.com. Visit this group at https://groups.google.com/group/django-users. To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/d3677ab5-06eb-47aa-bdf8-d789a4c454b7%40googlegroups.com. For more options, visit https://groups.google.com/d/optout.
Re: Entering initial data into django database
There is a page in the documentation dealing with initial data [1]. The good news is that you don't have to write more code. You insert your data in a file and load it with the manage.py command. Out of the box, JSON, XML and SQL are supported. [1] https://docs.djangoproject.com/en/1.9/howto/initial-data/ 2016-03-20 19:05 GMT+01:00 Lawrence Muriuki <muriukiwanderilawre...@gmail.com>: > Hi All, > > I have built a web scraper to scrape a website and get all match fixtures > for a particular day. Wanted to know how to insert that initial data into > django database and where that code should live..I have currently put the > code in init.py but it looks and sounds wrong according to a quick google > search.. > > Any help will be appreciated.. > Thank You > > -- > You received this message because you are subscribed to the Google Groups > "Django users" group. > To unsubscribe from this group and stop receiving emails from it, send an > email to django-users+unsubscr...@googlegroups.com. > To post to this group, send email to django-users@googlegroups.com. > Visit this group at https://groups.google.com/group/django-users. > To view this discussion on the web visit > https://groups.google.com/d/msgid/django-users/3de1d2d2-b774-4c39-b5b8-2b9602cff829%40googlegroups.com. > For more options, visit https://groups.google.com/d/optout. -- Cordialement, Coues Ludovic +336 148 743 42 -- You received this message because you are subscribed to the Google Groups "Django users" group. To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscr...@googlegroups.com. To post to this group, send email to django-users@googlegroups.com. Visit this group at https://groups.google.com/group/django-users. To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/CAEuG%2BTb0x%3D6JnrPZmOT0vLjZO-n2rh6TOoOkp0SkWTaRwSy_eA%40mail.gmail.com. For more options, visit https://groups.google.com/d/optout.
Entering initial data into django database
Hi All, I have built a web scraper to scrape a website and get all match fixtures for a particular day. Wanted to know how to insert that initial data into django database and where that code should live..I have currently put the code in init.py but it looks and sounds wrong according to a quick google search.. Any help will be appreciated.. Thank You -- You received this message because you are subscribed to the Google Groups "Django users" group. To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscr...@googlegroups.com. To post to this group, send email to django-users@googlegroups.com. Visit this group at https://groups.google.com/group/django-users. To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/3de1d2d2-b774-4c39-b5b8-2b9602cff829%40googlegroups.com. For more options, visit https://groups.google.com/d/optout.
Re: manage.py --keepdb VS DataMigration as Initial Data
Exactly . thanks. I'm happy i'm not alone ;) ... and did nothing wrong. .. I was thinking what could be done in the core to solve... The easyiest way, is keeping flushing data at the end of the tests, but run data inserts in migrations when the tests starts, even when --keepdb is present ... still thinking . - Cadu Leite G+: google.com/+CarlosLeite twitter: @cadu_leite site: http://people.python.org.br/ On Thu, Feb 11, 2016 at 9:59 PM, Tim Graham <timogra...@gmail.com> wrote: > You might be running into the same problem reported in > https://code.djangoproject.com/ticket/25251#comment:3 > > > On Thursday, February 11, 2016 at 1:16:20 PM UTC-5, Carlos Leite wrote: >> >> Hi there, >> >> I'm running a Django==1.8 app >> I read in the docs [1], to consider doing a data migration to load >> initial data on db, since initial fixture is consider deprecated since >> 1.7. >> >> Well, to keep my app up-to-date I choose to load "initial data" trough a >> data migration. >> >> My problem, SEEMS to be when I run tests using the "--keepdb" >> >> $> python manage.py --keepdb >> >> The second time I run into tests, the inital data is loss! >> >> is there a pattern to solve that, or i need code on tests to check de >> initial data and reload it ? >> >> >> [1] >> https://docs.djangoproject.com/en/1.8/howto/initial-data/#automatically-loading-initial-data-fixtures >> >> - >> Cadu Leite >> >> G+: google.com/+CarlosLeite >> twitter: @cadu_leite >> site: http://people.python.org.br/ >> > -- > You received this message because you are subscribed to the Google Groups > "Django users" group. > To unsubscribe from this group and stop receiving emails from it, send an > email to django-users+unsubscr...@googlegroups.com. > To post to this group, send email to django-users@googlegroups.com. > Visit this group at https://groups.google.com/group/django-users. > To view this discussion on the web visit > https://groups.google.com/d/msgid/django-users/644e763e-330e-48fc-9912-10fa548d9461%40googlegroups.com > <https://groups.google.com/d/msgid/django-users/644e763e-330e-48fc-9912-10fa548d9461%40googlegroups.com?utm_medium=email_source=footer> > . > For more options, visit https://groups.google.com/d/optout. > -- You received this message because you are subscribed to the Google Groups "Django users" group. To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscr...@googlegroups.com. To post to this group, send email to django-users@googlegroups.com. Visit this group at https://groups.google.com/group/django-users. To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/CAEM6-QJUWi%2BZ1e4dTc4h1i95s_91D-P-%2Bienh4jfAmyqR-RzSQ%40mail.gmail.com. For more options, visit https://groups.google.com/d/optout.
Re: manage.py --keepdb VS DataMigration as Initial Data
You might be running into the same problem reported in https://code.djangoproject.com/ticket/25251#comment:3 On Thursday, February 11, 2016 at 1:16:20 PM UTC-5, Carlos Leite wrote: > > Hi there, > > I'm running a Django==1.8 app > I read in the docs [1], to consider doing a data migration to load initial > data on db, since initial fixture is consider deprecated since 1.7. > > Well, to keep my app up-to-date I choose to load "initial data" trough a > data migration. > > My problem, SEEMS to be when I run tests using the "--keepdb" > > $> python manage.py --keepdb > > The second time I run into tests, the inital data is loss! > > is there a pattern to solve that, or i need code on tests to check de > initial data and reload it ? > > > [1] > https://docs.djangoproject.com/en/1.8/howto/initial-data/#automatically-loading-initial-data-fixtures > > - > Cadu Leite > > G+: google.com/+CarlosLeite > twitter: @cadu_leite > site: http://people.python.org.br/ > -- You received this message because you are subscribed to the Google Groups "Django users" group. To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscr...@googlegroups.com. To post to this group, send email to django-users@googlegroups.com. Visit this group at https://groups.google.com/group/django-users. To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/644e763e-330e-48fc-9912-10fa548d9461%40googlegroups.com. For more options, visit https://groups.google.com/d/optout.
manage.py --keepdb VS DataMigration as Initial Data
Hi there, I'm running a Django==1.8 app I read in the docs [1], to consider doing a data migration to load initial data on db, since initial fixture is consider deprecated since 1.7. Well, to keep my app up-to-date I choose to load "initial data" trough a data migration. My problem, SEEMS to be when I run tests using the "--keepdb" $> python manage.py --keepdb The second time I run into tests, the inital data is loss! is there a pattern to solve that, or i need code on tests to check de initial data and reload it ? [1] https://docs.djangoproject.com/en/1.8/howto/initial-data/#automatically-loading-initial-data-fixtures - Cadu Leite G+: google.com/+CarlosLeite twitter: @cadu_leite site: http://people.python.org.br/ -- You received this message because you are subscribed to the Google Groups "Django users" group. To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscr...@googlegroups.com. To post to this group, send email to django-users@googlegroups.com. Visit this group at https://groups.google.com/group/django-users. To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/CAEM6-QLvZv-tcJ%3DnmO92OovvnKz9NoevJbHCW39t2vR2_DJhOQ%40mail.gmail.com. For more options, visit https://groups.google.com/d/optout.
Initial data in 1.7
Hi there, as pointed in documentation [1], automatic loading of initial data from initial_data.[xml/yaml/json] is deprecated since 1.7 in favor of data migrations. However, there are several drawbacks and differencies: 1. Data migration is executed only once (unless migrations are rewinded to the beginning), while initial_data were loaded everytime with syncdb command. Former behavior ensures that the right data are present in table. Of course it can be used with data which doesn't change often (like sites). 2. It's not straightforward to provide initial data to existing or third-party apps. One have to create custom app to store migrations (like 'initial_data') and then create *empty* models.py in app directory. Otherwise migrations won't be loaded, as already pointed in [2]. What's the correct way to provide initial data to apps which needs to be present everytime, otherwise website won't work (like sites, auth token, superadmins, etc.)? Have anyone solved this issue recently in Django 1.7? Thanks, Tom [1] https://docs.djangoproject.com/en/dev/howto/initial-data/#automatically-loading-initial-data-fixtures [2] https://groups.google.com/d/msgid/django-users/20140715142108.GA10827%40rkade-thinkpad -- You received this message because you are subscribed to the Google Groups "Django users" group. To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscr...@googlegroups.com. To post to this group, send email to django-users@googlegroups.com. Visit this group at http://groups.google.com/group/django-users. To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/20140721191447.46b17e63%40bodhi. For more options, visit https://groups.google.com/d/optout.
set initial data to django-haystacks FacetedSearchForm
I have been digging around for about 24 hours now and am still not able to solve this. I am using a 'haystack.forms.FacetedSearchForm' and want set some initial field values to some of the form fields. Here are some more details on what I am trying to do. http://stackoverflow.com/questions/16340222/set-fields-initial-value-within-haystacks-facetedsearchform after a few hours of diggin around the code and documentation, I realized that we can not set inital values for a bound form and `FacetedSearchForm` is initialized in a method called `build_form` under `haystack.views.SearchView` I tried overriding the method and it still doesn't work. Is there a way we can set inital data to a bound form at all ? -- You received this message because you are subscribed to the Google Groups "Django users" group. To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscr...@googlegroups.com. To post to this group, send email to django-users@googlegroups.com. Visit this group at http://groups.google.com/group/django-users?hl=en. For more options, visit https://groups.google.com/groups/opt_out.
Re: Django inline formsets, force initial data to be saved.
On Tue, Mar 5, 2013 at 4:43 PM, Marc Aymerich <glicer...@gmail.com> wrote: > > > On Tue, Mar 5, 2013 at 3:11 AM, Russell Keith-Magee < > russ...@keith-magee.com> wrote: > >> >> >> On Mon, Mar 4, 2013 at 10:31 PM, Marc Aymerich <glicer...@gmail.com>wrote: >> >>> Hi, >>> I've spend several hours trying to figure out how to save inlines with >>> initial data in them. >>> >>> basically I have a very simple model with 2 fields: >>> >>> class DirectIface(models.Model): >>> parent = models.ForeignKey('nodes.Node') >>> name = models.CharField(max_lenght=64) >>> >>> And what I'm doing is defining a formset with initial data in it: >>> >>> class DirectIfaceInlineFormSet(BaseInlineFormSet): >>> def __init__(self, *args, **kwargs): >>> kwargs['initial'] = [{ 'name': 'eth1', }, {'name': 'eth2'},] >>> super(DirectIfaceInlineFormSet, self).__init__(*args, **kwargs) >>> >>> >>> In this case 2 Direct ifaces with names eth1 and eth2. >>> >>> The problem is that those ifaces doesn't get stored when I hit the save >>> button, that's because has_changed == False. >>> So is there a way to tell Django to save formsets with only initial data >>> ? >>> >> >> Sure - just provide the initial data as actual data. If, instead of using >> 'initial', you pass the same content as 'data', the form will be saveable. >> > > Jops, just tried > > > class DirectIfaceInlineFormSet(BaseInlineFormSet): > def __init__(self, *args, **kwargs): > kwargs['data'] = [{ 'name': 'eth1', }, {'name': 'eth2'},] > super(DirectIfaceInlineFormSet, self).__init__(*args, **kwargs) > > but I'm getting an AttributeError "'list' object has no attribute 'get'" > when i'm rendering the form. > yeah, finally I did something like class DirectIfaceInlineFormSet(BaseInlineFormSet): def __init__(self, *args, **kwargs): if not kwargs['instance'].pk: kwargs['data'] = { 'direct_ifaces-TOTAL_FORMS': u'3', 'direct_ifaces-INITIAL_FORMS': u'0', 'direct_ifaces-MAX_NUM_FORMS': u'', 'direct_ifaces-0-name': u'eth0', 'direct_ifaces-1-name': u'eth1', 'direct_ifaces-2-name': u'eth2',} else: self.extra = 1 super(DirectIfaceInlineFormSet, self).__init__(*args, **kwargs) that it works :) -- Marc -- You received this message because you are subscribed to the Google Groups "Django users" group. To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscr...@googlegroups.com. To post to this group, send email to django-users@googlegroups.com. Visit this group at http://groups.google.com/group/django-users?hl=en. For more options, visit https://groups.google.com/groups/opt_out.
Re: Django inline formsets, force initial data to be saved.
On Tue, Mar 5, 2013 at 3:11 AM, Russell Keith-Magee <russ...@keith-magee.com > wrote: > > > On Mon, Mar 4, 2013 at 10:31 PM, Marc Aymerich <glicer...@gmail.com>wrote: > >> Hi, >> I've spend several hours trying to figure out how to save inlines with >> initial data in them. >> >> basically I have a very simple model with 2 fields: >> >> class DirectIface(models.Model): >> parent = models.ForeignKey('nodes.Node') >> name = models.CharField(max_lenght=64) >> >> And what I'm doing is defining a formset with initial data in it: >> >> class DirectIfaceInlineFormSet(BaseInlineFormSet): >> def __init__(self, *args, **kwargs): >> kwargs['initial'] = [{ 'name': 'eth1', }, {'name': 'eth2'},] >> super(DirectIfaceInlineFormSet, self).__init__(*args, **kwargs) >> >> >> In this case 2 Direct ifaces with names eth1 and eth2. >> >> The problem is that those ifaces doesn't get stored when I hit the save >> button, that's because has_changed == False. >> So is there a way to tell Django to save formsets with only initial data ? >> > > Sure - just provide the initial data as actual data. If, instead of using > 'initial', you pass the same content as 'data', the form will be saveable. > Jops, just tried class DirectIfaceInlineFormSet(BaseInlineFormSet): def __init__(self, *args, **kwargs): kwargs['data'] = [{ 'name': 'eth1', }, {'name': 'eth2'},] super(DirectIfaceInlineFormSet, self).__init__(*args, **kwargs) but I'm getting an AttributeError "'list' object has no attribute 'get'" when i'm rendering the form. http://dpaste.com/1013099/ What i've missed ? Thanks again ! -- Marc -- You received this message because you are subscribed to the Google Groups "Django users" group. To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscr...@googlegroups.com. To post to this group, send email to django-users@googlegroups.com. Visit this group at http://groups.google.com/group/django-users?hl=en. For more options, visit https://groups.google.com/groups/opt_out.
Re: Django inline formsets, force initial data to be saved.
On Tue, Mar 5, 2013 at 3:11 AM, Russell Keith-Magee <russ...@keith-magee.com > wrote: > > > On Mon, Mar 4, 2013 at 10:31 PM, Marc Aymerich <glicer...@gmail.com>wrote: > >> Hi, >> I've spend several hours trying to figure out how to save inlines with >> initial data in them. >> >> basically I have a very simple model with 2 fields: >> >> class DirectIface(models.Model): >> parent = models.ForeignKey('nodes.Node') >> name = models.CharField(max_lenght=64) >> >> And what I'm doing is defining a formset with initial data in it: >> >> class DirectIfaceInlineFormSet(BaseInlineFormSet): >> def __init__(self, *args, **kwargs): >> kwargs['initial'] = [{ 'name': 'eth1', }, {'name': 'eth2'},] >> super(DirectIfaceInlineFormSet, self).__init__(*args, **kwargs) >> >> >> In this case 2 Direct ifaces with names eth1 and eth2. >> >> The problem is that those ifaces doesn't get stored when I hit the save >> button, that's because has_changed == False. >> So is there a way to tell Django to save formsets with only initial data ? >> > > Sure - just provide the initial data as actual data. If, instead of using > 'initial', you pass the same content as 'data', the form will be saveable. > Thank you Russ, you've saved my day ! :) -- Marc -- You received this message because you are subscribed to the Google Groups "Django users" group. To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscr...@googlegroups.com. To post to this group, send email to django-users@googlegroups.com. Visit this group at http://groups.google.com/group/django-users?hl=en. For more options, visit https://groups.google.com/groups/opt_out.
Django inline formsets, force initial data to be saved.
Hi, I've spend several hours trying to figure out how to save inlines with initial data in them. basically I have a very simple model with 2 fields: class DirectIface(models.Model): parent = models.ForeignKey('nodes.Node') name = models.CharField(max_lenght=64) And what I'm doing is defining a formset with initial data in it: class DirectIfaceInlineFormSet(BaseInlineFormSet): def __init__(self, *args, **kwargs): kwargs['initial'] = [{ 'name': 'eth1', }, {'name': 'eth2'},] super(DirectIfaceInlineFormSet, self).__init__(*args, **kwargs) In this case 2 Direct ifaces with names eth1 and eth2. The problem is that those ifaces doesn't get stored when I hit the save button, that's because has_changed == False. So is there a way to tell Django to save formsets with only initial data ? Thanks ! -- Marc -- You received this message because you are subscribed to the Google Groups "Django users" group. To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscr...@googlegroups.com. To post to this group, send email to django-users@googlegroups.com. Visit this group at http://groups.google.com/group/django-users?hl=en. For more options, visit https://groups.google.com/groups/opt_out.
Re: Initial data for dynamic field
On Fri, 23 Dec 2011 09:42:37 +0100, Menguwrote: you need to set "initial" attribute of TypedChoiceField. Thanks, I knew about the initial only on form instance and not on field :) On Dec 23, 10:34 am, Martin Tiršel wrote: Hello, I have: class SomeForm(forms.Form): ... def __init__(self, *args, **kwargs): ... super(SomeForm, self).__init__(*args, **kwargs) ... self.fields['starting_location'] = forms.TypedChoiceField( label=_('Starting location'), choices=DIRECTIONS_CHOICES, coerce=int ) Now I want to choose as initial selection one random item from DIRECTIONS_CHOICES choices but I have to do it in this __init__() method (not in view!). How can I achieve this? Thanks, Martin -- 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: Initial data for dynamic field
you need to set "initial" attribute of TypedChoiceField. On Dec 23, 10:34 am, Martin Tiršelwrote: > Hello, > > I have: > > class SomeForm(forms.Form): > ... > > def __init__(self, *args, **kwargs): > ... > super(SomeForm, self).__init__(*args, **kwargs) > ... > self.fields['starting_location'] = forms.TypedChoiceField( > label=_('Starting location'), > choices=DIRECTIONS_CHOICES, > coerce=int > ) > > Now I want to choose as initial selection one random item from > DIRECTIONS_CHOICES choices but I have to do it in this __init__() method > (not in view!). How can I achieve this? > > Thanks, > Martin -- 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.
Initial data for dynamic field
Hello, I have: class SomeForm(forms.Form): ... def __init__(self, *args, **kwargs): ... super(SomeForm, self).__init__(*args, **kwargs) ... self.fields['starting_location'] = forms.TypedChoiceField( label=_('Starting location'), choices=DIRECTIONS_CHOICES, coerce=int ) Now I want to choose as initial selection one random item from DIRECTIONS_CHOICES choices but I have to do it in this __init__() method (not in view!). How can I achieve this? Thanks, Martin -- 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: initial data to Formset causing problem
Have you called form.is_valid() somewhere that you're not showing? On Wed, Nov 9, 2011 at 7:15 AM, Asif Jamadar <asif.jama...@rezayat.net> wrote: > I’m assigning initial data to the field of each formset dynamically. But > when I’m trying to save that initial data it’s throwing “Key Error” in > cleaned data. Any solution? > > > > > > Here is the code: > > > > In views.py > > > > for form in formset.forms: > > > > question = form.save(commit=False) > > > > answer_value = form.cleaned_data['answer'] > > > > shade_value = form.cleaned_data['shade'] > > > > # rest of the code goes here > > > > question.save() > > > > > > Here ‘answer’ and ‘shade’ are choicefield. > > > > > > > > -- > 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. > -- 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.
initial data to Formset causing problem
I'm assigning initial data to the field of each formset dynamically. But when I'm trying to save that initial data it's throwing "Key Error" in cleaned data. Any solution? Here is the code: In views.py for form in formset.forms: question = form.save(commit=False) answer_value = form.cleaned_data['answer'] shade_value = form.cleaned_data['shade'] # rest of the code goes here question.save() Here 'answer' and 'shade' are choicefield. -- 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: Initial data for ManyToMany field
this initial can be a queryset or a list, but the list must use its primary key like sform = SymptomeForm(initial={'parent':[1,2]}) On 9月7日, 上午4时30分, Thomas49wrote: > Hello, > > I have two models, and the second contains a ManyToMany relationship: > > class TypeMedical(models.Model): >... > > class Symptome(TypeMedical): > ... > parent = > models.ManyToManyField(TypeMedical,related_name='Parent',blank=True) > ... > > Then, I use a ModelForm in order to save data. > > class SymptomeForm(ModelForm): > class Meta: > model = Symptome > > When I create a form, sometimes I want to select a field in "parent". > How can I do that? I tried many things but nothing works. Ex: > sform = SymptomeForm(initial={'parent':["Acupuncture",]}) > > I hope someone can help! Thanks, > > Thomas. -- 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: Initial data for ManyToMany field
> Look into formsets. It's what the admin inlines use. that is class TypeMedicalForm(forms.ModelForm): class Meta: model = TypeMedical TypeMedicalFormSet=formset_factory(TypeMedicalForm) take a look at the django docs for more details -- "The whole of Japan is pure invention. There is no such country, there are no such people" --Oscar Wilde |_|0|_| |_|_|0| |0|0|0| (\__/) (='.'=)This is Bunny. Copy and paste bunny (")_(") to help him gain world domination. -- 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: Initial data for ManyToMany field
Look into formsets. It's what the admin inlines use. On Tue, Sep 6, 2011 at 5:40 PM, Nanwrote: > > Because SymptomeForm is a ModelForm, it will initialize its "parent" > field as a ModelMultipleChoiceField, which I believe must be > initialized with a queryset instead of a list. > > On Sep 6, 4:30 pm, Thomas49 wrote: > > Hello, > > > > I have two models, and the second contains a ManyToMany relationship: > > > > class TypeMedical(models.Model): > >... > > > > class Symptome(TypeMedical): > > ... > > parent = > > models.ManyToManyField(TypeMedical,related_name='Parent',blank=True) > > ... > > > > Then, I use a ModelForm in order to save data. > > > > class SymptomeForm(ModelForm): > > class Meta: > > model = Symptome > > > > When I create a form, sometimes I want to select a field in "parent". > > How can I do that? I tried many things but nothing works. Ex: > > sform = SymptomeForm(initial={'parent':["Acupuncture",]}) > > > > I hope someone can help! Thanks, > > > > Thomas. > > -- > 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. > > -- "The whole of Japan is pure invention. There is no such country, there are no such people" --Oscar Wilde |_|0|_| |_|_|0| |0|0|0| (\__/) (='.'=)This is Bunny. Copy and paste bunny (")_(") to help him gain world domination. -- 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: Initial data for ManyToMany field
Because SymptomeForm is a ModelForm, it will initialize its "parent" field as a ModelMultipleChoiceField, which I believe must be initialized with a queryset instead of a list. On Sep 6, 4:30 pm, Thomas49wrote: > Hello, > > I have two models, and the second contains a ManyToMany relationship: > > class TypeMedical(models.Model): > ... > > class Symptome(TypeMedical): > ... > parent = > models.ManyToManyField(TypeMedical,related_name='Parent',blank=True) > ... > > Then, I use a ModelForm in order to save data. > > class SymptomeForm(ModelForm): > class Meta: > model = Symptome > > When I create a form, sometimes I want to select a field in "parent". > How can I do that? I tried many things but nothing works. Ex: > sform = SymptomeForm(initial={'parent':["Acupuncture",]}) > > I hope someone can help! Thanks, > > Thomas. -- 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.
Initial data for ManyToMany field
Hello, I have two models, and the second contains a ManyToMany relationship: class TypeMedical(models.Model): ... class Symptome(TypeMedical): ... parent = models.ManyToManyField(TypeMedical,related_name='Parent',blank=True) ... Then, I use a ModelForm in order to save data. class SymptomeForm(ModelForm): class Meta: model = Symptome When I create a form, sometimes I want to select a field in "parent". How can I do that? I tried many things but nothing works. Ex: sform = SymptomeForm(initial={'parent':["Acupuncture",]}) I hope someone can help! Thanks, Thomas. -- 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: how to implement a data grid? (or populate inlineformset with initial data)
Thanks for your reply, Daniel. I read the docs, but did not understand them properly. Your explanation makes sense, but doesn't seem to be working for me, for some reason. I followed the docs from https://docs.djangoproject.com/en/1.3/topics/forms/modelforms/#inline-formsets precisely, but am getting and error that my relation does not exist. I think it may have something to do with not using a default database. The funny thing is, I can access the related records fine from the parent instance (i.e. user.josjeventsregistration_set). Do you need to explicitly tell inlineformset to use a non-default DB somehow? In [1]: from django.forms.models import inlineformset_factory In [2]: from classes.models import JosUsers, JosJeventsRegistration In [3]: RegistrationFormSet = inlineformset_factory(JosUsers, JosJeventsRegistration) In [4]: user = JosUsers.objects.using('mydevdb').get(pk='1234') In [5]: fs = RegistrationFormSet(instance=user) ERROR: An unexpected error occurred while tokenizing input The following traceback may be corrupted or invalid The error message is: ('EOF in multi-line statement', (13, 0)) --- DatabaseError Traceback (most recent call last) /home/tony/sandbox/django/dashboard/ in () /home/tony/sandbox/django/env/lib/python2.6/site-packages/django/forms/ models.pyc in __init__(self, data, files, instance, save_as_new, prefix, queryset) 680 qs = queryset.filter(**{self.fk.name: self.instance}) 681 super(BaseInlineFormSet, self).__init__(data, files, prefix=prefix, --> 682 queryset=qs) 683 684 def initial_form_count(self): /home/tony/sandbox/django/env/lib/python2.6/site-packages/django/forms/ models.pyc in __init__(self, data, files, auto_id, prefix, queryset, **kwargs) 413 defaults = {'data': data, 'files': files, 'auto_id': auto_id, 'prefix': prefix} 414 defaults.update(kwargs) --> 415 super(BaseModelFormSet, self).__init__(**defaults) 416 417 def initial_form_count(self): /home/tony/sandbox/django/env/lib/python2.6/site-packages/django/forms/ formsets.pyc in __init__(self, data, files, auto_id, prefix, initial, error_class) 45 self._non_form_errors = None 46 # construct the forms in the formset ---> 47 self._construct_forms() 48 49 def __unicode__(self): /home/tony/sandbox/django/env/lib/python2.6/site-packages/django/forms/ formsets.pyc in _construct_forms(self) 105 # instantiate all the forms and put them in self.forms 106 self.forms = [] --> 107 for i in xrange(self.total_form_count()): 108 self.forms.append(self._construct_form(i)) 109 /home/tony/sandbox/django/env/lib/python2.6/site-packages/django/forms/ formsets.pyc in total_form_count(self) 81 return self.management_form.cleaned_data[TOTAL_FORM_COUNT] 82 else: ---> 83 initial_forms = self.initial_form_count() 84 total_forms = initial_forms + self.extra 85 # Allow all existing related objects/inlines to be displayed, /home/tony/sandbox/django/env/lib/python2.6/site-packages/django/forms/ models.pyc in initial_form_count(self) 685 if self.save_as_new: 686 return 0 --> 687 return super(BaseInlineFormSet, self).initial_form_count() 688 689 /home/tony/sandbox/django/env/lib/python2.6/site-packages/django/forms/ models.pyc in initial_form_count(self) 418 """Returns the number of forms that are required in this FormSet.""" 419 if not (self.data or self.files): --> 420 return len(self.get_queryset()) 421 return super(BaseModelFormSet, self).initial_form_count() 422 /home/tony/sandbox/django/env/lib/python2.6/site-packages/django/db/ models/query.pyc in __len__(self) 80 self._result_cache = list(self._iter) 81 else: ---> 82 self._result_cache = list(self.iterator()) 83 elif self._iter: 84 self._result_cache.extend(self._iter) /home/tony/sandbox/django/env/lib/python2.6/site-packages/django/db/ models/query.pyc in iterator(self) 271 model = self.model 272 compiler = self.query.get_compiler(using=db) --> 273 for row in compiler.results_iter(): 274 if fill_cache: 275 obj, _ = get_cached_row(model, row, /home/tony/sandbox/django/env/lib/python2.6/site-packages/django/db/ models/sql/compiler.pyc in results_iter(self) 678 fields = None 679 has_aggregate_select = bool(self.query.aggregate_select) --> 680 for rows in self.execute_sql(MULTI): 681 for row in rows: 682 if resolve_columns:
Re: how to implement a data grid? (or populate inlineformset with initial data)
On Tuesday, 31 May 2011 15:20:11 UTC+1, snfctech wrote: > > Thanks, Jayapal. > > I was hoping there was a little less java/ more django way to do this > by utilizing a Django ModelForm or InlindeFormSet and rendering > partial views. > > So am I missing the point of InlineFormSets? Can these not be > populated with data so they can be used to edit a set of existing > records? > > Thanks. > > Tony > No, you're not missing the point - that is exactly what model formsets are for. But you haven't read the documentation very closely: InlineFormsets are meant for editing only those elements that are related via ForeignKey to a specific object, so it is that related object that you pass to the formset via the `instance` parameter. The documentation shows this clearly: https://docs.djangoproject.com/en/1.3/topics/forms/modelforms/#inline-formsets If you want to edit the elements of a queryset that aren't necessarily all related to the same object, you just use a standard ModelFormset, which does take a `queryset` argument - again, as shown in the docs: https://docs.djangoproject.com/en/1.3/topics/forms/modelforms/#using-a-custom-queryset -- DR. -- 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: how to implement a data grid? (or populate inlineformset with initial data)
On Tue, May 31, 2011 at 9:20 AM, snfctechwrote: > I was hoping there was a little less java/ more django way to do this i haven't seen any Java around Dojo toolkit -- Javier -- 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: how to implement a data grid? (or populate inlineformset with initial data)
Thanks, Jayapal. I was hoping there was a little less java/ more django way to do this by utilizing a Django ModelForm or InlindeFormSet and rendering partial views. So am I missing the point of InlineFormSets? Can these not be populated with data so they can be used to edit a set of existing records? Thanks. Tony On May 31, 12:03 am, jai_pythonwrote: > Hi, > Long back i had used Dojodatagrid, plz go through my > bloghttp://jayapal-d.blogspot.com/2009/08/dojo-datagrid-with-editable-cel... > > I am sure that we can do with jquery. > > Lemme know if u required any help. > > Thanks, > Jayapal > > On May 31, 6:39 am, snfctech wrote: > > > I want to display a list of records that have some editable fields and > > some readonly fields, as well as asynchronously add new records to the > > list. I thought the way to start would be with an InlineFormSet - but > > I can't figure out how to populate my formset with initialdata. E.g. > > MyInlineFormset(queryset=myquery.all()) or > > MyInlineFormset(data=myquery.vales()) doesn't do the trick. > > > Can someone steer me in the right direction? > > > Thanks. -- 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: how to implement a data grid? (or populate inlineformset with initial data)
Hi, Long back i had used Dojo data grid, plz go through my blog http://jayapal-d.blogspot.com/2009/08/dojo-datagrid-with-editable-cells-in.html I am sure that we can do with jquery. Lemme know if u required any help. Thanks, Jayapal On May 31, 6:39 am, snfctech <tschm...@sacfoodcoop.com> wrote: > I want to display a list of records that have some editable fields and > some readonly fields, as well as asynchronously add new records to the > list. I thought the way to start would be with an InlineFormSet - but > I can't figure out how to populate my formset with initial data. E.g. > MyInlineFormset(queryset=myquery.all()) or > MyInlineFormset(data=myquery.vales()) doesn't do the trick. > > Can someone steer me in the right direction? > > Thanks. -- 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.
how to implement a data grid? (or populate inlineformset with initial data)
I want to display a list of records that have some editable fields and some readonly fields, as well as asynchronously add new records to the list. I thought the way to start would be with an InlineFormSet - but I can't figure out how to populate my formset with initial data. E.g. MyInlineFormset(queryset=myquery.all()) or MyInlineFormset(data=myquery.vales()) doesn't do the trick. Can someone steer me in the right direction? Thanks. -- 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: Loading initial data with a post_syncdb hook?
On May 9, 12:24 pm, Karen Traceywrote: > On Mon, May 9, 2011 at 12:56 AM, Adam Seering wrote: > > On May 8, 10:53 pm, Karen Tracey wrote:> > > > The change you have noticed is documented in the 1.3 > > > backwards-incompatibility list: > >http://docs.djangoproject.com/en/1.3/releases/1.3/#use-of-custom-sql-... > > > Actually, that's a different issue: I'm not using the custom-SQL > > loader, I'm using Python code with the post_syncdb hook. This one > > isn't in the backwards-compatibility page as far as I can tell. > > > (Was that comment intended to cover this case as well? Maybe a typo > > somewhere?) > > Hmm, you are right, this change is not supposed to affect data added via > post_syncdb handlers. Specifically the change here > is:https://code.djangoproject.com/changeset/15239. On an initial read it looks > like it might cause post_syncdb-added data to get thrown away, since the > post_syncdb signal is sent during the call_command('syncdb'). However, the > call_command('flush', ...) that was added after the call_command('syncdb', > ...) will also cause that signal to get sent. Ah, I see what's going on. Apologies; it sounds like this was a mess- up / misunderstanding on my part: Our syncdb hooks aren't safely reentrant or re-runnable; they're not idempotent, and they depend for correctness on having a clear django.core.cache to run queries against and to push stuff into (or at least a cache that we haven't already stuffed rows into that have since been deleted from the database but not the cache; we have a fancy system that listens to post_delete to keep the cache in sync with the database, but it looks like "flush" doesn't fire post_delete?). Most were written prior to Django's handy "dispatch_uid" deduplication mechanism, so they have a simple one-off global latch that only allows them to run once. So they ran once for the syncdb, then the "flush" cleared out all the database data and they didn't run again the second time around. My mistake was to look at the queries being sent to the database, see the data being loaded and the following TRUNCATE, and assume that things were supposed to stop there. (Out of curiosity, any idea why this was done this way? It feels a bit odd to me to generate data, throw it out, and generate it again... Could the SQL-loader just be turned off during "./manage.py test" runs?) This mostly leads to a nice clean obvious solution: Make our loading functions be safely reentrant and go start using dispatch_uid. One new problem, though: We'll have to do something to flush the cache whenever "flush" is called, so that stale data doesn't get left behind. Should be quite doable, if a little clunky. > > Right now, we're working on adding tests, and on encouraging > > developers to write tests for new parts of the code, new apps/code > > that are being developed, etc. Right now, as I understand it with > > Django's current behavior and our post_syncdb hook setup, we want to > > re-load the data in three cases: (1) The current test is the first > > test, (2) all prior tests are TestCase (as opposed to > > TransactionTestCase) instances, or (3) we are a TransactionTestCase > > instance. > > (...) In fact > Django will run all TestCase tests before any TransactionTestCase tests (as > noted in the > dochttp://docs.djangoproject.com/en/1.3/topics/testing/#testcase), precisely > because the mechanism used to reset the database for these different kinds > of tests can't ensure that a TestCase run after a TransactionTestCase will > see a "clean" database on start. Ah, ok: Because that text listed "(e.g. doctests)" as the counterexample, and since it seemed to be comparing both django.test.TestCase and django.test.TransactionTestCase, I took the first sentence of that paragraph to mean "A unittest.TestCase, on the other hand, ...". If all the TransactionTestCases are at the end as well, then that does in fact get rid of the weird edge cases that I cited, modulo doctests as you noted (which we do use occasionally but not very often). Thanks, Adam -- 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: Loading initial data with a post_syncdb hook?
On Mon, May 9, 2011 at 12:56 AM, Adam Seeringwrote: > On May 8, 10:53 pm, Karen Tracey wrote:> > > The change you have noticed is documented in the 1.3 > > backwards-incompatibility list: > http://docs.djangoproject.com/en/1.3/releases/1.3/#use-of-custom-sql-... > > Actually, that's a different issue: I'm not using the custom-SQL > loader, I'm using Python code with the post_syncdb hook. This one > isn't in the backwards-compatibility page as far as I can tell. > > (Was that comment intended to cover this case as well? Maybe a typo > somewhere?) > Hmm, you are right, this change is not supposed to affect data added via post_syncdb handlers. Specifically the change here is: https://code.djangoproject.com/changeset/15239. On an initial read it looks like it might cause post_syncdb-added data to get thrown away, since the post_syncdb signal is sent during the call_command('syncdb'). However, the call_command('flush', ...) that was added after the call_command('syncdb', ...) will also cause that signal to get sent. So your post_syncdb-added data should still be available in your test cases. I've verified via some experiments that if I add a post_syncdb handler that inserts data for one of my apps, that data is available for my test cases. So I'm confused why you are seeing different behavior -- what you are describing happening is not what I observe happening. [snip] > Right now, we're working on adding tests, and on encouraging > developers to write tests for new parts of the code, new apps/code > that are being developed, etc. Right now, as I understand it with > Django's current behavior and our post_syncdb hook setup, we want to > re-load the data in three cases: (1) The current test is the first > test, (2) all prior tests are TestCase (as opposed to > TransactionTestCase) instances, or (3) we are a TransactionTestCase > instance. This is all kind of beside the point since I'm not understanding why your post_syncdb-hander-added data is not available to your tests, but for the record: Worrying about whether a particular test is run first, or is preceded by other tests of a certain kind, is something your code should never have to do (excluding doctests, where Django makes no guarantees that things done by one doctest are invisible to others). It's Django's job to ensure that the database is "clean" when each test starts running. In fact Django will run all TestCase tests before any TransactionTestCase tests (as noted in the doc http://docs.djangoproject.com/en/1.3/topics/testing/#testcase), precisely because the mechanism used to reset the database for these different kinds of tests can't ensure that a TestCase run after a TransactionTestCase will see a "clean" database on start. Django will also ensure that anything changed in the DB (including anything done by setUp) in the first test is undone before the second test runs, so if you did add something to setUp of the first test that could then be seen by the 2nd test to run, that would be a bug in Django's test support. > [snip] > What I personally wish that Django did in this case would be to trust > the data that syncdb puts into the database; do the necessary > bookkeeping to restore it to its initial state at the end of each test > as needed. If I thought it would be accepted, I'd submit a patch. > But if it were that simple, I assume someone would have done it that > way at the start; I don't know enough about this project to understand > the reasoning behind the TRUNCATE here in any case... Hopefully > that'll do a better job framing of what I'd like to accomplish with > our code, though. > > What you describe is exactly what Django does for TestCases: restore the state of the DB to its initial post-syncdb version at the end of the test. It does not do that for TransactionTestCases because that would be prohibitively expensive, and unnecessary given first that TransactionTestCases clear the database on entry and second that Django ensures that all TestCases run before any TranactionTestCases. Django makes no guarantees about the state of the DB for doctests, but they don't seem to factor into your setup? What you are describing happening is contrary to what I observe, and contrary to what Django promises, so it would be helpful if you could gives us some information to recreate the behavior you are seeing. Karen -- http://tracey.org/kmt/ -- 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: Loading initial data with a post_syncdb hook?
On May 8, 10:53 pm, Karen Traceywrote: > On Sun, May 8, 2011 at 10:13 PM, Adam Seering wrote: > > (Incidentally, sorry if this is a duplicate; my original reply, > > identical text, doesn't show up on groups.google.com...) > > I don't know why, but google groups decided your original message might be > spam so held it. When it makes that decision for anyone other than a new > user, it doesn't bother to send a note to moderators until a few days later. > It's a great feechur of google groups. I have removed the copy that was held > for moderation so as to avoid the duplication. Ah, thanks! > > The change you have noticed is documented in the 1.3 > backwards-incompatibility > list:http://docs.djangoproject.com/en/1.3/releases/1.3/#use-of-custom-sql-... Actually, that's a different issue: I'm not using the custom-SQL loader, I'm using Python code with the post_syncdb hook. This one isn't in the backwards-compatibility page as far as I can tell. (Was that comment intended to cover this case as well? Maybe a typo somewhere?) > > Of the alternatives you list, using setUp seems like the correct approach. > I'm a little confused by your worry both that you're inevitably going to > forget to put a call somewhere where it is needed and simultaneous statement > that it's going to be causing duplicate work in a lot of places where it > isn't really needed, though. It seems like you ought to be able to figure > out where it is needed and put it there (possibly helped by tests that fail > due to it not being there). Hm; I'm not entirely sure why you're confused, it's certainly something that'll be a bunch of work for us... Perhaps you're assuming that the set of tests are reasonably static, so that it's possible to go through and do this once? Let me take a shot at clarifying; let me know if this helps: Right now, we're working on adding tests, and on encouraging developers to write tests for new parts of the code, new apps/code that are being developed, etc. Right now, as I understand it with Django's current behavior and our post_syncdb hook setup, we want to re-load the data in three cases: (1) The current test is the first test, (2) all prior tests are TestCase (as opposed to TransactionTestCase) instances, or (3) we are a TransactionTestCase instance. So I can't look at any given test to tell you whether the data has to be loaded or not; I need to know what test(s) have run before it. And this will change if we add new tests, and the result may cause breakage not in the current code but in other pre-existing tests, making it a pain to track down for anyone who doesn't know this particular quirk. We could just load it every time, but that would slow down our test runs more than I'd like. Also, it would involve adding the same one line to every setUp() method, and remembering to add it to new tests, etc. Which I guess isn't the most onerous thing, but, I mean, it's repeating the same line of code over and over again; is that not work duplication? What I personally wish that Django did in this case would be to trust the data that syncdb puts into the database; do the necessary bookkeeping to restore it to its initial state at the end of each test as needed. If I thought it would be accepted, I'd submit a patch. But if it were that simple, I assume someone would have done it that way at the start; I don't know enough about this project to understand the reasoning behind the TRUNCATE here in any case... Hopefully that'll do a better job framing of what I'd like to accomplish with our code, though. Thanks, Adam -- 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: Loading initial data with a post_syncdb hook?
On Sun, May 8, 2011 at 10:13 PM, Adam Seering <aseer...@mit.edu> wrote: > (Incidentally, sorry if this is a duplicate; my original reply, > identical text, doesn't show up on groups.google.com...) > I don't know why, but google groups decided your original message might be spam so held it. When it makes that decision for anyone other than a new user, it doesn't bother to send a note to moderators until a few days later. It's a great feechur of google groups. I have removed the copy that was held for moderation so as to avoid the duplication. The change you have noticed is documented in the 1.3 backwards-incompatibility list: http://docs.djangoproject.com/en/1.3/releases/1.3/#use-of-custom-sql-to-load-initial-data-in-tests Of the alternatives you list, using setUp seems like the correct approach. I'm a little confused by your worry both that you're inevitably going to forget to put a call somewhere where it is needed and simultaneous statement that it's going to be causing duplicate work in a lot of places where it isn't really needed, though. It seems like you ought to be able to figure out where it is needed and put it there (possibly helped by tests that fail due to it not being there). Karen -- http://tracey.org/kmt/ -- 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: Loading initial data with a post_syncdb hook?
On May 8, 7:16 pm, Jacob Kaplan-Mosswrote: > On Sun, May 8, 2011 at 4:25 PM, Adam Seering wrote: > > I have some Python code that generatesinitialdatafor some of my tables; I > > currently call that code from a post_syncdb hook. In Django 1.3, it looks > > like > > Django now calls TRUNCATE (or an equivalent non-PostgreSQL-ism) on all > > tables > > after running syncdb and all of itspost- hooks. > > That... doesn't sound right. Here's all the SQL syncdb executes (for a > simple app with one table); notice the distinct lack of any TRUNCATE > statement. > > Are you perhaps talking about doing this during testing? If so, you're > looking for unittest's setUp > method:http://docs.python.org/library/unittest.html#unittest.TestCase.setUp. Oh, sorry, yeah; let me clarify: Our code has initial database data that it needs in general to operate as intended, during tests or otherwise. Mostly (though not exclusively) to do with a plugins system; scanning a subdirectory for matching .py files and detecting the features that they export is a little expensive, particularly in the critical path of page-rendering; much faster to do it once in advance. The TRUNCATE is during tests, though. If we were to use TestCase.setUp, I would need to modify each of our test classes to call each of our post_syncdb data-set-up hooks. This seems inelegant somehow; someone's going to forget one, and it's redundant work (and so slower tests) because most of our tests aren't TransactionTestCases and so don't need to re-create all of the data. I could monkeypatch TestCase, and possibly even patch some hooks into django.core.management.flush.Command.handle_noargs or django.db.backends.*.DatabaseOperations.sql_flush to know when data has been flushed so that I don't have to restore it unnecessarily. That feels complicated and fragile, though; I'm not a fan if I can avoid it... If the appropriate signals existed in the test framework, I could hook them and do something mildly creative and achieve the same effect as the above using public API's and no monkeypatching. Unfortunately, it looks like they don't exist just yet; I just gave Trac #14319 a gentle poke along those lines. All of these seem way too complicated, though. Am I missing the forest for the trees?; is there a simpler solution here? Thanks, Adam (Incidentally, sorry if this is a duplicate; my original reply, identical text, doesn't show up on groups.google.com...) -- 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: Loading initial data with a post_syncdb hook?
On Sun, May 8, 2011 at 4:25 PM, Adam Seering <aseer...@gmail.com> wrote: > I have some Python code that generates initial data for some of my tables; I > currently call that code from a post_syncdb hook. In Django 1.3, it looks like > Django now calls TRUNCATE (or an equivalent non-PostgreSQL-ism) on all tables > after running syncdb and all of its post- hooks. That... doesn't sound right. Here's all the SQL syncdb executes (for a simple app with one table); notice the distinct lack of any TRUNCATE statement. Are you perhaps talking about doing this during testing? If so, you're looking for unittest's setUp method: http://docs.python.org/library/unittest.html#unittest.TestCase.setUp. Jacob -- 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.
Loading initial data with a post_syncdb hook?
Hi, I have some Python code that generates initial data for some of my tables; I currently call that code from a post_syncdb hook. In Django 1.3, it looks like Django now calls TRUNCATE (or an equivalent non-PostgreSQL-ism) on all tables after running syncdb and all of its post- hooks. I know I could use fixtures, but it's much more readable for us to use Python code for this initial data. (The data being generated is somewhat complex and denormalized for various reasons that probably won't be changed just for the sake of this issue..., but there are nice clean simple Python functions to create each entry.) Is there a good way to do so in the brave new Django 1.3 world? Thanks, Adam -- 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: Initial Data SQL not sticking?
Hmm, I see your commit; Did you get a confirmation message from your database that the commit worked? Perhaps you could try inserting the data via a python script. import sqlite3 # create/connect to a permanent file database con = sqlite3.connect("pyfitness2.db") # establish the cursor, needed to execute the connected db cur = con.cursor() cur.execute("INSERT INTO repository_date etc.. ;") con.commit() con.close() Note that my example is specifically for sqlite. On Mar 26, 7:42 pm, Daniel Pughwrote: > Forgive if this is totally obvious, but I'm having a bit of trouble > getting data into my first prototype with django. > > I am prototyping an application called repository, syncdb builds my > tables and all seems to work in the admin interface. > > However, I have 600 lines of data I want to use as the seed for my > main table. I have a sql file with INSERT commands stored in sql > folder named after the model (sql/date.sql) > > Immediately after running syncdb, I insert the data with either > or repository>. This seems to work, it reads through the SQL and ends > with this: > > INSERT INTO repository_date > (`labno`,`siteno`,`site`,`material`,`materialcomment`,`technique`,`d13`,`rcybp`,`error`,`ref`,`provtype`,`provenience`,`provenience2`,`generalcult`,`taxon`,`comments`) > VALUES > ('ISGS-4242','14CM406','','CHG','','CNV','-26.7','430','70','Bevitt > 1999','','','','','WLM',''); > > INSERT INTO repository_date > (`labno`,`siteno`,`site`,`material`,`materialcomment`,`technique`,`d13`,`rcybp`,`error`,`ref`,`provtype`,`provenience`,`provenience2`,`generalcult`,`taxon`,`comments`) > VALUES > ('unk','14RH301','','MAZ','','AMS','-25.3','600','40','','','','','','WLM',''); > CREATE INDEX "repository_date_5b0c863a" ON > "repository_date" ("siteno_id"); > CREATE INDEX "repository_reference_6223029" ON > "repository_reference" ("site_id");COMMIT; > > Problem is that when I try to access these data in the admin interface > or do dumpdata, nothing is there. I'm at a loss for why the data > aren't populating my database. > > I appollogize if this is completely obvious, it's my first hack at web > development and as much as I love it, some things totally mystify my. > > Thanks! -- 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.
Initial Data SQL not sticking?
Forgive if this is totally obvious, but I'm having a bit of trouble getting data into my first prototype with django. I am prototyping an application called repository, syncdb builds my tables and all seems to work in the admin interface. However, I have 600 lines of data I want to use as the seed for my main table. I have a sql file with INSERT commands stored in sql folder named after the model (sql/date.sql) Immediately after running syncdb, I insert the data with either or . This seems to work, it reads through the SQL and ends with this: INSERT INTO repository_date (`labno`,`siteno`,`site`,`material`,`materialcomment`,`technique`,`d13`,`rcybp`,`error`,`ref`,`provtype`,`provenience`,`provenience2`,`generalcult`,`taxon`,`comments`) VALUES ('ISGS-4242','14CM406','','CHG','','CNV','-26.7','430','70','Bevitt 1999','','','','','WLM',''); INSERT INTO repository_date (`labno`,`siteno`,`site`,`material`,`materialcomment`,`technique`,`d13`,`rcybp`,`error`,`ref`,`provtype`,`provenience`,`provenience2`,`generalcult`,`taxon`,`comments`) VALUES ('unk','14RH301','','MAZ','','AMS','-25.3','600','40','','','','','','WLM',''); CREATE INDEX "repository_date_5b0c863a" ON "repository_date" ("siteno_id"); CREATE INDEX "repository_reference_6223029" ON "repository_reference" ("site_id");COMMIT; Problem is that when I try to access these data in the admin interface or do dumpdata, nothing is there. I'm at a loss for why the data aren't populating my database. I appollogize if this is completely obvious, it's my first hack at web development and as much as I love it, some things totally mystify my. Thanks! -- 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.
Initial Data SQL not sticking?
Forgive if this is totally obvious, but I'm having a bit of trouble getting data into my first prototype with django. I have put together an application with three tables defined in models.py. syncdb builds them and all seems to work in the admin interface. I w -- 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: Initial data in forms
Sorry I'm tired. Got it ! collection = MediaCollection.objects.get(public_id=public_id) form = MediaCollectionForm(instance=collection) 2011/2/18 YomGuy <yomguyparis...@gmail.com> > Hi ! > > I need to get initial data in a form. > Do I have to use a formset or is there any method to fill a form coming > from a model item with existing data ? > > Thank for help > G > > -- 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.
Initial data in forms
Hi ! I need to get initial data in a form. Do I have to use a formset or is there any method to fill a form coming from a model item with existing data ? Thank for help G -- 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: Change the initial data to a modelForm
This don't work to me. Now I must to use the "." like a thousand separator and the "," like decimal separator (x.xxx,xx) (requirement of the boss). I try to follow the guide to "custom format fields" in the Django documentation, but I can't get formatted numbers. I have this: mysite/ formats/ __init__.py es/ __init__.py formats.py -- And in my settings.py USE_I18N = True USE_L10N = True FORMAT_MODULE_PATH = 'formats.es.formats' Nothing more. Where is my error? The FORMAT_MODULE_PATH must to be other? I must to declare the FORMAT_MODULE_PATH in other side? I must to include some library in the view? This is the first time when I work with localization. Thanks for read. -- 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: Change the initial data to a modelForm
Thanks, you are the best -- 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: Change the initial data to a modelForm
I don't think you need to change the value, but rather add localization so add proper formatting. http://docs.djangoproject.com/en/dev/topics/i18n/localization/#format-localization -- 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.
Change the initial data to a modelForm
Hello list. I have a model "PP" with a "float" field "val" and a modelform for this model For update the data of a existent "PP" I use a form like this Form_for_PP(request,POST, instance=instance) Now my question is, Can I change the initial data for the field "val"? I want to do this: If the value in "val" is 12345.6, the resulting form must to have the value "12.345,6" (the same value, but formatted) I can't find the way to do this when I use an instance. Set an "initial" don't work, the returning value is always the existing in the DB. Somebody can help me? Thanks for read, and sorry for my poor english. -- 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: how to initial data for inlineformset
if i changed to following: 'docfset':docfset({'actor':request.user}, instance=tdoc), i got: ValidationError On May 7, 10:21 am, victor <xur...@gmail.com> wrote: > docfset=inlineformset_factory(document, documentOnline, > form=documentOnlineForm, extra=1, can_delete=False) > c = RequestContext( > request, > { > > 'docfset':docfset(instance=tdoc,initial=[{'actor':request.user},]), > > 'documentform':documentForm(initial={'tSUser':getEDSByUObj(request.user, > []),'documentType':'Online','status':'Enabled'}), > } > ) > when runing,i got following errors: > __init__() got an unexpected keyword argument 'initial' > so,how to initial data for inlineformset?thanks. > > -- > 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 > athttp://groups.google.com/group/django-users?hl=en. -- 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.
how to initial data for inlineformset
docfset=inlineformset_factory(document, documentOnline, form=documentOnlineForm, extra=1, can_delete=False) c = RequestContext( request, { 'docfset':docfset(instance=tdoc,initial=[{'actor':request.user},]), 'documentform':documentForm(initial={'tSUser':getEDSByUObj(request.user, []),'documentType':'Online','status':'Enabled'}), } ) when runing,i got following errors: __init__() got an unexpected keyword argument 'initial' so,how to initial data for inlineformset?thanks. -- 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.
[django] automatically loading initial data fixtures for third party apps
Hi all, I want to provide automatically loaded initial data for the third party app - 'django-tagging'. There is a special place for internal apps: /fixtures/initial_data.yaml, but not for a third party. I want data to bi initialized on ./manage.py syncdb There are many similar questions: http://groups.google.com/group/django-users/browse_thread/thread/16a6bda3f0491f80/f5edd5c0bb0992d7?lnk=gst=initial+data#f5edd5c0bb0992d7 ps As a solution i see to keep initial data in the folder: fixture/ /initial_data.yaml, the same way as templates are overloaded. -- 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: Initial data in a many to many field
I wasn't using ProfileForm(instance = userProfile) because I didn't realize I could. Wow, that makes things easier and neater. Thanks so much. On Mar 25, 11:57 am, Nuno Maltezwrote: > >On Thu, Mar 25, 2010 at 2:00 AM, mjlissner wrote: > > I'll make things more concrete. I have the following in my model > > (which is made into a ModelForm): > > class UserProfile(models.Model): > > barmembership = models.ManyToManyField(BarMembership, > > verbose_name="the bar memberships held by the user", > > blank=True, > > null=True) > > > In my view, I have some code that looks like this: > > userProfile = request.user.get_profile() > > bar_memberships = userProfile.barmembership.all() > > > profileForm = ProfileForm( > > initial = {'barmembership' : [bar_memberships]}) > > I don't know why you're not using the "instance" argument to populate the form > > profileForm = ProfileForm(instance=userProfile) > > but you need to give the ModelForm a list of PKs for the many-to-many-field: > > bar_memberships = [obj.pk for obj in ob.barmembership.all()] > profileForm = ProfileForm( initial = {'barmembership' : bar_memberships}) > > (see the model_to_dict code in django/forms/models.py ) > > And force the refresh on the browser if it looks like it's not working > :) (at least FF has a strange > habit of keeping selections when reloading a form, ignoring the > initial selected items on the HTML). > > hth, > Nuno -- 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: Initial data in a many to many field
>On Thu, Mar 25, 2010 at 2:00 AM, mjlissnerwrote: > I'll make things more concrete. I have the following in my model > (which is made into a ModelForm): > class UserProfile(models.Model): > barmembership = models.ManyToManyField(BarMembership, > verbose_name="the bar memberships held by the user", > blank=True, > null=True) > > In my view, I have some code that looks like this: > userProfile = request.user.get_profile() > bar_memberships = userProfile.barmembership.all() > > profileForm = ProfileForm( > initial = {'barmembership' : [bar_memberships]}) I don't know why you're not using the "instance" argument to populate the form profileForm = ProfileForm(instance=userProfile) but you need to give the ModelForm a list of PKs for the many-to-many-field: bar_memberships = [obj.pk for obj in ob.barmembership.all()] profileForm = ProfileForm( initial = {'barmembership' : bar_memberships}) (see the model_to_dict code in django/forms/models.py ) And force the refresh on the browser if it looks like it's not working :) (at least FF has a strange habit of keeping selections when reloading a form, ignoring the initial selected items on the HTML). hth, Nuno -- 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.
Initial data in a many to many field
I've been struggling with this literally for hours. I'm trying to use a ModelForm with initial values being set as those that are already in the DB for a user. This works marvelously for every field that I have EXCEPT for the one manytomany field I have in my model. For that one, I can submit the form just fine, but it NEVER prepopulates with initial data. I'll make things more concrete. I have the following in my model (which is made into a ModelForm): class UserProfile(models.Model): barmembership = models.ManyToManyField(BarMembership, verbose_name="the bar memberships held by the user", blank=True, null=True) In my view, I have some code that looks like this: userProfile = request.user.get_profile() bar_memberships = userProfile.barmembership.all() profileForm = ProfileForm( initial = {'barmembership' : [bar_memberships]}) But I just can't get it to work. Is there something I'm missing here, or does anybody have any pointers as to what I need to do to make this work? All my other fields populate properly in this form...but this one is causing me major headaches. Thanks. -- 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: Form initial data is not dynamic
Ah. That does make sense! I cant believe I missed that in the docs. Thanks for pointing it out! On Mar 5, 7:08 am, David De La Harpe Goldenwrote: > On 05/03/10 01:30, NaMaK wrote: > > class DateTest(forms.Form): > > ... in_date=forms.DateTimeField(initial=datetime.datetime.now()) > > ... > > Well, note that the now() was executed when python first saw it, which > was just a bit after it first saw the class definition. Think about it - > it does make sense. > > But django allows initial on a form field to be a callable that will be > called for a value at display time, so if that's suitable, you can do: > > class DateTest(forms.Form): > in_date=forms.DateTimeField(initial=datetime.now ) > > # note absence of () on 'now' as you want to pass in now itself, > # not call it. > > This is covered in the docs, > btw.http://docs.djangoproject.com/en/1.1/ref/forms/fields/#initial > (towards the end of that section) > > Note deferring to display time with a callable is slightly different to > passing in a value at form construction time - another option is to pass > an initial dict of whatever you want at form construction time, if you > want it to be that (probably more relevant for cases other than > now/now()...) > > f = DateTest(initial=dict(in_date=datetime.now())) > > (callables also work there too) -- 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: Form initial data is not dynamic
On 05/03/10 01:30, NaMaK wrote: class DateTest(forms.Form): ... in_date=forms.DateTimeField(initial=datetime.datetime.now()) ... Well, note that the now() was executed when python first saw it, which was just a bit after it first saw the class definition. Think about it - it does make sense. But django allows initial on a form field to be a callable that will be called for a value at display time, so if that's suitable, you can do: class DateTest(forms.Form): in_date=forms.DateTimeField(initial=datetime.now ) # note absence of () on 'now' as you want to pass in now itself, # not call it. This is covered in the docs, btw. http://docs.djangoproject.com/en/1.1/ref/forms/fields/#initial (towards the end of that section) Note deferring to display time with a callable is slightly different to passing in a value at form construction time - another option is to pass an initial dict of whatever you want at form construction time, if you want it to be that (probably more relevant for cases other than now/now()...) f = DateTest(initial=dict(in_date=datetime.now())) (callables also work there too) -- 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.
Form initial data is not dynamic
Hi, I am using Django 1.1. When I create a form, the initial data is set when the class is created. It does not get updated when an object is created. The following can demonstrate: >>> >>> import datetime >>> from django import forms >>> >>> datetime.datetime.now() datetime.datetime(2010, 3, 4, 20, 11, 33, 477095) >>> >>> >>> class DateTest(forms.Form): ... in_date=forms.DateTimeField(initial=datetime.datetime.now()) ... >>> >>> datetime.datetime.now() datetime.datetime(2010, 3, 4, 20, 13, 5, 308900) >>> >>> >>> foo = DateTest() >>> >>> foo.as_p() u'In date: ' >>> >>> >>> datetime.datetime.now() datetime.datetime(2010, 3, 4, 20, 13, 52, 540813) >>> >>> >>> >>> bar = DateTest() >>> >>> bar.as_p() u'In date: ' >>> >>> >>> datetime.datetime.now() datetime.datetime(2010, 3, 4, 20, 15, 9, 644799) >>> >>> So as you can see, when the class was created, the tile was 20:12:58, and this was stored as initial data. Any new form object created after this time maintained the time of when the class was first initialized in memory rather than re-initializing whenever an object is created. I want this field to reflect the time of the object creation as opposed to the time of class creation. Is there any other way of doing this apart from setting the class variable at each object creation manually? In other words, is there a class initialization option that I can use, or settings option? Or do I by default just set the class variable by either overriding the __init__ constructor or setting it manually after object creation? -- 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: Providing flatpages initial data
pen('provdata.json', 'w') f.flush() f.write(buff) f.write("]") f.close() *** / code *** This yields a provdata.json flatpage which I copy into myproject/myapp/fixtures Then I run manage.py loaddata provdata.json and all of the provinces for my game get loaded. MUCH easier than coding them all by hand. And now that I have the general method I can apply it to all my database tables. Hope this helps someone. -Tim On Fri, Feb 19, 2010 at 1:09 PM, Timothy Kinney <timothyjkin...@gmail.com>wrote: > I started playing with this last night and got about as far as you > mentioned here. What I want to be able to do, though, is write a python > script that writes an authentic json flatpage that I can import into the > database. I have a large textfile full of names, items, and province > information (for a game) and I want to shove all this into the database. > > I tried adding some provinces to the database, dumpdata, and then looked at > the json file to see if I could copy the syntax it was using. This hasn't > quiet worked yet, but I will keep trying. > > Has anyone tried what I want to do? > > -Tim > > > > On Fri, Feb 19, 2010 at 11:13 AM, Rick Caudill <cau0...@gmail.com> wrote: > >> Hi all, >> >> I just came across a need to provide initial data for flatpages. I have >> read before that people have asked to do this. It is easier than thought >> :) >> >> 1. Create your content via the admin interface >> 2. Run 'python manage.py dumpdata flatpages > data.json' >> 3. When you want to provide the data run 'python manage.py loaddata >> data.json' >> >> >> I hope this helps someone that needs to do this sort of thing. >> >> >> -- >> Rick Caudill >> >> -- >> 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<django-users%2bunsubscr...@googlegroups.com> >> . >> For more options, visit this group at >> http://groups.google.com/group/django-users?hl=en. >> > > -- 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: Providing flatpages initial data
I started playing with this last night and got about as far as you mentioned here. What I want to be able to do, though, is write a python script that writes an authentic json flatpage that I can import into the database. I have a large textfile full of names, items, and province information (for a game) and I want to shove all this into the database. I tried adding some provinces to the database, dumpdata, and then looked at the json file to see if I could copy the syntax it was using. This hasn't quiet worked yet, but I will keep trying. Has anyone tried what I want to do? -Tim On Fri, Feb 19, 2010 at 11:13 AM, Rick Caudill <cau0...@gmail.com> wrote: > Hi all, > > I just came across a need to provide initial data for flatpages. I have > read before that people have asked to do this. It is easier than thought > :) > > 1. Create your content via the admin interface > 2. Run 'python manage.py dumpdata flatpages > data.json' > 3. When you want to provide the data run 'python manage.py loaddata > data.json' > > > I hope this helps someone that needs to do this sort of thing. > > > -- > Rick Caudill > > -- > 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<django-users%2bunsubscr...@googlegroups.com> > . > For more options, visit this group at > http://groups.google.com/group/django-users?hl=en. > -- 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.
Providing flatpages initial data
Hi all, I just came across a need to provide initial data for flatpages. I have read before that people have asked to do this. It is easier than thought :) 1. Create your content via the admin interface 2. Run 'python manage.py dumpdata flatpages > data.json' 3. When you want to provide the data run 'python manage.py loaddata data.json' I hope this helps someone that needs to do this sort of thing. -- Rick Caudill -- 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: Setting initial data for an M2M field
Jacob, Thanks so much for this; it really helped me. Tom On Feb 16, 8:29 pm, Jacob Kaplan-Moss <ja...@jacobian.org> wrote: > On Tue, Feb 16, 2010 at 10:01 AM, Tom <t.scr...@gmail.com> wrote: > > I can set other initial data, for example to the 'notes' CharField > > fine. I guess my question boils down to: how do you set initial data > > for a many-to-many field? > > The initial data for a many to many field needs to be a list. So:: > > f = EmailForm(initial={'contacts': [contact.id]}) > > Remember: it's a *many-to-many* field, which means that the field has > *many* values. > > Also notice the error message: "'long' object is not iterable". This > is telling you that someone, somewhere, has tried to iterate (treat as > a list) something (a long integer) that isn't a list object. > > Jacob -- 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: Setting initial data for an M2M field
On Tue, Feb 16, 2010 at 10:01 AM, Tom <t.scr...@gmail.com> wrote: > I can set other initial data, for example to the 'notes' CharField > fine. I guess my question boils down to: how do you set initial data > for a many-to-many field? The initial data for a many to many field needs to be a list. So:: f = EmailForm(initial={'contacts': [contact.id]}) Remember: it's a *many-to-many* field, which means that the field has *many* values. Also notice the error message: "'long' object is not iterable". This is telling you that someone, somewhere, has tried to iterate (treat as a list) something (a long integer) that isn't a list object. Jacob -- 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.
Setting initial data for an M2M field
Hi all, I have two models, a contact model: class Contact(models.Model): company = models.ForeignKey(Company) first_name = models.CharField(max_length=200) last_name = models.CharField(max_length=200) title = models.CharField(max_length=200) office_telephone = models.CharField(max_length=20) dd_telephone = models.CharField(max_length=20) mobile_telephone = models.CharField(max_length=20) address_1 = models.CharField(max_length=200) address_2 = models.CharField(max_length=200) address_3 = models.CharField(max_length=200) city_county = models.CharField(max_length=200) post_code = models.CharField(max_length=8) fax = models.CharField(max_length=20) email_address = models.EmailField(max_length=75) and an email model: class Email(models.Model): contacts = models.ManyToManyField(Contact) date = models.DateTimeField(auto_now_add=True) notes = models.CharField(max_length=2) I have a view that shows the contact data for a particular contact record, and I am putting a link on there that allows the user to attach an email record to that contact. I want the M2M field to be initially set to the contact record they have come from: def addcontactemail(request, contact_id): contact_id = int(contact_id) contact = Contact.objects.filter(id=contact_id) contact = contact[0] if request.method == 'POST': f = EmailForm(request.POST) if f.is_valid(): f.save() return HttpResponseRedirect('http://127.0.0.1:8000/contact/%d' % contact_id) else: f = EmailForm(initial={'contacts': contact.id}) return render_to_response('addcontactemail.html', {'formset': f}) But I am getting "Caught an exception while rendering: 'long' object is not iterable" thrown when the browser tries to render the form in the addcontactemail.html template. I can set other initial data, for example to the 'notes' CharField fine. I guess my question boils down to: how do you set initial data for a many-to-many field? Any pointers much appreciated! Thanks, Tom -- 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: Initial data fixtures and auto_now_add=True
On Feb 2, 1:45 pm, Russell Keith-Mageewrote: > Correct. I'm guessing that the same thing is happening - the default > value is being used because the fixture doesn't specify a value. Feel > free to update the ticket so the auto_now case isn't forgotten. Done ;) Kind regards, Andrew -- 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: Initial data fixtures and auto_now_add=True
On Tue, Feb 2, 2010 at 9:41 PM, Andrew Turnerwrote: > On Feb 2, 1:29 pm, Russell Keith-Magee wrote: >> The cause of the problem is your initial fixture. Django doesn't >> listen to auto_now_add or auto_now fields on fixture loading - fixture >> objects are saved in "raw" mode, so it is assumed that the fixture >> should have data for all the fields. In this case, your fixture is >> missing a definition for pub_date, so on the second sync, you are >> getting the error I would expect - that the null value in the column >> isn't allowed. > > I see. As stated in my original post, syncdb works the second time > round when auto_now=True is used. Surely that shouldn't work at all > either? Correct. I'm guessing that the same thing is happening - the default value is being used because the fixture doesn't specify a value. Feel free to update the ticket so the auto_now case isn't forgotten. Yours, Russ Magee %-) -- 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: Initial data fixtures and auto_now_add=True
On Tue, Feb 2, 2010 at 5:12 PM, Andrew Turnerwrote: > On Feb 2, 8:07 am, Russell Keith-Magee wrote: >> It is possible you've found a bug, but in order to verify that, we >> need a minimal example that reproduces the problem - that is, the >> simplest possible model and fixture combination that fails on the >> second syncdb like you describe. > > Thanks for the reply. > > Here is a simple initial_data.json:- > > [ > { > "model": "posts.entry", > "pk": 1, > "fields": { > "content": "This is the content" > } > } > ] > > And here is my models.py:- > > from django.db import models > > class Entry(models.Model): > content = models.CharField(max_length=250) > pub_date = models.DateTimeField(auto_now_add=True, editable=False) > > > First time syncdb is run, the fixture is correctly loaded, subsequent > runs result in the aforementioned error. Tested on Django 1.1.1 and > 1.2alpha. It appears you have found a bug (what is worse - one that I thought we were testing for). The cause of the problem is your initial fixture. Django doesn't listen to auto_now_add or auto_now fields on fixture loading - fixture objects are saved in "raw" mode, so it is assumed that the fixture should have data for all the fields. In this case, your fixture is missing a definition for pub_date, so on the second sync, you are getting the error I would expect - that the null value in the column isn't allowed. However, you should also be getting that error on the first syncdb. For some reason, the raw mode save isn't preventing the default value from being initialized. This is a bug, which I've opened as #12753. Of course, the immediate workaround for you is to include a datetime in your fixture. Yours, Russ Magee %-) -- 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: Initial data fixtures and auto_now_add=True
On Feb 2, 8:07 am, Russell Keith-Mageewrote: > It is possible you've found a bug, but in order to verify that, we > need a minimal example that reproduces the problem - that is, the > simplest possible model and fixture combination that fails on the > second syncdb like you describe. Thanks for the reply. Here is a simple initial_data.json:- [ { "model": "posts.entry", "pk": 1, "fields": { "content": "This is the content" } } ] And here is my models.py:- from django.db import models class Entry(models.Model): content = models.CharField(max_length=250) pub_date = models.DateTimeField(auto_now_add=True, editable=False) First time syncdb is run, the fixture is correctly loaded, subsequent runs result in the aforementioned error. Tested on Django 1.1.1 and 1.2alpha. Thanks, Andrew -- 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: Initial data fixtures and auto_now_add=True
On Tue, Feb 2, 2010 at 3:58 PM, Andrew Turner <acturne...@gmail.com> wrote: > On Jan 19, 1:36 pm, Andrew Turner <acturne...@gmail.com> wrote: >> I have an initial_data.json file which provides some, er, initial data >> whenever I run syncdb. One of my models has a DateTimeField with >> auto_now_add=True. The data is loaded first time round, but on >> subsequent syncdbs, I get "IntegrityError: posts_entry.pub_date may >> not be NULL". > > Anyone? Is this behaviour expected, or should I file a bug? Well, it's difficult to know what is expected without more details. I can't think of any obvious reason why a fixture should fail on the *second* syncdb that doesn't also involve you doing something unexpected to your data in the interim. However, without any details of what else is in your models, or what else you have done to your data, it's impossible to say if you've found a bug or if you're doing something wrong. It is possible you've found a bug, but in order to verify that, we need a minimal example that reproduces the problem - that is, the simplest possible model and fixture combination that fails on the second syncdb like you describe. Yours, Russ Magee %-) -- 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: Initial data fixtures and auto_now_add=True
On Jan 19, 1:36 pm, Andrew Turner <acturne...@gmail.com> wrote: > I have an initial_data.json file which provides some, er, initial data > whenever I run syncdb. One of my models has a DateTimeField with > auto_now_add=True. The data is loaded first time round, but on > subsequent syncdbs, I get "IntegrityError: posts_entry.pub_date may > not be NULL". Anyone? Is this behaviour expected, or should I file a bug? -- 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.
Fixtures Initial Data - Split Into Multiple Files?
heya, This is a small question, is there any way for the initial_data.json/ xml/sql file to reference other files, or split it up across multiple files? Basically, I want to split up my existing monolithic files, into a separate json file for each section (I'm basically using this to populate all the lookup tables - e.g. for category names). I couldn't find anything about this in the JSON spec, I'm not sure how other people are doing this in Django? Or do you just put everything in a single file? Cheers, Victor -- 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.
Initial data fixtures and auto_now_add=True
I have an initial_data.json file which provides some, er, initial data whenever I run syncdb. One of my models has a DateTimeField with auto_now_add=True. The data is loaded first time round, but on subsequent syncdbs, I get "IntegrityError: posts_entry.pub_date may not be NULL". Is this the expected behaviour? Note that all is fine if the field is changed to auto_now=True instead. -- 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.
Initial data for inline_formset
I'm trying to use initial data with an inline_formset and I get this >>> fs = SectionFormSet(initial=section_initial) Traceback (most recent call last): File "", line 1, in TypeError: __init__() got an unexpected keyword argument 'initial' >>> But inline formsets extend formsets, which take the initial keyword, and in the django.forms.models **kwargs is passed to all parents of BaseInlineFormset. I am extending BaseInlineFormset in my SectionFormSet but I am not overriding __init__ . Am I missing something? Cheers, Dave -- 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.
Different behavior of form = SomeForm(data) and form = SomeForm(initial=data)
Greetings :) Let's consider the following two models: - class State(models.Model): short_name = models.CharField(max_length=2, unique=True) name = models.CharField(max_length=50, unique=True) is_active = models.BooleanField(db_index=True) def __unicode__(self): return u'%s' % (self.name) class Company(models.Model): name = models.CharField(max_length=50) contact_person = models.CharField(max_length=50) email = models.EmailField() address = models.CharField(max_length=255) state = models.ForeignKey(State) def __unicode__(self): return u'%s' % (self.name) The following form: - class AttendToCompanyForm(forms.Form): name = forms.CharField(max_length=50, widget=forms.TextInput(attrs= {'class':'textInput',})) contact_person = forms.CharField(max_length=50, widget=forms.TextInput(attrs={'class':'textInput',})) email = forms.EmailField(max_length=75, widget=forms.TextInput (attrs={'class':'textInput',})) address = forms.CharField(max_length=255, widget=forms.Textarea()) state = forms.ModelChoiceField(State.objects.filter (is_active=True), widget=forms.Select(attrs={'class':'selectInput',})) And the view: - def attend_to_company(request, cid): company_to_attend = Company.objects.get(id=cid) if request.method == 'POST': form = AttendToCompanyForm(request.POST) if form.is_valid(): # some code # some code # some code return HttpResponseRedirect(reverse('redirect-to-some- page')) else: data = {'name': agencyrequest_to_attend.name, 'contact_person': agencyrequest_to_attend.contact_person, 'email': agencyrequest_to_attend.email, 'address': agencyrequest_to_attend.address, 'state': agencyrequest_to_attend.state.id} form = AttendToCompanyForm(data) return render_to_response('attend_to_company.html', {'form': form}, context_instance=RequestContext(request)) When I access the view via HTTP GET, if I use form = AttendToCompanyForm(data) then the state field (a drop down select) in the form is populated correctly and the corresponding state for the company appears as selected in the list, but when I use form = AttendToCompanyForm(initial=data) then the state field does not reflect the corresponding state for the company, and instead shows the first "-" element of the drop down list. Is this expected behavior? What is the cause of this? Thanks and regards, CM. --~--~-~--~~~---~--~~ 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: initial data for formset
Thanks. I've set extra=0 and added an element to the list, and now the last form on the page is half-initialized - the date is set but the time is not! What could cause that?? On May 26, 9:20 pm, Sam Chuparkoff <s...@sadach.org> wrote: > On Tue, 2009-05-26 at 17:27 -0700, adrian wrote: > > This code creates a formset and populates fields with copies of > > date and start_time. > > The problem is, if num_events is X then it creates X forms but it only > > populates X-1 (it leaves the last one uninitialized). My question > > is why, and how to fix it? Thanks. > > > DateTimeFormSet = formset_factory(DateTimeForm) > > initial_data_list = [] > > pattern_datetime_dict = { > > 'date':event.date, > > 'start_time':event.time_start, > > } > > > for x in range(1, num_events): > > initial_data_list.append(pattern_datetime_dict) > > > formset = DateTimeFormSet(initial = initial_data_list) > > Your initial data list only has (num_events - 1) elements. And > formset_factory is returning a formset class that generates 1 extra > form by default, giving you num_events total forms. > > If you don't want any extra forms, you can pass extra=0 into > formset_factory like so: > > DateTimeFormSet = formset_factory(DateTimeForm, extra=0) > > sdc --~--~-~--~~~---~--~~ 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: initial data for formset
On Tue, 2009-05-26 at 17:27 -0700, adrian wrote: > This code creates a formset and populates fields with copies of > date and start_time. > The problem is, if num_events is X then it creates X forms but it only > populates X-1 (it leaves the last one uninitialized). My question > is why, and how to fix it? Thanks. > > >DateTimeFormSet = formset_factory(DateTimeForm) > initial_data_list = [] > pattern_datetime_dict = { > 'date':event.date, > 'start_time':event.time_start, > } > > for x in range(1, num_events): > initial_data_list.append(pattern_datetime_dict) > > formset = DateTimeFormSet(initial = initial_data_list) Your initial data list only has (num_events - 1) elements. And formset_factory is returning a formset class that generates 1 extra form by default, giving you num_events total forms. If you don't want any extra forms, you can pass extra=0 into formset_factory like so: DateTimeFormSet = formset_factory(DateTimeForm, extra=0) sdc --~--~-~--~~~---~--~~ 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 -~--~~~~--~~--~--~---
initial data for formset
This code creates a formset and populates fields with copies of date and start_time. The problem is, if num_events is X then it creates X forms but it only populates X-1 (it leaves the last one uninitialized). My question is why, and how to fix it? Thanks. DateTimeFormSet = formset_factory(DateTimeForm) initial_data_list = [] pattern_datetime_dict = { 'date':event.date, 'start_time':event.time_start, } for x in range(1, num_events): initial_data_list.append(pattern_datetime_dict) formset = DateTimeFormSet(initial = initial_data_list) --~--~-~--~~~---~--~~ 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 -~--~~~~--~~--~--~---
Inline admin forms with dynamically defined initial data
Hi, all I have three models in many-to-many-through arrangement. Let's call them A, B, C, where B is the join model. I would like to edit B as inline from C, so that the number of inlines and their pre-filled data (if possible at all) matches the number of A objects. If I have, say three objects of A class, and they all have a `name` field, I would like to display the inline form as: -- Form for B -- -- C inlines: -- name 1: [ input box ] -- name 2: [ input box ] -- name 3: [ input box ] -- I haven't tried to solve it yet, but I was wondering if anyone can tell me if that's possible at all. -- Branko --~--~-~--~~~---~--~~ 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: foreignkey values in formset initial data
Responding to myself: If I specify the object.id instead of just a reference to the object as the initial field value, the selections work correctly. E.g. 'product': item.product.id instead of 'product': item.product --~--~-~--~~~---~--~~ 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 -~--~~~~--~~--~--~---