w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
Manipulating / Organizing ManyToManyField values in Django
You can get information from living models like this https://github.com/mkai/django-followers/blob/master/followers/utils.py Just see how they made function get_people_following_user and compare to UserLink model

Categories : Django

Django: Two ManyToManyField to the same model
To get all questions asked by a certain user, use Question.objects.filter(author=user). Similarly, to get all questions favorited by a certain user, use Question.objects.filter(favourite_users=user). The documentation contains some very helpful examples of lookups across many-to-many relationships.

Categories : Django

Django : ManyToManyField is missing from table
Django creates a separate table for many to many field,with references to both the tables.The new table will have foreign key to both the tables,movies and genre. So you wont see a new column,but you will surely find a new table. So whenever you add genre for the movie, a new row is created for every genre you add in the movies_genre table. For example for a movie a with movie id 1, you add genre b,c with genre ids 1,2, the following are created in the movie_genre table id movie_id genre_id 1 1 1 2 1 2

Categories : Django

Django's inspectdb doesn't do ManyToManyField
Your database schema appears to be alright. However Django doesn't automatically create Many-To-Many fields as you have found out. The models for driverclass_event and ** driver_driverclass_event** are a so-called 'through' models. Normally you would also define ManyToManyField on both ends of the relationship and specify the correct 'through' model: class Event(db.Model): pass class DriverClass(db.Model): events = db.ManyToManyField(Event, through='DriverClassEvent') class DriverClassEvent(db.Model): driver_class = db.ForeignKeyField(DriverClass) event = db.ForeignKeyField(Event) See also: https://docs.djangoproject.com/en/dev/topics/db/models/#extra-fields-on-many-to-many-relationships Normally through models are used when you want to store information about the rel

Categories : Mysql

