w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
django edit queryset objects without affecting database
One simple method is to convert the queryset to a list. The list will contain instances of your model. You can do whatever you like with those instances and nothing will be saved to the database unless you call save or one of the other methods that writes to the database. dividend_set = stock.dividend_set.all().order_by('date') dividends = list(dividend_set) for dividend in dividends: dividend.extra_value1 = 'foo' dividend.extra_value2 = 'bar' # now pass the dividends list to your template as part of your context rather than the qs

Categories : Python

How to combine/merge more than one queryset in to single queryset django
Use the | operator. i.e queryset = queryset1 | queryset2 | queryset3 But you can also use the & operator to find intersection. You have to make sure that all the querysets return are of the same objects i.e Tag. What you want to do basically is queryset = entries[0].tags.all() for entry in entries[1:]: queryset = queryset | entry.tags.all()

Categories : Python

Django Queryset - extracting only date from datetime field in query (inside .value() )
For the below case. select DATE(date), id,address,city, COUNT(cityid) as count from table where date between "start" and "end" group by DATE(date), address,id, city order by DATE(date) ASC,count DESC; You can use extra where you can implement DB functions. Table.objects.filter(date__range(start,end)).extra(select={'date':'DATE(date)','count':'COUNT(cityid)'}).values('date','id','address_city').order_by('date') Hope it will help you. Thanks.

Categories : Django

Why isn't my ModelFormSet saving?
Try this: if request.POST: formset = MembershipFormSet(request.POST) if formset.is_valid(): for form in formset: instance = form.save(commit=False) instance.user = request.user instance.save() return HttpResponseRedirect('next_page') else: return HttpResponse(formset.errors + request.POST.items()) Your issue is here: instances = form.save(commit=False) The issue is, you need to extract the individual form objects, cast it to the object instance, and assign user to it. Where as in your code, instances=form.save(...) is not doing that.

Categories : Django

Show a field of a modelformset as a value
Bumped into the answer while working on another form: {{form.instance.trainee}} Could then chop trainee out of the fields=[] definition as well

Categories : Django

Saving a Django ModelFormset doesn't save new objects
Edit: I think i found your error. You forgot to pass "data" arg to that "super" call. You wrote this: class BaseContactPersonFormSet(forms.models.BaseModelFormSet): def __init__(self, company, data=None, **kwargs): super(BaseContactPersonFormSet, self).__init__(**kwargs) for form in self: form.company = company ContactPersonFormSet = forms.models.modelformset_factory(model=Person, form=SingleContactPersonForm, formset=BaseContactPersonFormSet, can_delete=True, extra=0) but you should write this: class BaseContactPersonFormSet(forms.models.BaseModelFormSet): def __init__(self, company, data=None, **kwargs): super(BaseContactPersonFormSet, self).__init__(data, **kwargs) for form in self: form.company = company ContactPers

Categories : Django

Django: How to filter ForeignKey choices (e.g. with request.user) with ModelFormSet and FormWizard?
You simply want your foreign key queryset for the attendee attribute on your Model to be a filtered one on your ModelForm. You are on the right lines here: self.fields['attendee'].queryset = Person.objects.filter(owner=user) This is assuming an attribute 'owner' exists on the Person class. This won't work however, as where or what is your user arg? One solution is to curry the forms init method, as you mention, to include the correct user object: form = staticmethod(curry(AttendeeForm, user=<the-user-obj>)) Now you pop your user arg from the kwargs in your init method: user = kwargs.pop('user') Now your filtered queryset will only display the Person you filtered for. def __init__(self, user, *args, **kwargs): I tried this but I didn't get it to work. The line above

Categories : Django

How to edit gridview row inside?
If you are using an ObjectDataSource (or SqlDataSource or OleDbDataSource) to databind and use UpdateCommand, DeleteCommand, InsertCommand, then you do not need to explicitly write those three functions for the edit/update operation. You need those functions when you are writing the binding code in code-behind or if you want to do additional work before/after any operation. RowEditing fires when you click "edit" on the GridView. Here you specify what row to open in editmode by writing GridView1.EditIndex = e.NewEditIndex. You can also write code here to do any work that is required before user is put into editmode. For example, you can check for business rules conditions, and cancel the operation if rules are not met. RowUpdating fires when you click "save"/"update" on the GridView. This

Categories : Asp Net

