django,many-to-many,django-queryset , How to list objects in many to many Django

How to list objects in many to many Django


Tag: django,many-to-many,django-queryset

Considerer this model

class Dealership(models.Model):
    dealership = models.CharField(max_length=50)

class Ordered(models.Model):
    customer = models.ForeignKey("Customer")
    dealership = models.ManyToManyField("Dealership")
    status = models.CharField(max_length=2, choices=status_list, default='p')

I try

$ ./ shell
>>> from new_way.core.models import Ordered, Dealership
>>> q = Ordered.objects.all()[:5]
>>> [i.dealership for i in q.dealership.all]

And generate error

Traceback (most recent call last):
  File "<console>", line 1, in <module>
AttributeError: 'QuerySet' object has no attribute 'dealership'

How to return


all dealership by Ordered.


You're very close:


[i.dealership for i in q.dealership.all]


[dealership for dealership in q.dealership.all()]

Here's sample output from one of my model's M2M relationships on a project which demonstrates what you should see from the list comprehension. shared_with is an M2M field to a model called Profile:

>>> from polls.models import Poll
>>> polls = Poll.objects.all()
>>> for p in polls:
...   print([sw for sw in p.shared_with.all()])
[<Profile: kerri>]
[<Profile: kerri>]
[<Profile: jake>, <Profile: kerri>]
[<Profile: jake>, <Profile: kerri>]
[<Profile: jake>, <Profile: kerri>]
[<Profile: btaylor>]
[<Profile: jake>, <Profile: kerri>]


Using .update with nested Serializer to post Image

