Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - Insert listing into table
I want to insert data like this id =[3, 4, 10] into table row one by one like this: download.objects.bulk_create([download(status=1, owner=current_user, file_id_id=img_id, folder_id_id = folder_id)]) but when i run my code, only the first id (id [3]) inserted onto my table. Were should i change my code This is the whole code some_var = request.POST.getlist('_selected_action') data = [str(item) for item in some_var] datastr = data files = [i.replace("file-", "") for i in datastr ] integer_data = [str(item) for item in files] results = [int(x) for x in integer_data] # print results for listing in results: all_img = File.objects.all().filter(id=listing) for img in all_img: img_id = img.id folder_id = img.folder_id current_user = request.user folder = img.folder_id download.objects.bulk_create([download(status=1, owner=current_user, file_id_id=img_id, folder_id_id = folder_id)]) -
How to get my iframe code to display correctly in django cms?
I am using django cms to create my website and a google calendar. However, when I added the code, it comes up as just plain code and won't display the calendar. here is the link to my site: http://138.68.6.151:8000/en/events Can someone explain how to fix this? -
Mandatory slider in oTree/django
I want to use oTree as an alternative for conducting experiments. For this purpose I am looking for a possibility to include mandatory slider questions in forms, i. e. sliders you are required to move before you are able to proceed to the next question. As a start I tried to modify oTrees survey template to achieve a solution for future usage but wasn't able to integrate common approaches like a fieldtracker into the project. Here are two modified (yet currently after a number of unsuccessful try-outs not really functioning) versions of the models.py and views.py files which give a hint in which direction I want to go. # -*- coding: utf-8 -*- ## models.py # <standard imports> from __future__ import division from django.db import models from django_countries.fields import CountryField from model_utils import FieldTracker, from otree import widgets from otree.constants import BaseConstants from otree.db import models from otree.models import BaseSubsession, BaseGroup, BasePlayer class Constants(BaseConstants): name_in_url = 'survey' players_per_group = None num_rounds = 1 class Subsession(BaseSubsession): pass class Group(BaseGroup): pass class Player(BasePlayer): def set_payoff(self): """Calculate payoff, which is zero for the survey""" self.payoff = 0 q_country = CountryField( verbose_name='What is your country of citizenship?') q_age = IntegerFielder(verbose_name='What is your age?', min=13, … -
Django multi tenancy solution
This is a question, I'm asking after a thorough google & SO search. Is there any django app that can help me with multi tenancy in a single schema. Preferably the schema owner shall be able to create sub-user under her/himself as well. I have seen Django-tenant-schema and although its awesome, it uses schema, which I think might not be a good option, if there's more than 200,000 tenant owners. I have also seen django-simple-multitenant, however the solution uses "GNU Affero General Public License v3 which makes it somewhat impractical for anything that would not be free and open source applications." Any help would be appreciated. -
Language choice affects text overflow in html(bootstrap) (Django)
I'm using bootstrap to implement my post detail page. It works well and fit perfectly into tho format when using Korean. But, if I wrote english contents, it overflow the format. What's wrong with it? Here is the code : models.py from django.db import models from django.core.urlresolvers import reverse from django.conf import settings def upload_location(instance, file_name): return "{}/{}".format(instance.author.username, file_name) class Post(models.Model): author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) title = models.CharField(max_length=100) content = models.TextField() image = models.ImageField(upload_to=upload_location, blank=True, null=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class Meta: ordering = ('-created_at',) def __str__(self): return self.title def get_absolute_url(self): return reverse( "posts:detail", kwargs={ "pk": self.id, } ) def get_image_url(self): if self.image: return self.image.url return "http://placehold.it/300x200" post_detail.html {% extends 'chacha_dabang/skeleton/base.html' %} {% load pipeline %} {% block content %} <div class="container"> <section class="post-content-section"> <h2> {{ post.title }} </h2> <h5 style="text-align: right;"> {{ post.created_at }} </h5> <hr class="thin"> <img src="{{ post.get_image_url }}" alt="image"> <p> {{ post.content }} </p> </section> </br> <hr class="thin"> </br> <section id="comment-section" data-post-id={{ post.pk }}> <h3> 댓 글 (<span id="comment-count"></span>)</h3> <ul> </ul> <form method="POST" action=""> {% csrf_token %} {{ form.as_p }} <button type="submit" class="save btn btn-default">Save</button> </form> </section> </div> {% endblock %} {% block custom_js %} {% javascript "comments" %} {% javascript "message" %} {% … -
Set wait_timeout on Django migration
I have a very long migration to run (creating index on large table), and I am getting (2013, 'Lost connection to MySQL server during query') So I tried to set the wait_timeout' via RunPython as below, which the settings has been tested on./manage shell`, but it doesn't seem to help in migration. I am wondering if I run it at the correct place? def set_long_connection(*args, **kwargs): seconds = 28800 cursor = connection.cursor() cursor.execute('SET wait_timeout = {}'.format(seconds)) class Migration(migrations.Migration): dependencies = [ ('feed', '0021_genericapi_extra_ds'), ] operations = [ migrations.RunPython(set_long_connection), migrations.AlterField( model_name='importjob', name='state', field=models.CharField(default=b'new', max_length=25, db_index=True), ), ] -
Django 1.9 + Photologue: no such column
I am using Django 1.9+ Photologue 3.x to build a photo gallery web app. When I am trying to add photo or gallery, it returns 'NO SUCH COLUMN EXCEPTION' Request Method: GET Request URL: http://127.0.0.1:8000/admin/photologue/gallery/ Django Version: 1.9.5 Exception Type: OperationalError Exception Value: no such column: photologue_gallery.slug Exception Location: //anaconda/lib/python2.7/site-packages/django/db/backends/sqlite3/base.py in execute, line 323 Python Executable: //anaconda/bin/python Python Version: 2.7.12 Then I have checked the model file and view file. In model.py @python_2_unicode_compatible class Gallery(models.Model): date_added = models.DateTimeField(_('date published'), default=now) title = models.CharField(_('title'), max_length=250, unique=True) slug = models.SlugField(_('title slug'), unique=True, max_length=250, help_text=_('A "slug" is a unique URL-friendly title for an object.')) description = models.TextField(_('description'), blank=True) is_public = models.BooleanField(_('is public'), default=True, help_text=_('Public galleries will be displayed ' 'in the default views.')) photos = SortedManyToManyField('photologue.Photo', related_name='galleries', verbose_name=_('photos'), blank=True) sites = models.ManyToManyField(Site, verbose_name=_(u'sites'), blank=True) objects = GalleryQuerySet.as_manager() It seems to be right. Since it is Django 1.9, no more syncdb or clear sql methods are available. And I tried migrate/makemigrations, sqlmigrates and none of them works. My idea is to rebuild the sql table but how to achieve this, or any other approaches to solve this issue? Thank you. -
Django isn't serving static files
I'm working with an existing (and previously functional) Django site. We recently upgraded from Django 1.8.13 to 1.10. It works fine when hosted from my machine using PyCharm, but when deployed, all static resources (on the admin and the main site) yield 404's with the message, Directory indexes are not allowed here. Our settings.py contains the following: INSTALLED_APPS = ( ... 'django.contrib.staticfiles', ... ) STATIC_URL = '/static/' PROJECT_DIR = os.path.dirname(__file__) STATICFILES_DIRS = ( os.path.join(PROJECT_DIR, '../static'), ) STATIC_ROOT = os.path.join(PROJECT_DIR, '../static_resources') -
Django with Pycharm - PermissionError at /home/
I set up my first Django project in PyCharm this morning but seem to be receiving the following error whenever I intend to navigate to the /home/ view. This view can essentially be reached via a basic home UR but when I 'runserver' and navigate to the url I receive the following error: PermissionError at /home/ [Errno 13] Permission denied: 'C:\\Users\\Admin\\PycharmProjects \\Shadowrun\\ShadowrunTetraMode\\templates\\ShadowrunTetraMode' Request Method: GET Request URL: http://127.0.0.1:8000/home/ Django Version: 1.9.4 Exception Type: PermissionError Exception Value: [Errno 13] Permission denied: 'C:\\Users\\Admin\\PycharmProjects\\Shadowrun\\ShadowrunTetraMode\\templates\\ShadowrunTetraMode' Exception Location: C:\Users\Admin\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\template\loaders\filesystem.py in get_contents, line 24 Python Executable: C:\Users\Admin\AppData\Local\Programs\Python\Python35-32\python.exe Python Version: 3.5.1 Python Path: ['C:\\Users\\Admin\\PycharmProjects\\Shadowrun', 'C:\\Users\\Admin\\AppData\\Local\\Programs\\Python\\Python35-32\\python35.zip', 'C:\\Users\\Admin\\AppData\\Local\\Programs\\Python\\Python35-32\\DLLs', 'C:\\Users\\Admin\\AppData\\Local\\Programs\\Python\\Python35-32\\lib', 'C:\\Users\\Admin\\AppData\\Local\\Programs\\Python\\Python35-32', 'C:\\Users\\Admin\\AppData\\Local\\Programs\\Python\\Python35-32\\lib\\site-packages', 'C:\\Users\\Admin\\AppData\\Local\\Programs\\Python\\Python35-32\\lib\\site-packages\\FontTools', 'C:\\Users\\Admin\\AppData\\Local\\Programs\\Python\\Python35-32\\lib\\site-packages\\win32', 'C:\\Users\\Admin\\AppData\\Local\\Programs\\Python\\Python35-32\\lib\\site-packages\\win32\\lib', 'C:\\Users\\Admin\\AppData\\Local\\Programs\\Python\\Python35-32\\lib\\site-packages\\Pythonwin'] I did attempt to set the 'Override default permissions on file' and ' Override default permissions on folders'in PyCharm's Settings> Build,Execution,Deployment > Deployment> Options but to no avail. I am running PyCharm on Windows 10. I am wondering whether anybody might be able to point me in the right direction? Any advice would be highly appreciated! Mike -
Creating ModelAdmin that has more then 1 view
I'm currently working on a project that has a more of a complex Admin page. Currently what I'm trying to accomplish is when a user adds a Report this report then checks a bunch of data and create a list of people within the area (Less then 10 km). So when they add a report when you click save its changes view to a view that lists all the people it found and their emails, you can then select the people you want to add and press another button which does more stuff. My code is as follows: admin.register(Report) class ReportAdmin(admin.ModelAdmin): change_form_template = 'admin/phone/index.html' # inlines = [SubjectInLine] def response_change(self, request, obj): """ Determines the HttpResponse for the change_view stage. """ opts = self.model._meta msg_dict = {'name': force_text(opts.verbose_name), 'obj': force_text(obj)} context = {} if "_email" in request.POST: msg = _('Report Saved - Now please select the store below you would like to notify.') % msg_dict self.message_user(request, msg, messages.SUCCESS) payload = {'address': str(obj.location.address1) + ' ' + str(obj.location.address2)} start = requests.get("https://maps.googleapis.com/maps/api/geocode/json", params=payload) start = start.json() start_long = start['results'][0]['geometry']['location']['lng'] start_lat = start['results'][0]['geometry']['location']['lat'] start_loc = (float(start_lat), float(start_long)) clients = Clients.objects.filter() context['report'] = obj in_ten = [] for c in clients: payload = {'address': … -
Django Form Not updating
I'm trying to update a form in Django. I have the following: models.py from django.db import models from django.core.urlresolvers import reverse class List(models.Model): def get_absolute_url(self): return reverse('view_list', args=[self.id]) # Create your models here. class Item(models.Model): text = models.TextField(default = '') list = models.ForeignKey(List, default = None) forms.py from django import forms from lists.models import Item EMPTY_ITEM_ERROR = "You can't have an empty list item" class ItemForm(forms.models.ModelForm): class Meta: model = Item fields = ('text',) widgets ={ 'text' : forms.fields.TextInput(attrs={ 'placeholder': 'Enter a to-do item', 'class': 'form-control input-lg', }), } error_messages = { 'text' : { 'required': EMPTY_ITEM_ERROR } } I'm not seeing any changes in the forms.py now that it has been loaded. What I mean is, the page displays the form find, but if I attempt to change, for example, the placeholder value:: 'placeholder': 'Enter a to-do item OR DON'T!', The input box doesn't show any changes once the page loads. Is there a manage.py command I need to run? Or some other migration? -
Where to put a base html template in Django
I have six apps that share a common base html (base.html) template. My question is which should contain that base.html? Or should the project template directory contain that base.html? I am using Django version 1.10. -
Django Static image File Failed to load resource
I have an model called Item within there I have an image field. I added an new item with an image to the database and tried loading it inside of my index template. However I dont get an image when I look at the console it says ("WEBSITENAME/site_media/items/image.jpg 404 (Not Found)") I think the problem lies within the settings.py file but I cant figure out what exactly I did wrong here. index.html template {% load static %} <div class="item" style="background-image: url('{{ item.img.url }}')">` Model.py class Item(models.Model): name = models.CharField(max_length=200) img = models.ImageField(upload_to='items', default='', blank=True, null=True) def __str__(self): return "%s" % (self.name) Views.py def index(request): latestItems = Item.objects.all().order_by('-id')[:3][::-1] return render(request, 'webshop/index.html', {'latestItems' :latestItems}) settings.py SITE_ROOT = os.path.dirname(os.path.realpath(__file__)) MEDIA_ROOT = os.path.join(SITE_ROOT, 'site_media/') MEDIA_URL = 'site_media/' -
Why supervisor doesn't start after `restart` comand?
On Ubuntu 14.04 we have supervisor with 2 working sites on Django (gunicorn). Their configs are similar. All was good, supervisor correctly restart and up. After adding 1 more site - on sudo service supervisor restart he shut down, but doesn't up. And I must hit sudo service start to start supervisor. Here is my config: supervisord.conf: [unix_http_server] file=/var/run/supervisor.sock ; (the path to the socket file) chmod=0700 ; sockef file mode (default 0700) [supervisord] logfile=/var/log/supervisor/supervisord.log ; (main log file;default $CWD/supervisord.log) pidfile=/var/run/supervisord.pid ; (supervisord pidfile;default supervisord.pid) childlogdir=/var/log/supervisor ; ('AUTO' child log dir, default $TEMP) loglevel=debug [rpcinterface:supervisor] supervisor.rpcinterface_factory = supervisor.rpcinterface:make_main_rpcinterface [supervisorctl] serverurl=unix:///var/run/supervisor.sock ; use a unix:// URL for a unix socket [include] files = /etc/supervisor/conf.d/*/*.conf /etc/supervisor/conf.d/*.conf gunicorn.conf: [program:gunicorn] autostart=true autorestart=true directory=/home/project/ command=/home/project/env/bin/gunicorn -b 127.0.0.1:8000 config.wsgi:application stderr_logfile=/var/log/supervisor/project/gunicorn.err.log stdout_logfile=/var/log/supervisor/project/gunicorn.out.log environment=SOME_VARS=‘hello’ Why supervisor doesn't restart correctly after adding 1 more site? -
Django: "referenced before assignment" but only for some variables
I'm writing a small app in Django and I'm keeping the state saved in a few variables I declare out of the methods in views.py. Here is the important part of this file: from app.playerlist import fullList auc_unsold = fullList[:] auc_teams = [] auc_in_progress = [] auc_current_turn = -1 print(auc_in_progress) def auc_action(request): data = json.loads(request.GET["data"]) # ... elif data[0] == "start": random.shuffle(auc_teams) print(auc_unsold) print(auc_in_progress) auc_in_progress = [None, 0, None] print(auc_in_progress) The auc_unsold and auc_teams variables work fine; the auc_in_progress variable is not seen by this method, though, giving the error in the title. If I take out the print statement and let this code assign a value to it, the exception will be thrown somewhere else in the code as soon as I use that variable again. I have tried making another variable and this new one seems to suffer from this problem as well. What is happening? -
restframework 'tuple' object has no attribute '_meta'
Django throws the next exception: restframework 'tuple' object has no attribute '_meta' Model class BDetail(models.Model): lat = models.FloatField(blank=True, null=True) lng = models.FloatField(blank=True, null=True) class Meta: # managed = False db_table = 'b_detail' View from .models import BDetail from .serializers import BDetailSerializer from rest_framework import viewsets class BDetailList(viewsets.ModelViewSet): queryset = BDetail.objects.all() serializer_class = BDetailSerializer urls from django.conf.urls import url, include from bdetail import views from rest_framework import routers router = routers.DefaultRouter() router.register(r'bdetail', views.BDetailList) urlpatterns = [ url(r'^', include(router.urls), name='bdetail') ] serializers from .models import BDetail from rest_framework import serializers class BDetailSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = BDetail, fields = ('lat', 'lng') Environment: Request Method: GET Request URL: http://apiix.verinmuebles.dev/v1/bdetail/ Traceback: File "/var/www/verinmuebles/current/Env/api/local/lib/python2.7/site-packages/django/core/handlers/exception.py" in inner 39. response = get_response(request) File "/var/www/verinmuebles/current/Env/api/local/lib/python2.7/site-packages/django/core/handlers/base.py" in _get_response 187. response = self.process_exception_by_middleware(e, request) File "/var/www/verinmuebles/current/Env/api/local/lib/python2.7/site-packages/django/core/handlers/base.py" in _get_response 185. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/var/www/verinmuebles/current/Env/api/local/lib/python2.7/site-packages/django/views/decorators/csrf.py" in wrapped_view 58. return view_func(*args, **kwargs) File "/var/www/verinmuebles/current/Env/api/local/lib/python2.7/site-packages/rest_framework/viewsets.py" in view 87. return self.dispatch(request, *args, **kwargs) File "/var/www/verinmuebles/current/Env/api/local/lib/python2.7/site-packages/rest_framework/views.py" in dispatch 474. response = self.handle_exception(exc) File "/var/www/verinmuebles/current/Env/api/local/lib/python2.7/site-packages/rest_framework/views.py" in handle_exception 434. self.raise_uncaught_exception(exc) File "/var/www/verinmuebles/current/Env/api/local/lib/python2.7/site-packages/rest_framework/views.py" in dispatch 471. response = handler(request, *args, **kwargs) File "/var/www/verinmuebles/current/Env/api/local/lib/python2.7/site-packages/rest_framework/mixins.py" in list 45. return self.get_paginated_response(serializer.data) File "/var/www/verinmuebles/current/Env/api/local/lib/python2.7/site-packages/rest_framework/serializers.py" in data 701. ret = super(ListSerializer, self).data File "/var/www/verinmuebles/current/Env/api/local/lib/python2.7/site-packages/rest_framework/serializers.py" in data 240. self._data = self.to_representation(self.instance) File … -
Django template a tag link to another page for another column in the same view
I'm learning Django, and trying to create some practice by extending the polls app from the tutorial. Tried to find an answer but ended up with nothing. Please help! So I created a view that has 2 columns, database name, and DBCreationDate. Then I created a template and an url that would show me a list of the database names (the 1st column of my view), and a hyperlink which I intend to link me to another page showing me the DBCreationDate. The following is my view: def DBList(request): db = DBListACCPAC() context = {'DBList': db} return render(request, 'polls/DBDate.html', context) Then my template: {% if DBList %} <ul> {% for DB in DBList %} <li><a href="/polls/DBList/{{ DB.0 }}/"> {{ DB.0 }} </a></li> {% endfor %} </ul> {% else %} <p>No DB, check SQL function</p> {% endif %} Then the url: url(r'^DBList/$', views.DBList, name='DBList'), Then I created a separate template for the page that I'm trying to show the DBCreationDate: {% if DBList %} <ul> {% for DB in DBList %} <li> {{ DB.1 }} </li> {% endfor %} </ul> {% else %} Then the url: url(r'^DBList/[A-Z0-9]\{6\}$', views.DBList, name='DBDate'), The hyperlink works, but when I click it, I got an error … -
ModelForm to edit a model and its OneToOne-related model
Say I have a User model and an Account model. The Account is related to the User with a OneToOne relationship. I have a ModelForm for the User model, and I'm looking for a third-party plugin / patch / snippet to allow this declaration: class UserEditForm(ModelForm): class Meta: model = User fields = ['first_name', 'last_name', 'email', 'account__phone'] Note the account__phone part. Thanks! -
Django: display object's another field from template tag?
I have objects in my database, each object has two values(fields): 'id' and 'name'. I want to request my model from template tags to display another field of the object, when first one is given. Example. Model: Fruits Objects: Name:Banana ID:1 Name:Apple ID:2 Name:Orange ID:3 How do I make a request from my template tag to ask something like: 'display name of the object with ID=1' or 'display ID of the object named Orange'? -
Object permissions with read only access for anonymous users in Django Rest Framework
The problem I am using Django REST Framework - and so far I have been using the DjangoObjectPermissions permissions class. I use django-rules to determine which users have permissions for objects. However, this permissions class seems to deny read access to anonymous users. I need to find the best way to allow read-only access to all users (authenticated or not). For additions, modifications and deletions - the object permissions should be applied as normal. What is the best approach to solving this problem? Django does not seem to provide a can_view permission by default. Perhaps this will involve manually adding a can_view permission for each model. Or maybe it's better to somehow implement a DjangoObjectPermissionsOrAnonReadOnly permissions class? -
Add multiple instances of ModelForm to single page in Form Wizard
I have a form wizard set up to use multi, and I want to be able to add and remove instances of my ModelForm on the fly to submit and retrieve into the next page as an array in a select box. Pressing Add Another Row calls some javascript, to add a wizard-generated` {{ form }}. I want to retrieve an Array of Task_Forms to populate the select box on the following page: (as you can see, the drop down only contains the task name from the last field, because they are ovverwriting each other down the page.) This is the Tasks template: {% extends 'proposed_project_details/wizard_base.html' %} {% load widget_tweaks %} {% block formpart %} <span class="title" style="font-size: 1.5em;">Name of<span class="highlight">The Project</span></span> <div class="formElems"> {{ form.pro_name|attr:"class:descript"|attr:"rows:5"|attr:"placeholder:Project Name" }} </div> <span class="title" style="font-size: 1.5em;">What are your <span class="highlight">Project Objectives?</span></span> <div class="formElems"> {{ form.pro_objective|attr:"class:descript"|attr:"rows:5"|attr:"placeholder:Project Objectives" }} </div> <span class="title" style="font-size: 1.5em;">What is the <span class="highlight">Background</span> for your project?</span> <div class="formElems"> {{ form.pro_background|attr:"class:descript"|attr:"rows:5"|attr:"placeholder:Project Background" }} </div> {% endblock %} wizard_base.html {% extends 'proposed_project_details/thumbBase.html' %} {% load i18n %} {% load widget_tweaks %} {% block head %} {{ wizard.form.media }} {% endblock %} {% block content %} <p>Step {{ wizard.steps.step1 }} of {{ wizard.steps.count … -
Form input-box not displaying
I'm trying to display a simple form input-text box with Django. I'm am deploying on Amazon AWS. The site works fine on a different server (pythonanywhere) but there is a major problem on AWS. Specifically, the input box is not being displayed. I'm using templates as follows: home.html {% extends 'lists/base.html' %} {% block header_text %}Start a new To-Do list {% endblock %} {% block form_action %}{% url 'new_list' %}{% endblock %} base.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="X UA-Compatible" content="IE-edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>To-Do lists</title> <link href="/static/bootstrap/css/bootstrap.min.css" rel="stylesheet"> <link href="/static/base.css" rel="stylesheet"> </head> <body> <div class="container"> <div class="row"> <div class="col-md-6 col-md-offset-3 jumbotron"> <div class="text-center"> <h1>{% block header_text %}{% endblock %}</h1> <form method="POST" action="{% block form_action %}{% endblock %}"> {{ form.text }} {% csrf_token %} {% if form.errors %} <div class = "form-group has-error"> <span class = "help-block">{{ form.text.errors }}</span> </div> {% endif %} </form> </div> </div> </div> <div class="row"> <div class="col-md-6 col-md-offset-3"> {% block table %} {% endblock %} </div> </div> </div> </body> </html> models.py from django.db import models from django .core.urlresolvers import reverse class List(models.Model): def get_absolute_url(self): return reverse('view_list', args=[self.id]) # Create your models here. class Item(models.Model): text = models.TextField(default = '') list = models.ForeignKey(List, … -
Unable to find/edit ~/.bash_profile in windows machine
I'm following this tutorial (http://www.marinamele.com/taskbuster-django-tutorial/install-and-configure-mysql-for-django#install-mysql) to begin working with MySQL on my django projects. But it asks me to "modify the $PATH so that the mysql command lines are available in your terminal. Edit the ~/.bash_profile file and add the following: export PATH=$PATH:/usr/local/mysql/bin." Is this related to Git Bash by any chance? I use windows (7) and not able to find this ~/.bash_profile file. Where do I look, how do I proceed- I'm stuck at this step!? -
django: RecursionError when initialize a object
SO I am trying to build a simple shopping cart feature for my app, that simply add, remove a piece of equipment, and display a list of current cart. Here are my codes for this cart: (codes largely adopted from https://github.com/bmentges/django-cart) cart.py: import datetime from .models import Cart, Item, ItemManager CART_ID = 'CART-ID' class ItemAlreadyExists(Exception): pass class ItemDoesNotExist(Exception): pass class Cart: def init(self, request, *args, **kwargs): super(Cart, self).init() cart_id = request.session.get(CART_ID) if cart_id: try: cart = models.Cart.objects.get(id=cart_id, checked_out=False) except models.Cart.DoesNotExist: cart = self.new(request) else: cart = self.new(request) self.cart = cart def __iter__(self): for item in self.cart.item_set.all(): yield item def new(self, request): cart = Cart(request, creation_date=datetime.datetime.now()) cart.save() request.session[CART_ID] = cart.id return cart def add(self, equipment): try: item = models.Item.objects.get( cart=self.cart, equipment=equipment, ) except models.Item.DoesNotExist: item = models.Item() item.cart = self.cart item.equipment = equipment item.save() else: #ItemAlreadyExists item.save() def remove(self, equipment): try: item = models.Item.objects.get( cart=self.cart, equipment=equipment, ) except models.Item.DoesNotExist: raise ItemDoesNotExist else: item.delete() def count(self): result = 0 for item in self.cart.item_set.all(): result += 1 * item.quantity return result def clear(self): for item in self.cart.item_set.all(): item.delete() and models.py: class Cart(models.Model): creation_date = models.DateTimeField(verbose_name=_('creation date')) checked_out = models.BooleanField(default=False, verbose_name=_('checked out')) class Meta: verbose_name = _('cart') verbose_name_plural = _('carts') ordering = ('-creation_date',) def … -
Add method doesnt work when trying to establish m2m relationships using post_save in Django
My Content model has a many-to-many relationship to the Tag model. When I save a Content object, I want to add the relationships dynamically. Im doing this the following way. def tag_content(obj): for tag in Tag.objects.all(): print tag obj.tags.add(tag) obj.is_tagged = True obj.save() class Tag(models.Model): name = models.CharField(max_length=255) class Content(models.Model): title = models.CharField(max_length=255) is_tagged = models.BooleanField(default=False) tags = models.ManyToManyField(Tag, blank=True) def save(self, *args, **kwargs): super(Content, self).save(*args, **kwargs) @receiver(post_save, sender = Content) def update_m2m_relationships_on_save(sender, **kwargs): if not kwargs['instance'].is_tagged: tag_content(kwargs['instance']) The tag_content function runs, however, the m2m relationships are not established. Im using Django 1.9.8 btw. This makes no sense. What am I missing? Moreover, if I do something like tag_content(content_instance) in shell, then the tags are set, so the function is ok. I guess the problem is in the receiver. Any help?