Is Django ModelFormSet using up all my memory? Similar to a memory leak
Sorry to answer my own question. I couldn't find this information pointed out clearly anywhere else, and hopefully this Q/A will be helpful to others. Yes, MyModelFormSet is pulling every "MyModel" from the database. I verified this in a test environment which had 15,000 MyModels in the database. I observed the following: 1) I submitted only 3 MyModels forms in a HTTP post. After the post: 2) formset.forms contains 3 MyModelForms. 3) len(formset._queryset) equals 15,000. formset._queryset contains a list of every MyModel in the database. Django has pulled every MyModel and stored it in memory. The solution is to provide a queryset argument. You can read more about this in the Django documentation. This test was performed with Django version 1.4.5.

Categories : Django

Edit a file inside database in php
try this if(isset($_POST['ta'])){ $handle=fopen('saw42.TextGrid',"a"); require('db_connection.php'); // don't know why this line is here if ($handle===false){ echo 'Unable to open file'; }else{ fwrite($handle,"-----------"); fclose($handle); } }

Categories : PHP

Edit Mode inside Angular ng-repeat
If you don't want to clutter the object with the view state, you can save the view state in an different object. var app = angular.module('plunker', []); app.controller('MainCtrl', function($scope) { $scope.editedItems = {}; $scope.people = [ {name: 'Joe', age:23}, {name: 'Jim', age:32}, {name: 'Jill', age:13} ]; $scope.toggleEditing = function(person) { $scope.editedItems[person.name] = !$scope.editedItems[person.name] || true; }; }); HTML <div class="person" ng-repeat="person in people" ng-click="toggleEditing(person)"> <div class="details-view" ng-hide="editedItems[person.name]" ng-bind="person.name"></div> <div class="edit-view" ng-show="editedItems[person.name]"> <input type="text"

Categories : Angularjs

Java edit file inside WAR archive
You can't modify files contained in any ?AR file (WAR, JAR, EAR, AAR, ...). It's basically a zip archive, and the only way to modify it is to unzip it, make the changes, and zip it up again. If you're trying to have a running application modify itself, then recognize that 1) many containers run from an exploded copy of an ?AR file for various reasons, and 2) it's unlikely to do you any good to modify files on the fly anyway unless you plan to restart the application after the change or write lots of code to monitor for changes and refresh your app in some way afterward. Either way, you're probably better off figuring out how to make your desired change programmatically than trying to rewrite a running application. On the other hand, if you're not talking about having an application modif

Categories : Java

Editing control inside Row Edit Template
Ok, as expected coming from lady luck(?), a little while after asking this I found the answer. In order to get a control from inside the RowEditingTemplate you first need to get access to the Template in question. So, to answer my own question, in order to get my list I did: DropDownList ddlMyObjects = (DropDownList)WebDataGrid1.Behaviors.EditingCore.Behaviors.RowEditTemplate.TemplateContainer.FindControl("control_MyObject");

Categories : C#

Cannot edit images inside sitecore field renderer
It's wrong to use hardcoded path for images: You can see all parameters here. If you use XSLT to render your images, you can apply the parameters on the sc:image directly: <sc:image field="MyImage" width="150" height="100" bc="ffffff"/> If you use UserControls (.ascx) to render your images, you can register the following tagprefix to access sc:Image and sc:FieldRenderer: <%@ Register TagPrefix="sc" Namespace="Sitecore.Web.UI.WebControls" Assembly="Sitecore.Kernel" %>

Categories : Asp Net

Edit Wordpress shortcode output inside post edition
function pi_app_store_petit($atts, $content = null) { $atts = shortcode_atts(array('url' => 'url=""'), $atts,'app_store_petit'); return "<a href='{$atts["url"]}' target='itunes_store'>".do_shortcode($content)."</a>"; } add_shortcode('app_store_petit', 'pi_app_store_petit'); Now, you can use [app_store_petit url=" "][/app_store_petit] Reference : https://codex.wordpress.org/Function_Reference/add_shortcode

Categories : Wordpress

Can't edit input fields inside iframe app after using FB.login on Firefox
Try to put window.parent.focus() right after this line: $('#email').val( me.email ); if (me.name) { $('.displayname').text(" as " + me.name); $('#name').val( me.name ); $('#email').val( me.email ); window.parent.focus(); } I've had the same problem - couldn't get the focus on input fields, until I've selected the parent window inside the FB.api.

Categories : Javascript

editable kendoGrid inside kendoGrid Edit Popup not working correctly
Try this, function addressGridEditor(container, options) { var repgrid = $('<div id="kgrd_Address" data-bind="source:' + options.field + '"></div>') .appendTo(container) .kendoGrid( { columns: [ { field: "Address", title: "Address", width: "150px" }, { command: ["edit", "destroy"], title: "&nbsp;", width: "150px" } ], editable: "popup", scrollable: true, selectable: "row", autoBind: true }).data("kendoGrid"); } I think you have to remove editor: from function.

Categories : Jquery

Replace DIV inside another DIV with TEXTAREA, edit text and replace back
You can try like this example javascript: $("#edit").live("click",function(){ $(".inputbox").val($("#menu").text()).show(); $("#menu").hide(); $("#save").show(); $(this).hide(); }); $("#save").live("click",function(){ $("#menu").show(); $("#menu b").html($(".inputbox").val()); $(".inputbox").hide(); $("#edit").show(); $(this).hide(); });

Categories : Jquery

Edit image class (css class) inside contenteditable div
You can use the .setAttribute() method, or set the .className property. el.setAttribute('class', 'myClass'); el.className = 'myClass';

Categories : Javascript

How to save, delete, edit data to PHP / Mysql with inline edit in CKEditorsaving?
Below is a example on how to pass data from the Ckeditor. By pressing the button you can save the content via ajax. <div id="editable" contenteditable="true"> <h1>Inline Editing in Action!</h1> <p>The div element that contains this text is now editable. </div> <button type='button' id='save'><span>Save</span></button> <script> $(document).ready(function (e) { $("#save").click(function (e) { var data = CKEDITOR.instances.editable.getData(); var options = { url: "/path/to/php", type: "post", data: { "editor" : encodeUriComponent(data) }, success: function (e) { //code to do when success } };

Categories : PHP

Click event for edit/delete button when tableview is in edit mode
If you are using your custom button as a subview then you can addTarget to your button like this: [button addTarget:self action:@selector(yourMethod) forControlEvents:UIControlEventTouchUpInside]; Please be specific or show some screenshots. So that I can figure it out.

Categories : Iphone

how to configure or edit wp-filebase plugin edit to show author of files
yes we can configure the plugin without touching the code. However, following link was very helpful to me. documentation for the templates

Categories : PHP

How to show data in tabular format in asp.net mvc & perform edit operation without providing edit button in each row?
You are looking for an "inline edit" then I believe. You are probably going to need some Javascript to get a nice effect for this. I like JQuery, so I'd use JEditable. I'd suggest you have a read of this article: http://www.codeproject.com/Articles/265211/Using-JEditable-plugin-as-ASP-NET-MVC3-jQuery-inli Scroll to the section called "Integration with DataTables"

Categories : Asp Net Mvc

Custom sharepoint 2010 xslt list - Edit item via javascript - Data not refreshed after edit
If it's a modal window, then you have to monitor when the modal is closed (for example with http://sharepoint.stackexchange.com/questions/65513/detect-modal-dialog-close-with-jquery) then you can reload your main page with window.location.reload() or window.location.href=window.location.href

Categories : Javascript

Is there any way to Edit row of bound fields in gridview with custom edit button?
Everything is possible ;-) But you have to decide how you want the edit to be done. If you're not using the built in functionality to enable editing of the field contents, you need some other kind of editing. One option would be to use a separate details view beneath/besides the table that can be edited. Place the detail view in an update panel to avoid reloading the entire page. You would also need to place the grid view in an update panel to be able to reload it's content smoothly once the edited changes are saved.

Categories : C#

Django: edit template inside another template
If you want your user to be able to edit the template, then you should store the template in the database. There are some packages that do this for you, but it's easy enough to do by yourself # in models.py class EmailTemplate(models.Model): name = models.CharField(max_length=50) template = models.TextField() Then when you need to send an email, you can render it like so: # in views.py from django.template import Template, Context #in your view email_template = get_object_or_404(EmailTemplate, id = template_id) #You should know how to get this somewhere template = Template(email_template.template) email_body = template.render(Context({'my_context':'my_context'}))

Categories : Django

javascript error: ReferenceError: edit is not defined edit(this);
A script can be inline or external, it cannot be both. The presence of the src attribute causes the text node children of the script node to be ignored. If you want inline and external scripts, use two script elements. <script src="serialize-0.2.min.js"></script> <script> function edit(element){ // etc

Categories : Javascript

JQuery td inline edit -> after enter go to next edit cell?
you may try to bind a keydown event to the edit box input. On key down, it should fire the click event of the next cell. $('#editbox').keydown(function(event){ if (event.which == 13)$(this).parent().parent().next().children(':first').trigger('click'); }); hope this is helpful

Categories : PHP

Asp.net MVC 4 getJson work for create but not for edit. Seems to have an odd url in edit
The following line $.getJSON("ProfessionTypeList", will generate the URL of the form http://domain.com/Controller/ActionName/ProfessionTypeList i.e. it will append ProfessionTypeList at the end of the URL. You should try to make explicit URL will complete path. In CSHTML file, you can do so by using @Url.Action("ProfessionTypeList")

Categories : Javascript

I want to select the entire row for edit by click on edit
Your $(this) will hold the only element on which, you have clicked. So, $(this).addClass('ajax'); $(this).html('<input id="editbox" size="'+ $(this).text().length+'" value="' + $(this).text() + '" type="text">'); this code will add textbox to only that element.You need to take parent of clicked element first, like var p = $(this).parentNode; and then take all child nodes for 'p' element.And use for loop for all child elements and add above code for each single element, not for $(this).

Categories : PHP

Updating a queryset
Just a small typo, you missed the function call: tests = Stock.objects.all() If you prod around in an interactive shell you can see that: >>> type(Stock.objects.all) <type 'instancemethod'> while invoking the all() method will return an iterable object, namely a Django QuerySet.

Categories : Django

How to exclude from another QuerySet?
Read that topic: https://docs.djangoproject.com/en/dev/ref/models/querysets/#in and there is: You can also use a queryset to dynamically evaluate the list of values instead of providing a list of literal values:

Categories : Django

How to get choices value in queryset?
models.py class MyModel(models.Model) ALL = "ALL" NONE = "NONE" HALF = "HALF" SELECT_CHOICES = ( (ALL, "100%"), (HALF, "50%"), (NONE, "0%"), ) select_field = models.CharField(max_length = 255, choices = SELECT_CHOICES) @property def select_ratio(self): return self.get_select_field_display() Anywhere: mymodels = MyModel.objects.all() for entry in mymodels: print entry.select_ratio

Categories : Django

QuerySet with .latest() for each day
Maybe you can do somehting like: import datetime day = datetime.datetime.now().day the_last_one = Stats.objects.filter(created__day=day).order_by('-created')[0] or Something like the_last_one = Stats.objects.filter(created__day=day).order_by('created').latest()

Categories : Django

how to add one object to queryset
It's not exactly clear what you are trying to do, but I think you are trying to get the union of two querysets. If this is the case, you can use: c.common.externalLinks.all() | m.common.externalLinks.all() An alternative may be to use: ExternalLink.objects.filter(common__in=[m.common, c.common]) But that will depend on what the rest of your code looks like. An aside on python style: try to use snake_case rather than camelCase. Okay, it's not the union you want: perhaps you want to add all of the values from m.common.externalLinks.all() into c.common.externalLinks? c.common.externalLinks.add(*m.common.externalLinks.all()) Or, if you only want the first one: c.common.externalLinks.add(m.common.externalLinks.all()[0])

Categories : Python

Bug in Django queryset with count?
Ok, So I figured out where my problem was, it was in the init function, I got rid of it and used my manager's code instead, but I still think something is wrong with the queryset on django's side. class EmailChangeLogManager(models.Manager): def get_query_set(self): return super(EmailChangeLogManager, self).get_query_set().filter(state=EmailChangeLog.PENDING) def create_new_request(self, user): request = self.model() salt = hashlib.sha1(str(random.random())).hexdigest()[:5] username = user.username if isinstance(username, unicode): username = username.encode('utf-8') request.token = hashlib.sha1(salt+username).hexdigest() request.user = user request.save() return request EDIT: There seems to

Categories : Django

django queryset - hitting the db in O(1)
Use latest("execution_end_date") on your queryset: lji = JobInstance.objects.filter(job_type=job_type, agent=agent).latest('execution_end_date') Or add it to your model's Meta class like so: class JobInstance(models.Model): .... class Meta: get_latest_by = "execution_end_date"

Categories : Python

queryset django relationship
Filter using __isnull: Normally, Django automatically follows relationship fields using the lowercased name of the related model: Income.objects.filter(invoice__isnull=True) Here, you've specified the related_name attribute, so you need to use that: Income.objects.filter(Income__isnull=True) Note that this reveals that your related name attribute for the income FK on Invoice is backwards. I see no reason for you to be setting a related_name at all, but if you do need one it should describe how the invoices are related to incomes, not vice versa.

Categories : Python

django - how to get value of key-value queryset from values()
Use dot notation in Django templates: {{ object.column }} Dots have a special meaning in template rendering. A dot in a variable name signifies a lookup. Specifically, when the template system encounters a dot in a variable name, it tries the following lookups, in this order: Dictionary lookup. Example: foo["bar"] Attribute lookup. Example: foo.bar List-index lookup. Example: foo[bar]

Categories : Python

Django Queryset for date
Try this: from datetime import datetime, timedelta Example.objects.filter(date_created__lte=datetime.utcnow() - timedelta(days=6*30)).delete()

Categories : Python



© Copyright 2017 w3hello.com Publishing Limited. All rights reserved.