w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
How can I create custom form for User model Django
you want to create a form? create a form say forms.py from django.contrib.auth.models import User from django import forms class CreateUserForm(forms.Form): required_css_class = 'required' username = forms.RegexField(regex=r'^[w.@+-]+$', max_length=30, label="Username", error_messages={'invalid': "This value may contain only letters, numbers and @/./+/-/_ characters."}) email = forms.EmailField(label="E-mail") password1 = forms.CharField(widget=forms.PasswordInput, label="Password") password2 = forms.CharField(widget=forms.PasswordInput, label="Password (again)") def clean_username(self):

Categories : Python

Django: ValueError: Cannot create form field because its related model has not been loaded yet
Firstly, you can try reduce code to: def new2(request, number): po=PurcchaseOrder.objects.get(pk=number) form = WorkflowForm(request.POST or None) if form.is_valid(): new_flow = form.save() return HttpResponse('Good') else: return render(request, 'new-workflow.html', {'form': form, 'purchase': po}) Secondly, I not understood why you at other case wrote forms.ModelChoiceField(...) and another case ModelForm instance forms.ModelForm ?

Categories : Python

How to embed a model's form in another model in Django?
A ForeignKey is simply a pointer to specific row in another table. What your Person model says is "Every person has one or two telephones. Each telephone is stored in another table called 'Phone'." So, unless you are doing something sophisticated, your Person form is asking you to associate two existing Phones for your new Person. (editing to respond to your comment). If what you want to do is to have multiple phones, then what you need is a formset The first thing you need to do is to change which table points at which: instead of the person pointing to a phone, the phone should point to a person. So, for example, add belongs_to = models.ForeignKey(Person) to your phone model declaration. The next step is to actually ask for the phones in your view. Here is where formsets come in. In

Categories : Django

django "is a manually-defined m2m relation through model...which does not have foreign keys to"
I usually reverse m2m definitions as below. In your code above you're seeing a conflict in table names due to the underscore in your model class names. If you remove the underscores it should work. Reversing the relationships could work if you want to keep the underscores. class Option_Choices(models.Model): """ choices for each option """ name = models.CharField(max_length=30) product_options = models.ManyToManyField("Product_Options", related_name='choices') class Product_Options(models.Model): """ products can have many options """ OPTION_TYPE=( ('Color', 1), ) name = models.CharField(max_length=30) option_type = models.IntegerField(choices=OPTION_TYPE) products = models.ManyToManyField("Product", related_name='options')

Categories : Django

How to create relation many to many 3 Model laravel 4
This is correctly answered on comments by Phill, and as he says, you should user Eager Loading. $post = Post::with('comments', 'comments.user')->find(1); Then you can simply iterate like this: foreach ($post->comments as $comment) { echo $comment->user->name . ' said: ' . $comment->title; } Just for clarity tho, I would suggest you to name your $comment->user relationship to author instead, it feels natural to type $comment->author->name. You could do so as: class Comments extends Eloquent { public function author() { return $this->belongsTo('user', 'user_id'); } } // Remember to change eager loading to 'comments.author'

Categories : PHP

How create new instance of a model in relation many to many?
The has_and_belongs_to association adds a method collection_singular_ids= that for the current case will be @furniture.store_ids=. According to the docs The collection_singular_ids= method makes the collection contain only the objects identified by the supplied primary key values, by adding and deleting as appropriate. So, you can use this idea to add the stores to your furniture. Replace <% @store.each do |store| %> <div> <%= f.check_box :stores, store %> <%= store.name %> </div> <% end %> with <% @store.each do |store| %> <div> <%= f.check_box :store_ids, {:multiple => true}, store.id, nil %> <%= store.name %> </div> <% end %>

Categories : Ruby On Rails

Model Form to inline using foreignkey relation
I think I found a solution, but I'm sure there is a more correct way of doing this. class DslamSetForm(forms.ModelForm): def clean(self, *args, **kwargs): if self.cleaned_data and self.instance and self.instance.ip_block and self.instance.ip_block.ip_range and not self.instance.port: super(DslamSetForm, self).clean(*args, **kwargs) split_range = self.instance.ip_block.ip_range.split(' ') ip_list_choices = zip(split_range, split_range) self.fields['ip_address'] = forms.ChoiceField(choices=ip_list_choices) return self.cleaned_data class Meta: model = IP_block

