django,django-models,many-to-many,manytomanyfield,junction-table , How to add an entry to ManyToManyField in Django?


How to add an entry to ManyToManyField in Django?

Question:

Tag: django,django-models,many-to-many,manytomanyfield,junction-table

I have the following models:

class Vote(models.Model):
    cmt = models.ForeignKey(Comment)
    user = models.ForeignKey(User)
    vote_type = models.SmallIntegerField(default=0) # vote_type is +1 for upvote & -1 for downvote

class Comment(models.Model):
    uuid = models.CharField(max_length=40, default='random')
    user = models.OneToOneField(User, primary_key=True) # ForeignKey('User')
    text = models.CharField(max_length=300, null=True)
    votes = models.ManyToManyField(User, through='Vote', related_name='votes_table')

If I wasn't using the through keyword, I could have just added an element to votes field in Comment object (having uuid of id), like this: Comment.objects.get(uuid=id).votes.add(some_user) But this won't work here, since I have to store a vote_type for each entry in comments_votes table. How can this be done?


Answer:

Just create the Vote instance as described in the docs:

Vote.objects.create(cmt=Comment.objects.get(uuid=id),
                    user=some_user, vote_type=1)

Related:


Django file upload took forever with Phusion Passenger


django,apache,file-upload,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...

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


django,sorl-thumbnail
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...

Permission denied Setuptools


python,django,curl,setuptools
I'm trying install setuptools in my Mac, but when I run command curl https://bootstrap.pypa.io/ez_setup.py -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:...

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


django,django-models,django-admin
In https://docs.djangoproject.com/en/1.8/ref/models/fields/#django.db.models.Field.default 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(default=datetime.datetime.now()) When in the admin page I create a new object I always get the same datetime, as if the callable is...

How to use template within Django template?


python,html,django,templates,django-1.4
I have the django template like below: <a href="https://example.com/url{{ mylist.0.id }}" 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 REST tutorial DEBUG=FALSE error


python,django,django-rest-framework
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...

Create angular page in Django to consume data from JSON


angularjs,django,django-templates
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= "http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script> </head> <body data-ng-app="myApp"> <div data-ng-controller="MainController">...

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


python,django,pip,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...

How can i hook into django migrations for django 1.8


python,django,migration
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...

Django: Handling several page parameters


python,django,list,parameters,httprequest
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 block inclusion not working. What did I miss?


django,django-templates
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...

DjangoCMS 3 Filter Available Plugins


django,django-cms
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...

Does Django implement user permissions in databases with models?


python,django,orm,django-admin
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...

DRF Update Existing Objects


django,django-rest-framework
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:...

Button updates text of first element instead of selected element


javascript,jquery,html,django,django-templates
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: {%...

Django MySQLClient pip compile failure on Linux


python,linux,django,gcc,pip
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 ClearableFileInput - how to detect whether to delete the file


django,django-forms,django-crispy-forms
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 =...

upload_to dynamically generated url to callable


python,django,models
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...

How can I resolve my variable's unexpected output?


django,python-2.7
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...

Django test RequestFactory vs Client


django,unit-testing,django-views,django-rest-framework,django-testing
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...

Use django to expose python functions on the web


python,django
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: show newlines from admin site?


python,html,django,newline,textfield
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!

Django include template tag alternative in python class


python,django,django-templates
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...

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


python,django,rest,file-upload,request
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 and python manage.py runserver execution error


python,django,manage.py
When I execute python manage.py 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 http://127.0.0.1:8000/ Quit the server with CONTROL-C. Traceback (most recent call last): File "manage.py",...

Using .update with nested Serializer to post Image


django,rest,django-models,django-rest-framework,imagefield
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...

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


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...

django 1.8 CreateView Error


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

Switch Case in Django Template


python,django,django-1.3
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: {%...

Django listview clone selected record


django
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...

Django add an attribute class form in __init__.py


python,django,forms,django-forms
My form class from django import forms class Form(forms.Form): your_name = forms.CharField(label='Your name ', max_length=100) My app file __init__.py 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 __init__.py add an attribute captcha but it is not on the page. I...

Django does not render my forms' fields


django,django-models,django-forms,django-templates,django-views
I have this model in models.py: 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 forms.py contains: class LifeEventsForm(forms.Form): def __init__(self,...

Show message when there's no excerpt - Django templates


python,django,django-templates,django-template-filters
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...

Get the first image src from a post in django


django,django-templates,django-views
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(default=timezone.now) publish = models.BooleanField(default=False) In the admin it looks like this:...

django cannot multiply non-int of type 'str'


python,django
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(quote=self.pk).aggregate(Sum('unit_price' * 'quantity')) total_amount = property(_total_amount) In the shell : q=Quote.objects.get(pk=2) // valid...

Django TemplateDoesNotExist Error on Windows machine


python,django
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...

Upload to absolute path in Django


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...

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


django,django-models,django-queryset
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 to work with django-rest-framework in the templates


json,django,django-templates,django-rest-framework
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(default=date.today) 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 })...

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


python,django
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...

User registration endpoint in Django Rest Framework


django,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')...

Why is Django widgets for TimeInput not showing


django,django-forms,django-templates,django-views
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 models.py, class TimeLimit(models.Model): before = models.TimeField(blank=True, default=time(7, 0)) # 7AM after = models.TimeField(blank=True,...

Django: html without CSS and the right text


python,html,css,django,url
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...

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


django,django-templates,django-views
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'},...

Django template not found in main project directory error


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

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


python,django,osx,notifications,vagrant
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...