w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
How Can I save post requests to mongoengine using django forms?
If you use mongoengine>=0.8 then: blog = Blog.from_json('''{ "text": "My first blog post", "tags": [ {"tag":"mongo"}, {"tag":"django"} ] }''').save() or if you already have dict: blog = Blog._from_son({ "text": "My first blog post", "tags": [ {"tag":"mongo"}, {"tag":"django"} ] }).save()

Categories : Django

Are "n" or "ch" prefixes common prefixes when naming int or char variables in C++?
Yes, they are common (esp. in Windows related projects) But different projects may use different coding styles. So if you're working with an existing project, then the best is to stick to the style it already follows. The naming style you mentioned is known as Hungarian style, which is typically used in Windows related projects. In the Hungarian style, variables are formatted in camel case (e.g., CamelCase) and prefixed by their scope and types: [scope prefix]_[variable type][actual variable name in camel-cased style] For example: m_nMemberInteger is an integer (according to it prefix n), in addition, it's a member variable (according to its prefix m_) to some structure / class, and you can find the complete list of scope and type prefixes used in the Hungarian style in the above

Categories : C++

Oracle Forms 10g - why do I have to click save so that my insert query will save to database
Oracle Forms provides a great deal of functionality for you so that you don't have to write it. For example, if you base a block on a table, and if the user enters data and clicks "Save", Oracle Forms knows whether to execute Insert, Update or Delete statements appropriately followed by a Commit. In your case, you have ignored that functionality and have hardcoded an Insert and Commit in your button code. Therefore, the user does not have to click the Save button, because the data has already been "saved" by your Add button.

Categories : Oracle

HTML5 form attributes with Django forms and django-bootstrap-toolkit
You can set the value of the widget.attrs to pass certain other HTML attributes to the form. >>> from django import forms >>> name = forms.TextInput(attrs={'size': 10, 'title': 'Your name',}) >>> name.render('name', 'A name') u'<input title="Your name" type="text" name="name" value="A name" size="10" />' -Django Docs

Categories : Django

Subclassing django-registration 1.0 forms for django 1.5 custom user models
Some parts are most definitely not Django 1.5 compatible yet: https://bitbucket.org/ubernostrum/django-registration/src/8f242e35ef7c004e035e54b4bb093c32bf77c29f/registration/forms.py?at=default#cl-48 class RegistrationForm(forms.Form): # ... def clean_username(self): # ... # The line below needs fixing existing = User.objects.filter(username__iexact=self.cleaned_data['username']) if existing.exists(): raise forms.ValidationError(_("A user with that username already exists.")) else: return self.cleaned_data['username'] So unless those methods are changed and/or you subclass them, it won't work yet. For your specific case this registration form should do the trick: from registration import forms as registration_for

Categories : Django

django make available few of the django admin forms to the users at a different url
When you create a User, you can give different access to any part of your app in the user permission tab. This mechanism should do what you want. If you want to go further and play with the display of your app while keeping something similar to the django admin, you can use the templates of django admin in a view in order to give access to only a part of your model and add more design and custom functions. In this case, I'll suggest you to make a copy of the templates located in djangocontribadmin emplatesadmin and then you can modifiy them as you want.

Categories : Django

Django: How to use django.forms.ModelChoiceField with a Raw SQL query?
Are you sure you actually need a raw query there? Just looking at that query, I can't see any reason you can't just do it with filter(location__city=city_id, available_reserves__gte=0, datetime_from__gt=datetime.datetime.now()). Raw query sets are missing a number of methods that are defined on conventional query sets, so just dropping them in place isn't likely to work without writing your own definitions for all those methods.

Categories : Django

MS Forms ComboBox not updating in VBA during run-time
Thanks to Santosh's suggestions, I was able to fix this. Santosh suggests: Group_Form.CrossVariable_Cbox = groupVar DoEvents This was a partial success. My Debug statement now tells me False, and the ComboBox still displays a blank value. This somehow avoids the initial MS Forms warning, but unless I were to make a selection in the combobox, the next action/event would raise the warning. I played around a bit, and put the DoEvents ahead of the ComboBox assignment: DoEvents Group_Form.CrossVariable_Cbox = groupVar Debug.Print "After updating Group_Form.CrossVariable_Cbox = " & _ groupVar & ": " & (Group_Form.CrossVariable_Cbox = groupVar) Now, my debug statement tells me True, and most importantly, the form displays the correct value in the ComboBox.