Categories : Django

Django custom user model in admin, relation "auth_user" does not exist
After some digging around I found this https://docs.djangoproject.com/en/1.5/topics/auth/customizing/#custom-users-and-the-built-in-auth-forms The culprit is a function clean_username inside UserCreationForm inside django.contrib.auth.forms.py. A few tickets have been created, but apparently the maintainers don't think it's a defect: https://code.djangoproject.com/ticket/20188 https://code.djangoproject.com/ticket/20086 def clean_username(self): # Since User.username is unique, this check is redundant, # but it sets a nicer error message than the ORM. See #13147. username = self.cleaned_data["username"] try: User._default_manager.get(username=username) except User.DoesNotExist: return username raise forms.Valida

Categories : Django

Django ordering parent model by count of children models in (one to many relation)
child_set is the default related_name of your parent field in the Child model. If you've specified a different one, you will have to change the code accordingly. from django.db.models import Count ordered_parents = Parent.objects.annotate(num_children=Count('child_set')).order_by('-num_childen') Hope it helps.

Categories : Django

Django Rest Framework make OnetoOne relation ship feel like it is one model
What you want is nested relationships like { "url": "http://example.com/api/users/1", "username": "demo", "first_name": "De", "last_name": "mo", "email": "demo@example.com", "profile": { "url": "http://example.com/api/userprofiles/1", "mobile": true, "favourite_locations": [ "Paris", "London", "Tokyo" ] } } To have a similar result, you need to first have a accessor to the user profile, you can use User.profile but it will raise an exception if the user doesn't have an associated profile yet, so there is a little helper : class UserProfile(models.Model): user = models.ForeignKey(User, unique=True) User.user_profile = property(lambda u: UserProfile.objects.get_or_create(user=u)[0]) Ne

Categories : Django

Is it possible to create model of a table from a given table of database in django model
I don't think you can tell inspectdb to generate code only for a certain table. You can just use inspectdb for all tables, and then only use the code generated for the table you want. The modelname usually is the CamelCased version of your underscored_table_name.

Categories : Django

Can I have a Django form without Model
Yes. This is very much possible. You can read up on Form objects. It would be the same way you would treat a ModelForm, except that you are not bound by the model, and you have to explicitly declare all the form attributes. def form_handle(request): form = MyForm() if request.method=='POST' form = MyForm(request.POST) if form.is_valid(): cd = form.cleaned_data #now in the object cd, you have the form as a dictionary. a = cd.get('a') #blah blah encode parameters for a url blah blah #and make another post request and class MyForm(forms.Form): #Note that it is not inheriting from forms.ModelForm a = forms.CharField(max_length=20) #All my attributes here In the template: <form action="{% url form_handle %

Categories : Python

How would I create a CBV using django rest framework which will either retrieve a model instance or create a new one?
for classbased views in django-rest-framework this is usually done by: a GET request to the resource will retrieve records a POST request to the same resource will create a record I believe there are a couple examples of this in the django rest framework documentation

Categories : Django

In Django, if I select_for_update() a particular model instance, will its related model instances be locked as well?
No. The example you give will make 2 queries: SELECT ••• FROM `mymodel` WHERE `mymodel`.`id` = 1 FOR UPDATE; SELECT ••• FROM `related_thing` WHERE `related_thing`.`id` = ?; Clearly only the first locks. However, if you use select_related() the single query would be: SELECT ••• FROM `mymodel` LEFT OUTER JOIN `related_thing` ON (`mymodel`.`related_thing_id` = `related_thing`.`id`) WHERE `mymodel`.`id` = 1 FOR UPDATE; In which case it would lock related_thing as well (at least in MySQL but it might be db dependent).

Categories : Django

Django - Add a field to a form that not should be in a model
You can add additional fields to a ModelForm: class FooForm(ModelForm): extra_stuff = forms.CharField() class Meta: model = Foo fields = ['bar', 'biz']

Categories : Django

django: pass a model to a form
You misunderstand the way scope and classes work in Python. actsToValidate is a class-level property, and will be evaluated when the class is defined. __init__, on the other hand, is evaluated when the class is instantiated. And even if they were evaluated in the right order, it still wouldn't work, because you haven't put modelToUse into the class scope, where it can be seen by the field definition. You need to define the field at the class level without the queryset, then add it in the __init__ method. Like this: class ActsAddForm(forms.Form): actsToValidate=forms.ModelChoiceField(empty_label="Select an act to validate", widget=forms.Select(attrs={'onchange': 'this.form.submit();'})) def __init__(self,*args,**kwargs): modelToUse = kwargs.pop('modelToUse') supe