Getting total price for a ManyToManyField in Django
No need to add the dollar_amount field, that is duplicate information. Instead make it a property, this is how you get the total price: from django.db.models import Sum p = PurchaseOrder.objects.filter(...) p.annotate(Sum("products__price_for_each_item")

Categories : Python

How to include a ManyToManyField in an email? Django
You'll need to iterate through your products. I think you can do something like: for item in instance.products: body_text += 'Product': item Although, you should really be using a template and the EmailMessage class.

Categories : Python

Django - Is ManyToManyField required to use over ForeignKey?
ForeignKey and ManyToMany are two different things. You probably mean ForeignKey v/s OneToOne An example: Lets take some arbitrary Developer model class Developer(models.Model): user = models.OneToOneField(User) #ensure there is a one-to-one relationship between User and Developer model - One user object in django.contrib.auth can be associated with only one Developer and vice versa category = models.ManyToMany(Category) #Developer can be part of many categories, and also one category can be associated with many developers birth_address = models.ForeignKey(Address) #He can have only birth place. The address can be associated with many, so it is a `OneToMany` relationship So, ManyToMany is many-to-many relationship and ForeignKey is a restricted ManyToMany (a many-to-one r

Categories : Django

Extend Django's ManyToManyField with custom fields
This is not the correct way to do it. See Extra fields on many-to-many relationships in the Django documentation. Besides, the CustomManyToManyField you created is a custom field, not a model, so it can't contain fields.

Categories : Python

Django how to delete from ManyToManyField with extra field?
You can remove the instance on the intermediary model. From the example provided in djangoproject: m_qs = Membership.objects.filter(person=person, group=group) #or some other logic to filter try: m = m_qs.get() #assuming queryset returns only 1 element m.delete() except: pass #handle more gracefully

Categories : Django

django display ManyToManyField as a form field
When looping over the form, it should be: {% for field in form %} {% if field.name == "gvtCompo" %} {% for gvtCompo in form.instance.gvtCompo.all %} {{ gvtCompo.gvtCompo }} {% endfor %} {% endif %} {% endfor %} field itself has no related field.gvtCompo.

Categories : Django

Checking if an item is contained in a ManyToManyField (django)
It still not clear to me what object you want to see if connected to other but if you want to know if a user is in an specific event you can do it like this: {% if event in user.eventList.all %} Display Message1 {% else %} Display Message2 {% endif %} You can use operator in in if conditions in modern django versions. Hope this helps!

Categories : Python

Displaying multiple instances in a ManyToManyField in Django
You can use string concatenation to concatenate the name with the price. If products should be the first part of the string and price_for_each_item the second part, use: def get_products(self): return "<br />".join("%s %s" % (p.products, p.price_for_each_item) for p in self.product.all()) A few unrelated comments: Note that, according to the XHTML standards (and recommended by the HTML standard), a tag without any real content, like the <br> tag should be self-closing (thus <br /> instead of <br> </br>). Also, removing the square brackets inside the join function will create a generator instead of a list. This will not create a (useless) intermediary list in memory and the process will be slightly faster. I think it's a good habit to develop in case yo

Categories : Python

Django-date incrementation in a list with ManyToManyField
Yep, make interval an IntegerField or maybe rather a PositiveSmallIntegerField since it will never get a negative value nor a very huge number. Careful, better don't mix plural and singular in model names, they affect the related names when you traverse your foreign keys which makes it a pain to debug, see here. I prefer to use only singulars. Instead of: visit = Visit.objects.filter(patient_id=patient.id) You can simply type: visit = Visit.objects.filter(patient=patient) Try something like this def visit_profile(request, slug): patient = Patients.objects.get(slug=slug) visitimm = [] # Looping over all active visit records of the patient in date order for v in patient.visit_set .filter(active=True).order_by('date_of_visit'): # Looping o

Categories : Python

Django: getting FIRST item that belongs to a model object in a ManyToManyField
.first() is new in the Django Development version. See the docs: https://docs.djangoproject.com/en/dev/ref/models/querysets/#first Until it's out as stable, or you run the dev version, stick with what you have. The QuerySet is lazy, and "should" take the least-work approach. If you're concerned, check your query log in the MySql General Log. (from the docs) Note that first() is a convenience method, the following code sample is equivalent to the above example: try: p = Article.objects.order_by('title', 'pub_date')[0] except IndexError: p = None

Categories : Django

Getting list-display to show ManyToManyField in an organized format Django
You can use filter_horizontal: class PurchaseOrderAdmin(admin.ModelAdmin): list_display = ('get_products') filter_vertical = ['product'] Or you can use an inline: class ProductInline(admin.TabularInline): model = Product class PurchaseOrderAdmin(admin.ModelAdmin): inlines = (ProductInline,)

Categories : Python

Django - Accessing model from django.contrib's User class via ManyToManyKey
There you go: if user.is_authenticated() and story not in liked_stories: In this line the error is thrown. The code you have posted does not resemble the code you are executing.

Categories : Django

How to cast Django form to dict where keys are field id in template and values are initial values?
If you have the auto_id set to True then you can get the id with form_object_instance.field_name.auto_id. With that in mind you can create your dict by iterating over the form object. I am just wondering why you would need to do such a processing as the form object is usually used to encapsulate such behaviors...

Categories : Django

How getting ManyToManyField("self") in the template?
It works the same way: {% for sequel in film.sequels.all %}{{ sequel.titolo }}{% endfor %} If there aren't any sequels, use {% empty %} {% for sequel in film.sequels.all %} {{ sequel.titolo }} {% empty %} <p>No sequels</p> {% endfor %}

Categories : Django

How to Import This ManyToManyField from JSON?
To add to a items many-to-many you use components.add(item) i.e for component in items["components"]: db_item.components.add(component) Many to many relations uses a so called lookup table, you have defined such a table via the through="Composition" parameter. This means the Composision model will be used as the special table to store those relations. if you dont specify a through table django will create one automatically to be used transparently.

Categories : Django

Authenticating users that inherit from the django user class or django.contrib.auth.models.User
Make sure your model is in an app that's in your installed apps list, the Auth_USER_MODEL is set as @alecxe mentioned, and that you ran sync db. If you ran sync db BEFORE you setup your new user model, you'll need to nuke the database and run it again now that your model is in place. This could explain why everything seems to be working but it's not.. From the docs: Changing AUTH_USER_MODEL has a big effect on your database structure. It changes the tables that are available, and it will affect the construction of foreign keys and many-to-many relationships. If you intend to set AUTH_USER_MODEL, you should set it before creating any migrations or running manage.py migrate for the first time. Changing this setting after you have tables created is not supported by makemigrations a

Categories : Python

How to render models.ManyToManyField checkbox widgets horizontally?
I've done it using Crispy fields. Very simple and usefull. Plus you can use Bootstrap toolkit. And yours life will be more esier. http://django-crispy-forms.readthedocs.org/en/1.1.1/tags.html

Categories : Django

In Django, how to sort instances of a child model class based on a field of its parent model class?
did you try: class Meta: ordering = ['product_name', 'product'] #or ordering = ['product', 'product_name'] def __unicode__(self): return str(self.product_name) + " - " +str(self.product)

Categories : Django

Difference between assigning values to attributes in child class and parent class
This is really a question of class design and maintenance. Obviously in this case there are no characteristics that Humans have that Mammals don't and no other Mammals. But, for instance, let's say you later update Mammal to have a "feet" attribute: class Mammal(object): def __init__(self, name, feet): self.name = name self.feet = feet Mammals now have a number of feet, and so you might expect Humans to also. But me.feet will throw an error, because the Human __init__ didn't initialize it, and the Mammal __init__ didn't run. Nor can you declare feet with me = Human('Joe', 2), because the Human __init__ doesn't take that argument. So you've created a maintenance problem -- Humans are now not really good Mammals, because some of their promised attributes are always und

Categories : Python

Requesting class constant value in Ruby returns all defined values within this class
Your syntax defines First as an Array, while also defining Second as 2 and Third as 3 in the process. Remove the commas to have First set to 1: class Values First = 1 Second = 2 Third = 3 end

Categories : Ruby

Can´t check if array values are true from another class in main class
There's some unusual architectural choices here, but the specific problem you're facing is that you're re-creating the Bitmaps every time, and comparisons are performed by reference, not by value. Change your bildelisteDyr class as follows: public class bildelisteDyr { static Bitmap[] bildeListeInternal; static bildelisteDyr() { bildeListeInternal = new Bitmap[21]; bildeListeInternal[0] = Properties.Resources.ål; //... bildeListeInternal[20] = Properties.Resources.turtle; } public static Bitmap bildeListe (int index) { return bildeListeInternal[index]; } } Some more resources on the conceptual problem: == Operator Value vs Reference Types

Categories : C#

Is it possible to move variable's values from one class to another class without inheritance in java?
Using static you can archive that: public class class1 { public static string myname = "light"; } public class2 { public static void displayMyname() { System.out.println(class1.myname); } } Notic that the method that display the values must be static as well.

Categories : Java

Map with Class as keys and values having objects operating on key class instances
You can't do this with just a normal Map; you have to do your own wrapping with a method that enforces the type constraint. See the related question Java generics enforce same type for keys and values of map.

Categories : Java

Accessing values from other class and how to access base class variable
In 1. you are creating anonymous instances using new and you access their member className. In 2. you can use super.className INSIDE your derived class. class SecondClass extends FirstClass{ public String className="SecondClass"; public String extend=new FirstClass().className; public void method() { String cn = super.className; } } Apart from this possibilities, you are grinding OO-principle of data-hiding to pieces. If you want to access a base-class member, either make the base-class member protected or create getter/setter-methods.

Categories : Java

Django Inline Admin : Error : has no ForeignKey to
syncdb does not detect changes (read the section Syncdb will not alter existing tables) . You either need to - Drop the database and recreate (not very recommended) or - Install a 3rd party app called django-south to modify the database colums and manage the migrations

Categories : Python

Is it possible to use css wildcard class selector where there are multiple class values?
You were using an incorrect selector - a [class] is all anchors with a class as a descendant. Basically, any element descending from an <a>, which starts with or contains the class icon- will be targeted. What you want is to select all anchors starting with or containing that class themselves - a[class]: a[class^="icon-"], a[class*=" icon-"] { text-decoration: none; color: #1BA1E2; } jsFiddle example here.

Categories : CSS

assigning values to structure of a class using class object
The problem is your usage of sprintf. sprintf will not allocate any memory for you, active, suspended and erased are pointing to strange and undefined addresses. You are invoking undefined behaviour. Without adding all the normally necessary detail, use std::string and it's operator overloads instead. For simple parsing, use streams. For now, totally avoid any C-string-function, and instead use C++ solely.

Categories : C++

Since functions are first-class values in F#, why can't I use lambdas as values?
You can you just have to call it this way: let result = myConcat "a" ((fun() -> "b")()) When you created myConcat it gets interpreted as: val myConcat : a:string -> b:string -> string It's expecting the second argument as a string, and you are passing it a method. To do what you want you have to declare myConcat as let myConcat a b = a + "+" + b() then yo u can pass in a function as the second argument. This will then get interpreted as val myConcat : a:string -> b:(unit -> string) -> string

Categories : F#

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

how do I set values of CheckBoxes in Django
You should probably rethink your approach. What does the user field in your form mean, and how would you want to select users with it? Most likely a ChoiceField is more applicable. For details about this field, see for example this question. Otherwise, rename your field to make it more descriptive, e.g. selected. In this case, you will have to distinguish between users, which in turn means you will have to prefix your form identifiers and names. In other words, build your form manually. As an example (adjust to your specific needs) {% for user in users %} <input id="user_pk_{{ user.pk }}" value="{{ user.pk }}" type="hidden" /> <input id="user_selected_{{ user.pk }}" type="checkbox"{% if user.selected %} checked="checked"{% endif %} /> <input id="user_some_property_{{

Categories : Django

Django - Integrating django-profiles (and django-registration) with django-facebook
Here's how I suggest you do things. Do away with django-facebook and look into django-allauth. It will handle accounts (registration, logic, connecting social accounts). Also, django-profiles has many issues with 1.5+ for me and I don't bother with it and instead create my own profiles app and UserProfile model with any additional fields that wouldn't be handled by django-allauth. An example from one of my implementations class UserProfile(models.Model): user = models.OneToOneField(User) default_address = models.OneToOneField(Address, blank=True, null=True) default_tshirt_size = models.CharField(blank=True, null=True, choices=constants.tshirt_sizes, max_length=50) default_shoe_size = models.CharField(blank=True, null=True, choices=constants.shoe_sizes, max_length=50) Y

Categories : Python

Django, filter by multiple values
Contracts.objects.filter(band__in=bands) You might want to add a prefetch_related statement there to prefetch the gigs though, otherwise your template loop will hit the DB once per contract. contracts = Contracts.objects.filter(band__in=bands).prefetch_related()

Categories : Django

Django-printing of random values
You create a view for the main page, and another view that returns a random number. Then you write an ajax call in javascript to refresh what you see. Like this: views.py def main(request): return render(request, 'index.html') def random_generator(request): return HttpResponse(randrange(0, 5)) urls.py url('^main/$', 'myapp.views.main'), url('^random/$', 'myapp.views.random_generator') Then in your template: <script type="text/javascript"> function refreshRandom() { $.ajax({ url: '/random/', dataType: 'html', success: function(data) { $('#random').html(data); }, complete: function() { window.setTimeout(refreshRandom, 5000); } }); } window.setTimeout(refreshRandom, 5000); </script> &

Categories : Django

django NoReverseMatch with multiple pk values
You need to rethink your urls. Hopefully the following comments will help. In your family urls you have url(r'^(?P<pk>d+)/person/',include('person.urls',namespace='person')), Then in your person urls you have url(r'^(?P<pk>d+)/$',PersonDetailView.as_view(),name='person-detail'), This suggests a url of the form /family/<pk>/person/<pk>/. That is invalid, as you have used the named argument pk twice in the same pattern. If you rename one of your primary keys in the url pattern, for example: url(r'^(?P<person_pk>d+)/$',PersonDetailView.as_view(),name='person-detail'), Then you can use the pk_url_kwarg option in your PersonDetail view. class PersonDetailView(generic.DetailView): model=Person pk_url_kwarg = 'person_pk' Note also that you have

Categories : Django

Django group by dates and SUM values
Hmm you are using Count, you should use Sum, and values() will determine what goes into GROUP BY so you should use values('datetime') only. Your queryset should be something like this: from django.db.models import Sum values = self.model.objects.filter( datetime__range=(self.dates[0], self.dates[1]) ).values('datetime').annotate(data_sum=Sum('data')) although I'm not so sure about the order of the filter(), so it could be this: values = self.model.objects.values('datetime').annotate(data_sum=Sum('data')).filter( datetime__range=(self.dates[0], self.dates[1]) ) I guess you would wanna try both then. If you want to see the raw query of those queryset, use Queryset.query: print self.model.objects.filter( datetime__range=(self.dates[0], self.dates[1]) ).values('datetime').a

Categories : Mysql

Using Django templates to set default values
Fix this line to wrap {{old_query}} between quotes: <input type="text" class="searchbox" name="s" value="{{old_query}}" /> That should give you the whole search instead of the first word.

Categories : Python



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