I have an ImageField. When I update it with the .update command, it does not properly save. It validates, returns a successful save, and says it is good. However, the image is never saved (I don't see it in my /media like I do my other pictures), and when it...

sorl-thumbnail: Creating a thumbnail inside a for loop in a template

I am trying to create a thumbnail with the size of 100x100 px from an image. I am using a for loop, and the for loops works and the image is rendered but for some reason when I am trying to create a thumbnail it doesn't work. Here is my...

DRF Update Existing Objects

I'm new to DRF and python so go easy on me... I can successfully get the RoadSegment objects, but I cannot figure out how to update an existing object I have the following model: class RoadSegment(models.Model): location = models.CharField(max_length=100) entryline = models.CharField(unique=True, max_length=100) trafficstate = models.CharField(max_length=100) With the following serializer:...

Django: html without CSS and the right text

First of all, this website that I'm trying to build is my first, so take it easy. Thanks. Anyway, I have my home page, home.html, that extends from base.html, and joke.html, that also extends base.html. The home page works just fine, but not the joke page. Here are some parts...

Permission denied Setuptools

I'm trying install setuptools in my Mac, but when I run command curl -o - | python show a message telling: Processing setuptools-17.1.1-py3.4.egg Removing /Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/setuptools-17.1.1-py3.4.egg Copying setuptools-17.1.1-py3.4.egg to /Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages Adding setuptools 17.1.1 to easy-install.pth file error: [Errno 13] Permission denied:...

Upload to absolute path in Django

I am trying to get upload_to of FileField to be an absolute path rather than relative to MEDIA_ROOT. If I make the path absolute I get a 400 error on post of file. If no leading / it stores under MEDIA_ROOT. The uploaded document needs to be held securely and...

Create angular page in Django to consume data from JSON

In an angular controller I have a list of items: app.controller('MainController', ['$scope', function($scope) { $scope.items = [ {"foo":"bar 1"}, {"foo":"bar 2"}, {"foo":"bar n"} ] }]); The following html page, based on angular, displays a list of item: <!DOCTYPE html> <html> <head> <title>list</title> <script src= ""></script> </head> <body data-ng-app="myApp"> <div data-ng-controller="MainController">...

Django ClearableFileInput - how to detect whether to delete the file

I'm using Django Crispy Forms for my form with an option to upload an image (ImageField in my Model) The forms renders as I'd expect, with the checkbox to clear an existing file. However when processing the form submission the 'image-clear' checkbox always gives me a 'None' value. image_clear =...

How to use template within Django template?

I have the django template like below: <a href="{{ }}" target="_blank"><h1 class="title">{{ mylist.0.title }}</h1></a> <p> {{ mylist.0.text|truncatewords:50 }}<br> ... (the actual template is quite big) It should be used 10 times on the same page, but 'external' html elements are different: <div class="row"> <div class="col-md-12 col-lg-12 block block-color-1"> *django...

Django does not render my forms' fields

I have this model in class Life_events(models.Model): patient = models.ForeignKey(Demographic) HSCT_date = models.DateField('HSCT date',null=True,blank=True) HSCT_outcome = models.CharField('HSCT outcome',max_length=100, null=True, blank=True) partaker_in_clinical_trial= models.CharField('Partaker in clinical trial',max_length=200, null=True, blank=True) date_of_input= models.DateField(null=True,blank=True) def __str__(self): return str(self.patient) My contains: class LifeEventsForm(forms.Form): def __init__(self,...

How to list objects in many to many Django

Considerer this model class Dealership(models.Model): dealership = models.CharField(max_length=50) class Ordered(models.Model): customer = models.ForeignKey("Customer") dealership = models.ManyToManyField("Dealership") status = models.CharField(max_length=2, choices=status_list, default='p') I try $ ./ shell >>> from new_way.core.models import Ordered, Dealership >>> q = Ordered.objects.all()[:5] >>> [i.dealership for i in q.dealership.all] And generate error Traceback (most recent call last):...

Django add an attribute class form in

My form class from django import forms class Form(forms.Form): your_name = forms.CharField(label='Your name ', max_length=100) My app file from django import forms from my_app.forms import Form from captcha.fields import ReCaptchaField def register(form): form.captcha=CaptchaField() register(Form) Code in add an attribute captcha but it is not on the page. I...

Django test RequestFactory vs Client

I am trying to decide whether I should use Django's Client or RequestFactory to test my views. I am creating my server using DjangoRESTFramework and it's really simple, so far: class SimpleModelList(generics.ListCreateAPIView): """ Retrieve list of all route_areas or create a new one. """ queryset = SimpleModel.objects.all() serializer_class = SimpleModelSerializer...

Django template not found in main project directory error

I am getting a 'template not found' error, although I've set up a correct template hierarchy (or so I thought) . ├── ├── twinja │   ├── │   ├── admin.pyc │   ├── │   ├── __init__.pyc │   ├── migrations │   │   ├── │   │   └── __init__.pyc │   ├──...

Add field to django ModelForm that are in the model but not in the form

I have a django model and a ModelForm. The model has about 10 fields, but I only want to show a few with the ModelForm for the user. So I have something like this: class Create_EventForm(ModelForm): class Meta: model = Event fields = ['event_name','event_datetime','event_venue','event_url','event_tags','event_zip','event_category','event_description'] However, I can't create an object...

How to get simple ForeignKey model working? (a list of class in another class)

I tried to figure this out on my own :( couldn't quite get there. Pls take pity. . . I'm trying to represent exercise data (a start time an end time and many--an undetermined number of-- heart rates) this is the model I have set up: class HeartRate(models.Model): timestamp =...

How can I resolve my variable's unexpected output?

I have a variable in django named optional_message. If I debug the variable then it says Swenskt but when I try to print the variable on my page the following comes out: (u'Swenskt',) and the variable can't be tested for its length etc. What should I do if I only...

Does Django implement user permissions in databases with models?

In a typical database, admin can assign users and can create tables which can be accessed by only a particular set of users or groups. One can also create queries that can be made by certain users in a database like MySQL. Does Django provide any such functionality or is...

Django file upload took forever with Phusion Passenger

I have a Django app deployed using Passenger (I did not choose mod_wsgi because mod_passenger is already there and being used). When I uploaded an MP3 file (900 kB), Google Chrome displays upload % which reached 100% pretty fast but then it took forever for the resulting page. The database...

Why is Django widgets for TimeInput not showing

I'm trying to create a TimeInput field in a form and noticed that the widget isn't showing correctly. But when I check the localhost:8000/admin, I see the widget showing up correctly. My code is as follows. For, class TimeLimit(models.Model): before = models.TimeField(blank=True, default=time(7, 0)) # 7AM after = models.TimeField(blank=True,...

django and python runserver execution error

When I execute python runserver command for my django_test projects I get following error: System check identified no issues (0 silenced). June 14, 2015 - 20:43:03 Django version 1.8.2, using settings 'django_test.settings' Starting development server at Quit the server with CONTROL-C. Traceback (most recent call last): File "",...

Django: Handling several page parameters

I have several possible parameter to process in a page. Assume x0, x1, x2,..., x1000. It seems awkward to get and process them one by one by request.GET.get('x0'), request.GET.get('x1'), ... Any idea to put them in a list, so that they can be processed in a loop....

Django TemplateDoesNotExist Error on Windows machine

I have been following the tutorial for Django Tango with Django I was trying to add a template as instructed on the link. I am working with Python 2.7, Django 1.8 on a windows 7 machine. Below is the error that I get: TemplateDoesNotExist at /rango/ rango/index.html Request Method: GET...

Use django to expose python functions on the web

I have not worked with Django seriously and my only experience is the tutorials on their site. I am trying to write my own application now, and what I want is to have some sort of API. My idea is that I will later be able to use it with...

django 1.8 CreateView Error

I'm using django 1.8 to create a login form. But the template containing registration form does not render properly. my class SignUpView(CreateView): RegistrationForm = UserCreationForm fields = ['username','password1','password2'] model = User template_name = 'accounts/signup.html' my from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.forms import AuthenticationForm from crispy_forms.helper import FormHelper from...

How do I loop through a nested context dictionary in Django when I have no idea the structure I will recieve

I have a dictionary I am passing to a template that looks something like this: {'leasee': {'respond': {'hour': True, 'day': True}, 'contact': {'phone': True, 'facebook': True, 'email': True, 'other': True, 'text': True}, 'licence': '987654321', 'help': {'beautySupplyProvider': True, 'photographer': True}, 'phoneNumber': '12345678910', 'name': 'Chris', 'certifications': {'yes': True, 'long': 'All of them'},...

How to design a history for n:m relations

Problem: I have a n:m relation between a table A and another table B and it is required to have the complete history of this relation, in other words I must be able to reproduce the status of any point the past. Ideas: My first attempt is to dissect to...

Django MySQLClient pip compile failure on Linux

Django documentation as of v1.8 recommends using mysqlclient connector for the framework. I'm attempting to pip install the package on Ubuntu 14.04 with Python 3.4 and running into a GCC error that I'm unable to find reference to. I'm not an expert on compiling software, so was hoping somebody can...

django cannot multiply non-int of type 'str'

I'm a beginner in python & django coding. I have this model : class QuoteRow(models.Model): (...) quantity = models.IntegerField(blank=True, null=True) unit_price = models.DecimalField(max_digits=12, decimal_places=6, blank=True, null=True) And these lines in another model 'Quote' : def _total_amount(self): return QuoteRow.objects.filter('unit_price' * 'quantity')) total_amount = property(_total_amount) In the shell : q=Quote.objects.get(pk=2) // valid...

Display django runserver output from Vagrant guest VM in host Mac notifications?

I can think of many ways to skin this cat, and Googling hasn't shown an elegant solution either. Does anyone have an easy / elegant way to forward the output from Django's runserver command in a terminal connected to a guest Vagrant VM to the host to display to Mac's...

DjangoCMS 3 Filter Available Plugins

In the DjangoCMS3 documentation it says you can configure DjangoCMS behavior using CMS_PLACEHOLDER_CONF in your settings. For instance: CMS_PLACEHOLDER_CONF = { 'right-column': { 'plugins': ['TextPlugin', 'PicturePlugin'], ... This would make TextPlugin and PicturePlugin to be the only two plugins available inside any placeholder called "right-column". It works, but what if...

How can i hook into django migrations for django 1.8

I am using django 1.8. Now i need to add some custom fields based permisions so i have created a YML file from python models like this description: permissions: ['ADMIN'] award: permissions: ['USER'] Its working fine but my issue if some chnages the field names or reomves some field then...

Callable in model field not called upon adding new object through Django admin

In we read that the callable of a default field value is called, every time a new object is created. In my model I have: when_first_upload = models.DateTimeField( When in the admin page I create a new object I always get the same datetime, as if the callable is...

Django runserver not serving some static files

My local testing server for Django v1.8.2 on Windows 8.1 is only serving certain static files. Others are giving a 404 error. - excerpt urlpatterns = [ url(r'^$', views.index) ] + staticfiles_urlpatterns() - excerpt INSTALLED_APPS = ( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'main', 'users' ) STATIC_URL =...

Django include template tag alternative in python class

I know there is a Django template tag that allows to include other templates like so: {% include 'template.html' %} I am wondering if I could do the same, but in a separate python class (not in the HTML template)? I know that for example the url tag has an...

User registration endpoint in Django Rest Framework

I'm using Django rest framework. I've written the following view to register a new user to the system. @api_view(['POST']) @csrf_exempt @permission_classes((AllowAny, )) def create_user(request): email = request.DATA['email'] password = request.DATA['password'] try: user = User.objects.get(email=email) false = False return HttpResponse(json.dumps({ 'success': False, 'reason': 'User with this email already exists' }), content_type='application/json')...

Django listview clone selected record

From an existing LISTVIEW is there a simple way to create a new record based on existing previos record? 1) select the record 2) call the CREATEVIEW 3) set as initail the data from point 1) would this be possible and which is best? A) Get data from 1) by...

Trying to write a unit test for file upload to a django Restless API

I'm writing a fairly small lightweight REST api so I chose restless as the quickest/easiest support for that. I didn't seem to need all the complexity and support of the django-REST module. My service will only received and send json but users need to upload files to one single endpoint....

Django: show newlines from admin site?

This is probably very simple. My database objects have a TextField. Now, when I add the contents of the TextFields to an html paragraph, there are no new lines. How can I make Django show those newlines? Thank you!

Button updates text of first element instead of selected element

When I select the "Like" button, the button updates properly. However, the "like count" updates the count for the first image only, instead of the image I selected. Any ideas how to make only the selected image's like count update as the button does? Thank you in advance! html: {%...

Get the first image src from a post in django

I have a model to write blogs. In that I'm using a wysiwyg editor for the Blog's descritpion, through which I can insert an image within the description. class Blog(models.Model): title = models.CharField(max_length=150, blank=True) description = models.TextField() pubdate = models.DateTimeField( publish = models.BooleanField(default=False) In the admin it looks like this:...

Show message when there's no excerpt - Django templates

I have this field on a Django template: <p class="border_dotted_bottom"> {{ expert.description|slice:":300" }} <a href="{% url 'profile' expert.username %}">{% trans "read more" %}</a>.... </p> If this object (user) has no 'decription' (a text field) it shows the word 'None', I need to get rid of that, maybe if he doesn't...

Django REST tutorial DEBUG=FALSE error

I'm trying to learn to use the django REST framework via the tutorial. I've gotten to the section "Testing our first attempt at a Web API". When I start the server, I get: System check identified no issues (0 silenced). June 15, 2015 - 00:34:49 Django version 1.8, using settings...

How can I fill the table? (Python, Django)

I faced with a problem: I have 4 lists with data. And I need to fill the table with this data. It is the example of table: So, as you already understood, at first column must be data from a first list, at second - second list, ... I tried...

How to work with django-rest-framework in the templates

Please bear with me. I am just learning django-rest-framework. And I really can't seem to grab it. model: class Day(models.Model): date = models.DateField( class ToDo(models.Model): date = models.ForeignKey(Day) name = models.CharField(max_length=100) very_important = models.BooleanField(default=False) finished = models.BooleanField(default=False) normal view: def home(request): days = Day.objects.all() return render(request, 'test.html', { 'days':days })...

Is there a way to install django with pip to point to a specific version of python in virtualenv

I have a system with CentOS installed. It currently runs python2.6, but python2.7 is also installed. I want to run django 1.7, which is also currently installed. If I run django outside of a virtualenv, it is using python2.6 by default. I didn't install it myself. What I assume is...

upload_to dynamically generated url to callable

I've seen a lot of post about this problem without really understanding how to solve it. I have this model: class Project(TimeStampedModel): name = models.TextField(max_length=100, default='no name') logo = models.ImageField() I'd like to have my image saved to media root following this template: <name>/logo/<filename> At first glance, I would like...

Django block inclusion not working. What did I miss?

In my base.html file I have this: {% block menu %}{% endblock menu %} and in base_menu.html I have this: {% extends "base.html" %} {% block menu %} <nav class="navbar navbar-inverse navbar-fixed-top"> ... stuff ... </div> {% endblock menu %} I would expect the menu html to show where the...

Switch Case in Django Template

I'm trying to put different template for different category based on category ID. I'm using Django 1.3. Switch case is not working with Django 1.3, I get this error: Invalid block tag: 'switch', expected 'endblock' or 'endblock content' but switch case had been correctly closed. Here is my code: {%...