Categories : Django

how to add a condition of comparing two fields of the model itself in Django model query
Sure, that's what the "F" object is for! from django.db.models import F # snip return self.exclude(full_score = F('actual_score')) Use QuerySet.exclude here, as you want to not get the results that match. If you really want to use QuerySet.filter, you can use a negated "Q" object: self.filter(~Q(full_score = F('actual_score'))).

Categories : Python

Rails controller create action difference between Model.new and Model.create
The Model.new method creates a nil model instance and the Model.create method additionally tries to save it to the database directly. Model.create method creates an object (or multiple objects) and saves it to the database, if validations pass. The resulting object is returned whether the object was saved successfully to the database or not. object = Model.create does not need any object.save method to save the values in database. In Model.new method, new objects can be instantiated as either empty (pass no construction parameter) In Model.new(params[:params]) pre-set with attributes but not yet saved in DB(pass a hash with key names matching the associated table column names). After object = Model.new, we need to save the object by object.save

Categories : Ruby On Rails

django adding fields to model form
Use two separate forms - UserForm, created out of models.User & AddStaffForm but exclude the 'user' field in the AddStaffForm. Use only ONE submit button for both. So your template will look like: <form method="post" action="/path/to/wherever"> {{ user_form }} {{ add_staff_form }} <button>Submit</button> </form> Then, when the user submits the form, process each form independently in the following order: Process the user form first and save the user instance created by the form to the db. if user_form.is_valid() is True, you can do this by simply doing user = user_form.save() Next, process the AddStaffForm but pass commit=False (i.e. staff = add_staff_form.save(commit=False) since it does not contain the value for the user field just yet. Prov

Categories : Django

How I can validate a Django form with a model attribute?
You could override the init method of ChildrenGodfatherForm to initialize default edition def __init__(self, *args, **kwargs): super(ChildrenGodfatherForm, self).__init__(*args,**kwargs) instance = kwargs.get('instance') if instance is not None: self.edition = instance.edition # updating existing object, use its edition else: self.edition = Edition.objects.latest('date') # creating new object, use default edition. and then modify the query in clean method to use this parameter ChildrenGodfather.objects.get(child=self.cleaned_data['child'], godfather=self.cleaned_data['godfather'], edition=self.edition)

Categories : Django

In Django, how do I set a model that has a field with multiple instances of another model?
What you have is correct (you have one person with many positions). I initially thought ManyToManyField but I see this is indeed a one to many relationship if the position are unique to a person.

Categories : Python

Django - Check if model has children (related model)
You can try to get the first element: def hasBooks(self): return len(self.books.all()[:1]) == 1 For sure this will note retrieve all the elements but only the first book of an actor (the slice implies a LIMIT 1 in the SQL query). You can also use the useful exists() function: def hasBooks(self): return self.books.exists()

Categories : Django

Create same model in multiple databases - Django
You should look at the syncdb command - you can call it programmatically like so: from django.core.management import call_command call_command('syncdb') In your case, you'll want to use named arguments for any options you would have passed in at the command line: call_command('syncdb', noinput=True, database=user_db) Hope that helps. Check this out also: https://docs.djangoproject.com/en/dev/ref/django-admin/#running-management-commands-from-your-code

Categories : Python

Create an instance of a Django model with a FileField
You can open the existing file on the filesystem, wrap it in a Django File instance, and pass that in to the field directly: >>> from django.core.files import File >>> from myproject.myapp.models import FileModel >>> with open('/path/to/existing_file.txt') as f: ... wrapped_file = File(f) ... m = FileModel(model_file=wrapped_file) ... m.save() ... >>> m.model_file.name u'files/existing_file.txt'

Categories : Django

How to create Password Field in Model django
Use widget as PasswordInput from django import forms class UserForm(forms.ModelForm): password = forms.CharField(widget=forms.PasswordInput) class Meta: model = User

Categories : Python

Validate Django model form with excluded fields
Try this: class ReviewForm(forms.ModelForm): def clean(self): if self.instance.source == self.instance.target: raise forms.ValidationError("You cannot review your entity") return super(ReviewForm, self).clean() class Meta: model = models.Review fields=["title", "content"]

Categories : Django

Can create new model instance but can not update an existing one oin Django
You're overriding the save method incorrectly by the looks of things: def save(self, *args, **kwargs): if not self.slug: self.slug = slugify(self.title) if not self.point: location = "%s+%s+%s+%s"%(self.address, self.city, self.state, self.zipcode) cord = get_lat_long(location) x,y = cord.split(",") x = float(x) y = float(y) self.point = Point(x,y) self.point2 = Point(x,y) super(classified, self).save(*args, **kwargs) ## wrong indentation! Your super() call should be aligned with the first level of indentation. As you have it, super().save is only called if there is no self.point.

Categories : Django

How to create an unique object for a Django model with a many to many field?
You can not use get_or_create directly for m2m. You can do something like this: user_list = [user1, user2] thread_qs = Thread.objects.filter(users=user_list[0]) for user in user_list[1:]: thread_qs= thread_qs.filter(users=user) try: thread = thread_qs.get() #get if only one object. except MultipleObjectsReturned as e: print 'Multiple Objects Returned' except ObjectDoesNotExist: #create object if does not exist thread = Thread.objects.create() thread.users.add(user_list) thread.save() #this might be redundant

Categories : Django

Edit attributes of a child model from the form representing parent model
Problem 1: delete adress on person deletion You can use post_delete signal to automatically delete the adress once your person is deleted. It's quite simple to use from django.db.models.signals import post_delete from web.programing.roxx.models import Person, Adress @receiver(post_delete, sender=Person, dispatch_uid="person_post_delete") def onPersonDelete(sender, instance, using, **kwargs): # be carefull, the instance doesn't exist anymore in the database adress_id = instance.business_Address.id if id != None: Adress.objects.filter(id=adress_id).delete() But this won't display the adress in the "Are you sure ?" message.. Problem 2: edit the adress in the person admin page For the moment, I don't see any solution simpler than building a custom form to edit Pers

Categories : Python

AngularJS ng-model form driven by ng-repeat over UI model description data how to?
I've just figured out one (but may be not the best?) way to achieve this myself.. see http://jsfiddle.net/vorburger/8CxRC/3/ - basically still based on my square bracket dynamic keys 'trick', but with some pre-processing: for (var i = 0; i < $scope.uimodel.length; i++) { var resolvedModelProperty = $scope.datamodel; var remainingPath = $scope.uimodel[i].model; while (remainingPath.indexOf('.') > -1) { var nextPathSlice = remainingPath.substr(0, remainingPath.indexOf('.')); resolvedModelProperty = resolvedModelProperty[nextPathSlice]; remainingPath = remainingPath.substr(remainingPath.indexOf('.') + 1); } $scope.uimodel[i].modelB = resolvedModelProperty; $scope.uimodel[i].modelL = remainingPath;

Categories : Javascript

Django model method, referring to other model via FK
No need to write a method on PlayerProfile. You can used the built-in relationship manager to look this up via the parent PlayerProfile, provided you know which GameStatus belonging to the PlayerProfile you need to access: # look up first player returned from the PlayerProfile model manager player_profile_1 = PlayerProfile.objects.all()[0] # look up first game status associated with the first player profile, # then access the game_status attribute game_status_1 = player_profile_1.gamestatus_set.all()[0].game_status UPDATE: If you can access the game_status of a game from within a loop like this: {% for playerprofile in game.team.playerprofile_set.all %} {% for game_status in playerprofile.gamestatus_set.get(game_id=game.id) %} {{ game_status.game_status }} {% endfo

Categories : Django

Django: How can I access data of a model through another model?
use {{ post.category.name }} In your templates. Using many to one relations seems more suited. Use it like this. class Category(models.Model): name = models.CharField(max_length = 50) class Post(models.Model): title = models.CharField(max_length=50, blank=True) category = models.ForeignKeyField('Category') If you want to keep the manytomany relationship you can do: {% for post in posts %} {{ post.title }} | of {% for category in post.category_set %} {{ category.name }} {% endfor%} {% endfor %}

Categories : Django

Django Model Form - Unable to update table with foreign key
Since you are editing, you need to get the form object using the object instance. In your case, it tries to create a new object, but since this pk already exists, it is throwing the integrity error. form = ContactForm(request.POST, instance=contact_obj) Move the creation of contact_obj up to the beginning of the view method Something like this: from django.core.exceptions import MultipleObjectsReturned def contact(request, template_name): try: contact_obj = Contact.objects.get(user=request.user) except: #You might want to handle multiple objects returned case here too.. contact_obj = None form = ContactForm(instance=contact_obj) if request.method == "POST": form = ContactForm(request.POST, instance=contact_obj) if form.is_valid():

Categories : Python

django admin - add custom form fields that are not part of the model
It it possible to do in the admin, but there is not a very straightforward way to it. Also, I would like to advice to keep most business logic in your models, so you won't be dependent on the Django Admin. Maybe it would be easier (and maybe even better) if you have the two seperate fields on your model. Then add a method on your model that combines them. For example: class MyModel(models.model): field1 = models.CharField(max_length=10) field2 = models.CharField(max_length=10) def combined_fields(self): return '{} {}'.format(self.field1, self.field2) Then in the admin you can add the combined_fields() as a readonly field: class MyModelAdmin(models.ModelAdmin): list_display = ('field1', 'field2', 'combined_fields') readonly_fields = ('combined_fields',)

Categories : Django

Create a Django model with referencing Models in Manager class
How would I go about creating a "Company" with a default "Showroom? Override the save method of model Company or register a post save signal on model Company. Can I use the unsaved company to create my showroom? No. Updated: class Company(models.Model): name = models.CharField(max_length=100) email = models.EmailField() def save(*args, **kwargs): super(Company, self).save(*args, **kwargs) self.showroom__set.create(name=self.name) Updated by Berdus: class Company(models.Model): name = models.CharField(max_length=100) email = models.EmailField() def save(self, *args, **kwargs): is_first_save = self.pk is None super(Company, self).save(*args, **kwargs) if is_first_save: self.showroom_set.create(name=self.name) Note the se

Categories : Python

Yii validation compare against related model's Attribute when create new model
Try using the safe attribute to validation as shown public function rules() { return array( array('db', 'compareWithSzeriaGyartmanyDb','safe'), ); }

Categories : Validation

Create a model observer that creates an associated model relationship
You should create a UserObserver rails g observer UserObserver and define an action: def after_create(user) domain = user.email.split("@").last if (group = Group.where(domain: domain)).any? GroupUser.create(group.id, user.id) else group = Group.create(domain) GroupUser.create(group.id, user.id) end end I think this might be helpful. UPDATE: Sorry, there was a problem with code. Fixed it.

Categories : Ruby On Rails

django social auth , create user model with email as primary key
Well I am doing facebook login for my ios app. What I am doing is Login to facebook from my app and get the facebook access token Send the facebook email and access token to the django backend Then what I do is, instead of using the django default authenticate method which takes the username and password to authenticate a user, I overwrite my own authenticate method. Doing this is really easy just read Django Custom Authentication In my custom authentication class I verify the email-token pair sent from the front using fb sdk for python and that is it. After than I can login the user using the django in built login

Categories : Python

Rails form to create model with reference
The error comes from this part: @model = Model.new(model_params) I'm pretty sure your model_params is actually params[:model]. If yes, it means it tries to create a record for Model with the attribute ref_models and the values contained in params[:model][:ref_models] You should take off the params[:model][:ref_models] before passing it to the Model.new(params[:model]): def create ref_models = params[:model].delete(:ref_models) @model = Model.new(params[:model]) ref_models.each do |ref| @ref = RefModel.where("ref_name = ?", ref) @model.ref_models << @ref end respond_to do |format| ... end end

Categories : Ruby On Rails

How to obtain the ForeignKey id to create a new form linked with the model?
You have multiple choices to solve this. It really depends on the workflow you want to implement in your app. Choose a description before creating the reward You will have a page listing all the user's descriptions : this is your dashboard view. From here, the user will have to choose the description he wants to add a reward to : by clicking on it, by click on a specific create reward link, etc. This is up to you (ergo/design choice). The main point is to get the description id and pass it to your new_reward view via URLconf (urls.py) with something like this : # urls.py urlpatterns = patterns('', # your urlpatterns ... url(r'^description/(?P<description_id>d+)/reward/add/$', 'your.app.views.new_reward', name='add-reward'), # your urlpatterns ... ) This is just an example.

Categories : Django



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