Categories : Vba

Save 2 Forms At the Same Time MVC 3
jQuery's submit function actually causes the browser to send a request, i.e. you're submitting the form. To accomplish this you'll need to uses ajax. Something like this should do the trick: $.ajax({ method: 'POST', url: $('#workForm').attr('action'), data: $('#workForm').serialize(), success: function(data) { //grab whatever id you need here var id_thing = $(data).find('#id_here').val(); //do something with id $('#conttForm input[name="your-hidden-id-field"]').val(id_thing); $('#conttForm').submit(); } })

Categories : Javascript

How can I insert the Save Button using Orchard.Forms?
By default submit button will not generated for any form built this way. to add submit button to your form change your code as following : public void Describe(DescribeContext context) { Func<IShapeFactory, object> form = shape => { var f = Shape.Form( Id: "MyLayoutBasicInformation", _BasicInformation: Shape.Fieldset( Title: T("Basic Information"), _FirstName: Shape.TextBox( Id: "FirstName", Name: "First Name", Title: T("First Name"), Description: T("The name for this field") ) ), _Submit:Shape.Submit(Value:"Save") ); ret

Categories : C#

How do i save all inline forms that adding by javascript?
Well I can't see any mistakes, but maybe you can use easier solution to add new form, so that you won't have to use jquery formset at all. Formset class has nice attribute called empty_form: https://docs.djangoproject.com/en/1.4/topics/forms/formsets/#empty-form You can pass it as "empty_form" context variable and add this script inside template: <script type="text/template" id="row-template"> <tr> {% for field in empty_form %} <td>{{ field }}</td> {% endfor %} </tr> </script> <script type="text/javascript"> var formset = {}; $(function() { $('.btn-add-extra-form').click(function() { formset.$total = $('#id_rows-TOTAL_FORMS'); formset.$initial = $('#id_rows-INITIAL_FORMS'); formset.templateRowStr = $

Categories : Django

Save Two forms at the same time using jquery or ajax?
You need to post both forms using .ajax. Serialize the data from both forms and then post to your server script. $("#btnSave").click(function (e) { e.preventDefault(); //Serialize the form data var formOne$ = $('#workForm').serialize(); var formTwo$ = $('#contForm').serialize(); $.ajax( { url : "YOURURL", type: 'post', data : { formOne : formOne$ , formTwo : formTwo$ }, success : function( responseText ){ //Forms were submitted }, error : function( e ){ alert( ' Error : ' + e.statusText ); } }); });

Categories : Javascript

How can i Save two different forms At the same time Using Jquery or Javascript?
Here is how my AJAX suggestion would work: $.post("/form1.php", { //form data here }, function (data) { // get data to use in the second form $.post("/form2.php", { //form data here }, function () { }); }); However, I agree with everyone else to just use 1 form. How are you originally submitting the forms?

Categories : C#

What is the use of forms.py in django
Making models and views "dumb" is by choice: If you use a specific file like "forms.py" where you have your form classes together with their validations, it is much easier and especially faster to unit test these forms than having to use Django's test client. The same goes for models: Any complicated algorithms usually go into a "utils.py" (or similarily named) file, so this can be tested easier. And lastly, when the size of your views.py or models.py file gets larger and larger over time, it is a bit annoying to scroll around the file all the time.

Categories : Django

Forms in Django
You can still do f = Student_Form(request.POST) r = Reagent_Form(request.POST) and django will assign the appropriate fields. To hide the FK field, class Student_Form(ModelForm): class Meta: model = Student exclude = ('reagent', ) class Reagent_Form(ModelForm): class Meta: model = Reagent While saving in the view, def myview(request): reagent_form = Reagent_Form(prefix='reagent') student_form = Student_Form(prefix='student') if request.POST: reagent_form = Reagent_Form(request.POST, prefix='reagent')         student_form = Student_Form(request.POST, prefix='student') if reagent_form.is_valid() and student_form.is_valid(): reagent = reagent_form.save() #first create the object

Categories : Django

having difficulties with submiting two forms within one page with one save button
You can use serialize() function in Jquery and post the data using Ajax. $("#submit_btn_id").click(function(){ var values = $("#frm_id1").serialize(); values += "&"+$("#frm_id2").serialize(); $.ajax({ type : "POST", url : "url_to_post_data_to", data : values, success: function(data) { //do something on success } }); }); url to post is the path to which you want post the data.

Categories : Asp Net Mvc

MVC4 forms that save to entity framework models
When you send in the model to the view, use something like @using(Html.BeginForm("Index")) { @Html.TexboxFor(x => x.Name) // istead of <input type=text> @Html.TextborFor(x => x.Description) <input type="submit" value="Submit button"/> } to bind the model to the view, which in turn will make it post back when you click the submitt button. In the controller you have something like [HttpPost] public ActionResult Index(CourseViewModel model) // because you'd want to use a // view model and not the entity itself { // check if the model is valid // maybe some more logic db.SaveChanges(); return View(model); }

Categories : Forms

Django forms, specifying Model
I'm thinking you are wanting a forms.ModelForm instead of forms.Form: class ThisForm(forms.ModelForm): class Meta: model = TheModel fields = ['text'] Then your view should be able to form.save(). See here for the official documentation.

Categories : Python

Coerce in django forms
TypedChoiceField is just like ChoiceField, except ChoiceField always return unicode. With TypedChoiceField you pass a function that takes one argument and returns the value cast to the type you want. For example, if you want to coerce the value to integer, use: int_field = forms.TypedChoiceField(choices=SOME_CHOICES, coerce=int) The field value will always be an integer or fail validation.

Categories : Python

Django Forms - Many to Many relationships
I'd start by renaming category in the model to categories, and updating the related code accordingly - the singular naming is just going to be a continuous headache. At that point, you're pretty close. In your success branch when submitting an article, assign the categories as a separate statement. article = Article.objects.create( title=form.cleaned_data['title'], body=form.cleaned_data['body'] ) # note changed plural name on the m2m attr & form field article.categories.add(*form.cleaned_data['categories']) # alternately # for cat in form.cleaned_data['categories']: # article.categories.add(cat) return redirect('article_index') # Redirect after POST Oh, and, kudos on avoiding ModelForm. It's muuch easier to hook up the form-instance plumbing yourself, this question wou

Categories : Python

Django What is the best way to format forms?
Well, there are a couple of options that you can take advantage of like: form.as_p form.as_ul form.as_table Its up to you to decide what you would like. As for customizing it with CSS, take a look at how they structured the form here (taken from django docs): <form action="/contact/" method="post"> {{ form.non_field_errors }} <div class="fieldWrapper"> {{ form.subject.errors }} <label for="id_subject">Email subject:</label> {{ form.subject }} </div> <div class="fieldWrapper"> {{ form.message.errors }} <label for="id_message">Your message:</label> {{ form.message }} </div> <div class="fieldWrapper"> {{ form.sender.errors }} <label for="i

Categories : Python

Only using django forms for validation
you can iterate the form and get each field seperately and do whatever you want to do: <form action="/contact/" method="post"> {% for field in form %} <div class="fieldWrapper"> {{ field.errors }} {{ field.label_tag }}: {{ field }} </div> {% endfor %} <p><input type="submit" value="Send message" /></p> Hope this somehow helps ...

Categories : Django

Save/load controls made inside C# windows forms
They say not to reinvent the wheel but you could do this a countless number of ways. It really depends on the style, format, and audience of the user. Sometimes I like to do everything in a simple txt style file this way anyone can easily edit the information. XML will offer you the ability to more easily organize your information which probably will be better. It really is up to you, I would say whatever you are more comfortable with. I personally would make my own little algorithm to search a plain txt file but that is because I am not using XML. You should create a Class just for handling saving and loading the file. Something like public class CustomControls { //more code public void AddCustomControl(Control x) { } public void RemoveCustomControl(

Categories : C#

Django : difference between calling self.model.save() and self.model.save(*args,**kwargs)
The obvious difference is that in the first case you are passing positional and keyword arguments. If you wonder what arguments Model.save() takes and what they do, the simplest thing is to read the source code. Then you'll find something like: def save(self, force_insert=False, force_update=False, using=None): """ Saves the current instance. Override this in a subclass if you want to control the saving process. The 'force_insert' and 'force_update' parameters can be used to insist that the "save" must be an SQL insert or update (or equivalent for non-SQL backends), respectively. Normally, they should not be set. """ if force_insert and force_update: raise ValueError("Cannot force both insert and updating in model saving.") self.save_base(using

Categories : Python

Django wizard interaction between forms
Add get_form_initial() method in your wizard class, for the 2nd step, use data from first step using get_cleaned_data_for_step(). Something like: class myWizardView: def get_form_initial(self, step): if int(step) == 1: # get cleaned data from prev step return self.get_cleaned_data_for_step(str(int(step) - 1)) You may want to manipulate the dict to have appropriate attribute names etc. More reference at Form Wizard

Categories : Django

passing variables in django forms
Just try put the code of the GET method before the if request.method == POST. Something like this: def acoplar_track(request, track_id, ): //Code for GET here if request.method == POST: //Code for POST here //return render GET method

Categories : Django

Django forms.DateInput validation
Maybe '%Y/%m/%d' is not in the DateField's input_formats list. You can try to add it like this: start_date = django.forms.DateField(label=_("Start date"), initial=timezone.now().date(), input_formats=['%Y/%m/%d'], widget=django.forms.DateInput(format = '%Y/%m/%d'), input_formats=('%Y/%m/%d')) end_date = django.forms.DateField(label=_("End date"), initial=None, required=False, input_formats=['%Y/%m/%d'], widget=django.forms.DateInput(format = '%Y/%m/%d'), input_formats=('%Y/%m/%d')) Hope this helps!

Categories : Django

How to add fields to Django Forms with a decorator
You have to replace the forms' constructor in the decorator like so: def form_with_captcha(orig_form, theme=None): if hasattr(orig_form, "captcha"): raise ValueError("form already has a field captcha!") orig_form.__orig__init__ = orig_form.__init__ def new_init(self, *args, **kwargs): self.__orig__init__(*args, **kwargs) self.fields["captcha"] = self.captcha orig_form.__init__ = new_init orig_form.captcha = ReCaptchaField(attrs={"theme": theme or "white"}) return orig_form

Categories : Python

Do not resubmit forms in Django wizard end
Looks like overriding render_done() method works great. But my problem was all about validation. I had field where validator was checking if user exists. If it does not - he was created on that step. So revalidation will alway fail here :). Remvoing this code: if not form_obj.is_valid(): return self.render_revalidation_failure(form_key, form_obj, **kwargs) solved revalidation issue at the wizard end.

Categories : Django

django forms passing parameters
The problem is that you're not persisting the value across requests. Once you do a post, your parameter is not present on the WayForm instance. To get around this, you can initialize your form like so: def acoplar_track(request, track_id): newWays_l = x.getTrackWays() formulari = WayForm(request.POST or None, request.FILES or None, waysNumber = len(newWays_l)) if request.method=='GET': track = get_object_or_404(Track, id=track_id) return render(request,'principal/wayForm.html') else: if formulari.is_valid(): return render_to_response('principal/inici.html', context_instance=RequestContext(request))

Categories : Django

How to get a time widget in django forms?
You're looking for the DateTime field. birth_time=forms.DateTime() For more info: https://docs.djangoproject.com/en/dev/ref/models/fields/#django.db.models.DateTimeField

Categories : Django

Javascript driven forms in Django
So you want to validate something in JS before submitting. Here's one way to do that. Instead of putting an input of type submit in the form you should put a button of type button: <form id="my-form" submit="..."> ... <input type='button' id='submit-button' value="Save"> </form> Note that unless you specify the type as "button", it will still try to submit. Then in a JS file you write something like this (include jQuery in your HTML file): $('#submit-button').click(function() { var errors = testErrors(); // this function tests for the errors. if (errors != "") { alert(errors); } else { $('#my-form').submit(); } } Example testErrors(): function testErrors() { var country = $("#id_country").val(); var city = $("

Categories : Javascript

Django Forms, fields and models
You can set user by creating an empty instance of the Suggest model: def some_view(request, ...): suggest = Suggest() initial = {} if request.user.is_authenticated(): suggest.user = request.user initial['name'] = request.user.get_full_name() form = SuggestForm(..., instance=suggest, initial=initial) if request.method == 'POST' and form.is_valid(): form.save() ... To display only part of the fields You can use two separate forms (with name and without) or add an {% if user.is_authenticated %} statement in your template to skip the name field when rendering HTML of the form.

Categories : Django

Django crispy forms not loading CSS
You need to include the css/js yourself. So... Download bootstrap, put the files in your static files directory, include a link to the bootstrap css/js files in your base.html template, then you will be able to see the proper formatting.

Categories : Django

Gathering information from few forms in django
I think this would be most easily solved by making a form which includes both the search term and any filters; you can place the form elements wherever you want. Your form would have to be something like: from django import forms class MySearchForm(forms.Form): FILTERS = (("lt20", "Less than 20"), ("20to50", "Twenty to fifty"), ) term = forms.CharField() filters = forms.MultipleChoiceField(widget = CheckBoxSelectMultiple, choices = FILTERS) Then you would have to display the form manually, so you can split it up however you want in the template. In other words, instead of using a filter like {{form.as_p}}, you would have to do {{form.term}} and {{form.filters}}. You could also define your filters in a model, so that yo

Categories : Python

Add other elements than fields in Django forms
In this case, I would use an AJAX form to post entries in the back end, and upon submission recall the entries and write it out as JSON. Django has native functionality for all of this. Here is a recent SO example: How to submit form without refreshing page using Django, Ajax, jQuery?

Categories : Django

How to integrate JS frameworks with django forms
I would do this simply by adding the <script> and <style> tags required by select2 in a {% block extra_header %} inside the template where the form is rendered. Those script tags should load the select2 library and run it for the select box directly in the client side (no server side changes are required IMHO). Any DOM changes that may be required should also be done in those scripts (this keeps the new feature encapsulated and isolated). The {% block extra_header %} should load directly into the <header> section of the main template.

Categories : Django

Django forms "pattern" for this situation?
You can do something like this: Create a dictionary of the forms, FORMS = { 0: CreateWomanProfileForm, 1: CreateManProfileForm } And in the views: def create_profile(request, template): is_man = 1 if request.session.get('user_type_cd') == 'man' else 0 if request.method == "POST": form = FORMS.get(is_man)(request.POST) if form.is_valid(): # Do stuff return HttpResponseRedirect(reverse('do-next-thing')) else: form = FORMS.get(is_man)() return render_to_response(template, locals(), context_instance=RequestContext(request)) Or even this should work def create_profile(request, template): is_man = 1 if request.session['user_type_cd'] == 'man' else 0 form = FORMS.get(is_man)(request.POST or None) if req

Categories : Django

Django: How are forms related to models?
Conceptually, forms serve as the handler for inputting data in your HTML in order to use that data somewhere in your application (in your views). You'll find two common uses for forms in Django: working with your models (data defined by your database) or for the purposes of accomplishing some kind of task (like sending an e-mail - where you don't necessarily need to have an associated model). Forms do a lot of things for both of these functions. These range from modularity, extensibility and ease of management (as they can be easily defined, interchanged, inherited etc. in Python) to validation (one of the biggies). Validation is crucial - and it's probably what you are referring to in terms of registration. Django Forms will validate against a definition either defined in your Form cl

Categories : Django

Django - dynamic forms for GenericForeignKey
Just in case someone would benefit from this. I ended up with 2 forms with different prefixes: 1) for the MainModel, 2) dynamically created for the selected content_type. The fields of form 2) are dynamically added to the site (on content_type selection) via ajax/jquery load function. The processing of the data & proper save are handled in the view.

Categories : Python



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