Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
get() takes no keyword arguments : Django tutorial with different models
Here is my gambling view in views.py def gambling(request, profile_id): Profile = get_object_or_404(profile, pk=profile_id) coin = get_object_or_404(Coin, pk=profile_id) try: selected_choice = coin.Face.get(pk=request.POST['name']) except (KeyError, Coin.DoesNotExist): # Redisplay the question voting form. return render(request, 'gamble/detail.html', { 'Profile': Profile, 'error_message': "You didn't select a choice.", }) else: selected_choice.Face selected_choice.save() return HttpResponseRedirect(reverse('gamble:results', args=(profile.id,))) Here is the form in detail.html {% if error_message %}<p><strong>{{ error_message }}</strong></p>{% endif %} <form action="{% url 'gamble:gambling' Profile.id %}" method="post"> {% csrf_token %} {% for choice in coin.Face %} <input type="radio" name="choice" id="choice{{ forloop.counter }}" value="{{ choice.id }}" /> <label for="choice{{ forloop.counter }}"> {{ choice }}</label><br /> {% endfor %} <input type="submit" value="flip" /> </form> Here is my code for the Models profile and coin in models.py # Create your models here. class profile(models.Model): name = models.CharField(max_length=120) description = models.TextField(default='description default text') def __unicode__(self): return self.name class Coin(models.Model): #choice = models.ForeignKey(BetAmount, on_delete=models.CASCADE) choice_text = models.CharField(max_length=200, default="...") flip = randint(0,1) Heads =0 Tails =1 Face ={ "Heads": Heads, "Tails": Tails } def __str__(self): return self.choice_text def flipped(self): return self.flip I keep getting the error about .get(), even though I am passing the form name, I am not sure if it has to do with the Coin object itself, clarity on … -
I am working with AuditTrail of django. I am getting the error in a code which i took from djangoproject.com
This is my audit.py file. It is giving error that: AttribueError:cant set attribute on this line: attrs[field.name].rel = rel Please Help The code is directly from official django website. I have not made any changes to it. I am working to setup AuditTrail from django.dispatch import dispatcher from django.db import models from django.core.exceptions import ImproperlyConfigured from django.contrib import admin import copy import re import types try: import settings_audit except ImportError: settings_audit = None value_error_re = re.compile("^.+'(.+)'$") class AuditTrail(object): def __init__(self, show_in_admin=False, save_change_type=True, audit_deletes=True, track_fields=None): self.opts = {} self.opts['show_in_admin'] = show_in_admin self.opts['save_change_type'] = save_change_type self.opts['audit_deletes'] = audit_deletes if track_fields: self.opts['track_fields'] = track_fields else: self.opts['track_fields'] = [] def contribute_to_class(self, cls, name): # This should only get added once the class is otherwise complete def _contribute(sender, **kwargs): model = create_audit_model(sender, **self.opts) if self.opts['show_in_admin']: # Enable admin integration # If ModelAdmin needs options or different base class, find # some way to make the commented code work # cls_admin_name = cls.__name__ + 'Admin' # clsAdmin = type(cls_admin_name, (admin.ModelAdmin,),{}) # admin.site.register(cls, clsAdmin) # Otherwise, register class with default ModelAdmin admin.site.register(model) descriptor = AuditTrailDescriptor(model._default_manager, sender._meta.pk.attname) setattr(sender, name, descriptor) def _audit_track(instance, field_arr, **kwargs): field_name = field_arr[0] try: return getattr(instance, field_name) except: if len(field_arr) > 2: if callable(field_arr[2]): … -
Django CompileError: File to import not found or unreadable: bootstrap-sass/assets/stylesheets/bootstrap/variables
I am currently working on the cadasta - an open source organisation's - Django project. They require you to run their platform in a virtual machine (virtualbox) using vagrant. As I enter their repository, and run their server using ./runserver, I am all of a sudden getting a CompileError which says: File to import not found or unreadable: bootstrap-sass/assets/stylesheets/bootstrap/variables. Parent style sheet: /vagrant/cadasta/core/static/css/_variables.scss. on line 74 of core/static/css/_variables.scss @import "bootstrap-sass/assets/stylesheets/bootstrap/variables"; Following this link: https://github.com/jrief/djangocms-cascade/issues/130, I found that libsass is already installed, and so I tried installing bootstrap-sass inside the VM, but it did no good. Everything was working fine until I renamed the cadasta-platform directory (i.e their github repo that I cloned, and so the main project is included inside this folder only.) and refreshed. I even tried running the server again, but couldn't get through this error. I suppose renaming the directory shouldn't be the cause? Please help. -
Django: create file and download with return results in the same html
I am stuck in a Django process and would like to seek your help. Specifically, I create a function of clicking a button to generate a report from the database in views.py. Then the report will be downloaded. Further to that, I want the html return the download completed message after the work is done. I have tried to used iframe from online resources but it does not work as the message pops before the file is download, instead of after. I am wondering any solution to that. I attach the code as below for your reference. Many thanks! html template: <script> function iframe_creation() { var iframe = $('<iframe name="postiframe" id="postiframe" style="display: none" />'); //remove the previous iframe if more than one click on the submit button $("#"+$(iframe).attr("id")).remove(); //append the iframe to the html page $("body").append(iframe); return iframe; } //post a form via an iframe function post_iframe(iframe, form, link) { var form = $(form); form.attr("action", link); form.attr("method", "post"); form.attr("target", $(iframe).attr("id")); form.submit(); } /* submit the export form, download a file and displays success message */ function download_file(form, link) { //create iframe iframe=iframe_creation(); showspinner() //submit data to iframe post_iframe(iframe, form, link) //display a success message var msg="File successfully sent to download!"; … -
react client side rendering with django
I am integrating reactjs with my django, I have done setup and even able to render page from server too, but in client side when it comes to rendering and event handling and attaching, I am getting error "Uncaught ReferenceError: MainContainer is not defined". I am totally lost here, please help me. <html> <head> <link rel="stylesheet" type="text/css" href="static/src/css/bootstrap.min.css"/> <link rel="stylesheet" type="text/css" href="static/src/css/style.less"/> </head> <body> <script> // var INITIAL_DATA = JSON.parse('{{ serialized_value|safe }}') var INITIAL_DATA = {{ serialized_value|safe }} </script> <div id="app">{{ rendered|safe }}</div> <script type="text/javascript" src="static/build/index_webpack.js"></script> <script> // ReactDOM.render(React.createFactory(MainContainer)({isOpen: false, props: {'freeShipping': free_shipping_message_new,'navigationBar': [loose_leaf_content]}}), document.getElementById('app')); ReactDOM.render(MainContainer({isOpen: false, props: {'freeShipping': free_shipping_message_new,'navigationBar': [loose_leaf_content]}}), document.getElementById('app')); </script> </body> </html> -
foreign key constraint violation with RelatedFactory in django unit tests
I have a OneToOne model which I use with a Factory in unit tests. When tests are executed I get a foreign key constraint violation: IntegrityError: insert or update on table "core_designfeatures" violates foreign key constraint This wasn't a problem in Django 1.9, but I need to upgrade to 1.10 for other reasons. Is there a way I can make this work? I included the relevant snippets below: Django==1.10.5 factory-boy==2.8.1 Faker==0.7.7 Models excerpt: class DesignFeatures(BaseModel): """List of board features""" design = models.OneToOneField( Design, on_delete=models.CASCADE, related_name='features', ) Factories excerpts: class DesignFeaturesFactory(factory.django.DjangoModelFactory): class Meta(object): model = models.DesignFeatures class DesignFactory(factory.django.DjangoModelFactory): class Meta(object): model = models.Design features = factory.RelatedFactory(DesignFeaturesFactory, 'design') Exception on test execution: vi +216 /usr/local/lib/python2.7/site-packages/django/test/testcases.py # __call__ self._post_teardown() vi +908 /usr/local/lib/python2.7/site-packages/django/test/testcases.py # _post_teardown self._fixture_teardown() vi +1064 /usr/local/lib/python2.7/site-packages/django/test/testcases.py # _fixture_teardown connections[db_name].check_constraints() vi +224 /usr/local/lib/python2.7/site-packages/django/db/backends/postgresql/base.py # check_constraints self.cursor().execute('SET CONSTRAINTS ALL IMMEDIATE') vi +112 /usr/local/lib/python2.7/site-packages/raven/contrib/django/client.py # execute return real_execute(self, sql, params) vi +64 /usr/local/lib/python2.7/site-packages/django/db/backends/utils.py # execute return self.cursor.execute(sql, params) vi +94 /usr/local/lib/python2.7/site-packages/django/db/utils.py # __exit__ six.reraise(dj_exc_type, dj_exc_value, traceback) vi +62 /usr/local/lib/python2.7/site-packages/django/db/backends/utils.py # execute return self.cursor.execute(sql) IntegrityError: insert or update on table "core_designfeatures" violates foreign key constraint "core_designfeatures_design_id_3cf84d33_fk_core_design_id" DETAIL: Key (design_id)=(26) is not present in table "core_design". -
Django oauth2app grant_type error
I have created a django app on django with : 'rest_framework', 'oauth2_provider', When I try to access the athorization headers from the following adress: http://localhost:8000/o/token/ posting: UZNlPZzWTGFPltqWt4HBK6rGogZR9j0ZI2llKE5J:SGFjoAgtB3bLZIwr9GlpwXdCbZQbN9JH1TO7Jp3vi0r5McGbXuY9unGikHe9VLr0VUzLAWQhOpUB3jRGj7pvtYpcTJeePkMou4ZWjyvHOgq7SQWDwRpWWQPNMQUJyuJR grant_type:client_credentials username:geethpw password:abcabcabc I always get: {"error": "unsupported_grant_type"}although the grant-type is correct. i read their github repo (https://github.com/hiidef/oauth2app/tree/master/oauth2app) and the following was the function throwing the error (file:tokey.py): def _validate(self): """Validate the request.""" # Check response type if self.grant_type is None: raise InvalidRequest('No grant_type provided.') if self.grant_type not in [ "authorization_code", "refresh_token", "password", "client_credentials"]: raise UnsupportedGrantType('No grant type: %s' % self.grant_type) if self.client_id is None: raise InvalidRequest('No client_id') try: self.client = Client.objects.get(key=self.client_id) except Client.DoesNotExist: raise InvalidClient("client_id %s doesn't exist" % self.client_id) # Scope if self.scope is not None: access_ranges = AccessRange.objects.filter(key__in=self.scope) access_ranges = set(access_ranges.values_list('key', flat=True)) difference = access_ranges.symmetric_difference(self.scope) if len(difference) != 0: raise InvalidScope("Following access ranges doesn't exist: " "%s" % ', '.join(difference)) if self.grant_type == "authorization_code": self._validate_authorization_code() elif self.grant_type == "refresh_token": self._validate_refresh_token() elif self.grant_type == "password": self._validate_password() elif self.grant_type == "client_credentials": self._validate_client_credentials() else: raise UnsupportedGrantType('Unable to validate grant type.') How can i fix this? -
Django mariaDB connection Library not loaded: libssl.1.0.0.dylib
File "/Users/tommy/.pyenv/versions/anaconda3-4.1.0/lib/python3.5/site-packages/django/db/backends/mysql/base.py", line 28, in raise ImproperlyConfigured("Error loading MySQLdb module: %s" % e) django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module: dlopen(/Users/tommy/.pyenv/versions/anaconda3-4.1.0/lib/python3.5/site-packages/_mysql.cpython-35m-darwin.so, 2): Library not loaded: libssl.1.0.0.dylib Referenced from: /Users/tommy/.pyenv/versions/anaconda3-4.1.0/lib/python3.5/site-packages/_mysql.cpython-35m-darwin.so Reason: image not found I think that this problem is "Django couldn't find openssl libaray" what should i do -
DRF Posting Foreign Key UserId
I am using the django rest framework and I have a very simple model of Posts for a particular user which I have serialised in the following manner. Serializers.py class PostSerializer(serializers.HyperlinkedModelSerializer): image = serializers.ImageField(max_length=None, use_url=True) question = serializers.CharField(required=False) ayes = serializers.CharField(required=False) nays = serializers.CharField(required=False) neutrals = serializers.CharField(required=False) class Meta: model = Posts fields = ('user','question', 'image','ayes', 'nays', 'neutrals') My models.py is as follows class Posts(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) created = models.DateTimeField(auto_now_add=True) question = models.TextField(max_length=500, blank=True) image = models.ImageField('optionalImage', upload_to='images/posts/', default='/images/posts/blank.png') ayes = models.TextField(max_length=200, default=0) nays = models.TextField(max_length=200, default=0) neutrals = models.TextField(max_length=200, default=0) When I tried posting to this I kept getting NOT NULL Integrity constraint error of user_id. Hence I added context={'request': request}) to the serializer which ends up giving me the following error: Could not resolve URL for hyperlinked relationship using view name "user-detail". You may have failed to include the related model in your API, or incorrectly configured the lookup_field attribute on this field. My views.py is as follows: views.py @permission_classes((IsAuthenticated, )) class PostsView(generics.ListCreateAPIView): queryset = Posts.objects.all() serializer_class = PostSerializer def get(self, request, format=None): snippets = Posts.objects.filter(pk=request.user.id) serializer = PostSerializer(snippets, many=True,context={'request': request}) return Response(serializer.data) def post(self, request, format=None): posts = PostSerializer(data=request.data,context={'request': request}) if posts.is_valid(): posts.save() return Response("YOLO", … -
DjangoRest - It is possible to define multiple create(self, request) in ModelViewSet
I have a project which need to perform different create processes in the same Model. We can achieved this one by creating multiple ModelViewSet. class AnimalViewSet(viewsets.ModelViewSet): queryset = Animal.objects.all() serializer_class = AnimalSerializer def create(self, request): # just simply create the object... pass Endpoint is POST /api/animal/ class CalvingViewSet(viewsets.ModelViewSet): # This is called when an animal has successfully delivered its new born.. queryset = Animal.objects.all() serializer_class = AnimalSerializer def create(self, request): # create the object.. # define parent animals pregnancy as success # and more.. pass Endpoint is POST /api/calving/ But i prefer not doing so. Now it is possible to define multiple create(self, request) in a single ModelViewSet? class AnimalViewSet(viewsets.ModelViewSet): queryset = Animal.objects.all() serializer_class = AnimalSerializer def create(self, request): # just simply create the object... pass def calving(self, request): # create the object.. # define parent animals pregnancy as success # and more.. pass Endpoint for create(self, request): is POST /api/animal/ the is problem is i don't have any idea about the endpoint of calving(self, request): I also found @list_route(methods=['post']) may help but i want to make sure there is another right way to do this. -
How do I correctly serve static files with django+nginx in separate docker containers?
I always struggle with this, probably because with most projects I only have to deal with static settings initially and then never touch them again. docker-compose snippet parentserver: container_name: parentserver restart: always build: ./parentserver expose: - "8000" links: - postgres:postgres - authserver:authserver volumes: - /usr/src/app - /usr/src/app/static env_file: .env environment: DEBUG: 'true' command: ./startup.sh nginx: container_name: nginx restart: always build: ./nginx/ ports: - "80:80" volumes: - /www/static volumes_from: - parentserver links: - parentserver:parentserver sites-enabled/django_site server { listen 80; server_name example.org; charset utf-8 location /static { alias /root/cannablr/cannablr/static; } location / { proxy_pass http://parentserver:8000; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; } } Django settings.py STATIC_ROOT = os.path.join(PACKAGE_ROOT, "static1") STATIC_URL = "/static/" STATICFILES_DIRS = [ os.path.join(PACKAGE_ROOT, "static"), ] Not sure if related but I don't entirely understand the use of volumes: /www/static in my docker-compose, do I need this? Any help would be appreciated, right now my site is being served by nginx but missing all css, images, etc. -
Should I use slug field too in django
I am developing an blog like application where there are going to be posts with similar or sometimes same titles. Also users are able to edit the titles of their post whenever they want. Currently my urls look like this. <a href="{% url 'myapp:read' post.id %}">{{post.title}} </a> Now I've read few answers where along with id they have passed slug too like url of this question. Even with id the url is going to be unique, right? then why slug? and if it is for humanizing the url then should be store it too? So to summarize: If id is unique then why slug? If its important then should we store it? If it has anything to do with canonical-link please elaborate the working of canonical links & how slug can help it? or at least direct me to the source. Reference: when to store slugfield in database in django? and this answer Thanks in advance. -
OSError: No translation files found for default language zh_Hans
django: 1.10.3 local: windows server: debian local can run normally, can not runing in my server, but can runing by en-us, why, i can't runing by zh_hans ? Traceback: ...File "/home/a/ENV/lib/python3.5/site-packages/django/utils/translation/__init__.py", line 85, in ugettext return _trans.ugettext(message) File "/home/a/ENV/lib/python3.5/site-packages/django/utils/translation/trans_real.py", line 337, in gettext return do_translate(message, 'gettext') File "/home/a/ENV/lib/python3.5/site-packages/django/utils/translation/trans_real.py", line 320, in do_translate _default = _default or translation(settings.LANGUAGE_CODE) File "/home/a/ENV/lib/python3.5/site-packages/django/utils/translation/trans_real.py", line 227, in translation _translations[language] = DjangoTranslation(language) File "/home/a/ENV/lib/python3.5/site-packages/django/utils/translation/trans_real.py", line 134, in __init__ raise IOError("No translation files found for default language %s." % settings.LANGUAGE_CODE) OSError: No translation files found for default language zh_Hans. -
can't get rid of gap between header and body
I have tried everything from editing padding/margins to saving file as utf-8 without BOM in notepad suggested in other posts to get his gap to go away. Nothing is seems to work so I come to ask for help. I am developing this webpage using python/django framework in which my base.html file looks like this {% load bootstrap3 %} <!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>Michael Goytia</title> {% bootstrap_css %} {% bootstrap_javascript %} </head> <body> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css"> <!-- Static navbar --> <nav class="navbar navbar-custom navbar-static-top"> <div class="container"> <div class="navbar-header"> <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar"> <!-- put three little bars in toggle button--> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a class="navbar-brand" href="{% url 'personal_info:index' %}"style="color:#6C9F9F"><i class="fa fa-user-secret"></i> <b>Michael Goytia</b></a> </div> <div id="navbar" class="navbar-collapse collapse"> <ul class="nav navbar-nav"> <li><a href="{% url 'personal_info:about_me' %}"style="color:#6C9F9F"><i class="fa fa-user-circle-o"></i> <b>About Me</b></a> </li> <li><a href="{% url 'personal_info:projects' %}"style="color:#6C9F9F"><i class="fa fa-paper-plane"></i> <b>Projects</b></a> </li> <li><a href="{% url 'personal_info:contact' %}"style="color:#6C9F9F"><i class="fa fa-address-book"></i> <b>Contact Information</b></a> </li> </ul> </div><!--/.nav-collaspse --> </div> </nav> <div class="container"> <div class="page-header"> {% block header %}{% endblock header %} </div> <div> {% block content %}{% endblock content %} </div> </div><!-- /container --> <!-- Place this … -
Duplicate Form Field Input Django
So lets say I have two fields called Member1 and Member2 and both these fields belong in the same Class or table. A user will input values into these two fields via a ModelForm. How can I ensure that these two fields are not duplicates of each other. Here is my current validation code: def clean(self): member1 = User.objects.filter(username__iexact=self.Member1.lower()) member2 = User.objects.filter(username__iexact=self.Member2.lower()) if member2 == member3: raise ValidationError("Can't have duplicate team members") But it is not working, Any ideas? -
When doing a POST request on a model from a form it doesn't assign an ID to the object
When I add a post from admin it assigns the ID and I can link to the post. I get no errors when I go to that address. But if I create a post form it doesn't seem like I am getting an ID. I get an error that says there is no matching query. I thought the ID was automatically assigned. Environment: Request Method: GET Request URL: http://127.0.0.1:8000/reports/5/this-is-even-more-formal/ Django Version: 1.10.5 Python Version: 3.6.0 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.humanize', 'TheFishNetwork', 'accounts', 'subnetwork', 'posts'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback: File "/home/swapnil/python_envs/fishenv/lib/python3.6/site-packages/django/core/handlers/exception.py" in inner 39. response = get_response(request) File "/home/swapnil/python_envs/fishenv/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response 187. response = self.process_exception_by_middleware(e, request) File "/home/swapnil/python_envs/fishenv/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response 185. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/swapnil/PycharmProjects/fishnetwork/posts/views.py" in report_detail 38. user = User.objects.get(id=pk) File "/home/swapnil/python_envs/fishenv/lib/python3.6/site-packages/django/db/models/manager.py" in manager_method 85. return getattr(self.get_queryset(), name)(*args, **kwargs) File "/home/swapnil/python_envs/fishenv/lib/python3.6/site-packages/django/db/models/query.py" in get 385. self.model._meta.object_name Exception Type: DoesNotExist at /reports/5/this-is-even-more-formal/ Exception Value: User matching query does not exist. views.py @login_required def create_report(request): if request.method == "POST": if request.POST['title'] and request.POST['body']: report = FishingReport() report.title = request.POST['title'] report.slug = slugify(report.title) report.body = request.POST['body'] report.sub_network = SubNetwork.objects.get(sub_name=request.POST['sub']) report.pub_date = timezone.datetime.now() report.author = request.user report.save() return render(request, 'posts/createreport.html') else: subnetwork … -
Deploy django cookiecutter template on Heroku
I am trying to deploy a web on Heroku. When I run heroku run python manage.py migrate I will get some errors: django.core.exceptions.ImproperlyConfigured: Set the DJANGO_SENTRY_DSN environment variable I read the documentation on Cookiecutter, the document said I have to specify these values. But it didn't tell me what's the purpose and the method. I am wondering do I really have to specify all this values? DJANGO_AWS_ACCESS_KEY_ID DJANGO_AWS_SECRET_ACCESS_KEY DJANGO_AWS_STORAGE_BUCKET_NAME DJANGO_SENTRY_DSN DJANGO_SENTRY_CLIENT DJANGO_SENTRY_LOG_LEVEL DJANGO_MAILGUN_API_KEY DJANGO_MAILGUN_SERVER_NAME Logs: $ heroku logs --app glacial-forest-93266 --dyno run.9155 2017-02-23T03:28:44.634830+00:00 heroku[run.9155]: Starting process with command `python manage.py migrate` 2017-02-23T03:28:45.292164+00:00 heroku[run.9155]: State changed from starting to up 2017-02-23T03:28:47.487454+00:00 heroku[run.9155]: Process exited with status 1 2017-02-23T03:28:47.336279+00:00 app[run.9155]: /app/.heroku/python/lib/python3.5/site-packages/environ/environ.py:608: UserWarning: /app/co nfig/settings/.env doesn't exist - if you're not configuring your environment separately, create one. 2017-02-23T03:28:47.359554+00:00 app[run.9155]: Traceback (most recent call last): 2017-02-23T03:28:47.359557+00:00 app[run.9155]: File "/app/.heroku/python/lib/python3.5/site-packages/environ/environ.py", line 264, in ge t_value 2017-02-23T03:28:47.336297+00:00 app[run.9155]: "environment separately, create one." % env_file) 2017-02-23T03:28:47.359787+00:00 app[run.9155]: value = self.ENVIRON[var] 2017-02-23T03:28:47.359791+00:00 app[run.9155]: File "/app/.heroku/python/lib/python3.5/os.py", line 683, in __getitem__ 2017-02-23T03:28:47.360099+00:00 app[run.9155]: raise KeyError(key) from None 2017-02-23T03:28:47.360103+00:00 app[run.9155]: KeyError: 'DJANGO_SENTRY_DSN' 2017-02-23T03:28:47.360105+00:00 app[run.9155]: 2017-02-23T03:28:47.360106+00:00 app[run.9155]: During handling of the above exception, another exception occurred: 2017-02-23T03:28:47.360107+00:00 app[run.9155]: 2017-02-23T03:28:47.360109+00:00 app[run.9155]: Traceback (most recent call last): 2017-02-23T03:28:47.360130+00:00 app[run.9155]: File "manage.py", line 23, in … -
Get JSON's attribute value in Chatterbot and Django integration
statement.text in chatterbot and Django integration returns {'text': u'How are you doing?', 'created_at': datetime.datetime(2017, 2, 20, 7, 37, 30, 746345, tzinfo=<UTC>), 'extra_data': {}, 'in_response_to': [{'text': u'Hi', 'occurrence': 3}]} I want a value of text attribute so that it prints How are you doing? -
How to Stay DRY in Django
I have a Django url for users to change their password, which looks like this: url(r'^change-password$', views.user_change_password, name='change_password'), url(r'^change-password/done/$', views.user_changed_password, name='password_changed') Where views.user_change_password is: def user_change_password(request): response = password_change(request, template_name=r"Foo/Account/change_password.html", post_change_redirect=reverse('Foo:password_changed')) return response This works, but it seems to me that having to specify the lookup name password_changed in two separate places violates the principle of DRY. Is there a standard way in Django of dealing with this? -
couldn't import django in virtualenv but works when deactivated
I am trying to deploy my Django Projects on Amazon AWS using Ubuntu 16.04. I am running python version 2.7.12 and Django 1.10.5. I created my virtualenv named venv and then activated it. I get this error when I try to run python manage.py runserver. Traceback (most recent call last): File "manage.py", line 17, in "Couldn't import Django. Are you sure it's installed and " ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment? Then I realize Django might not be in my python path. So I added export PYTHONPATH="/usr/local/lib/python2.7/dist-packages/django" into my venv/bin/activate script. Now with the virtualenv activated I can go into python and type import sys sys.path ['', '/usr/local/lib/python2.7/dist-packages/django', '/home/ubuntu/TravelBuddy/venv/lib/python2.7', '/home/ubuntu/TravelBuddy/venv/lib/python2.7/plat-x86_64-linux-gnu', '/home/ubuntu/TravelBuddy/venv/lib/python2.7/lib-tk', '/home/ubuntu/TravelBuddy/venv/lib/python2.7/lib-old', '/home/ubuntu/TravelBuddy/venv/lib/python2.7/lib-dynload', '/usr/lib/python2.7', '/usr/lib/python2.7/plat-x86_64-linux-gnu', '/usr/lib/python2.7/lib-tk', '/home/ubuntu/TravelBuddy/venv/local/lib/python2.7/site-packages', '/home/ubuntu/TravelBuddy/venv/lib/python2.7/site-packages'] As you can see now django is indeed in my python path. I thought this was going to fix the problem but it didn't: it still says couldn't import Django. Now I am confused because when I deactivate my virtualenv and import Django it does work. this is what prints out when I deactivate my virtualenv and do sys.path ['', '/usr/local/lib/python2.7/dist-packages/django', '/usr/lib/python2.7', '/usr/lib/python2.7/plat-x86_64-linux-gnu', '/usr/lib/python2.7/lib-tk', … -
How to remove {'field__avg': when printing avg in Django templates
This should be a pretty simple question, but googling for it has been difficult. I'm trying to average a field in Django, and I've got that all figured out, but when I print it in my template, I get this annoying "{'field__avg':" printing along with the actual value. How do I remove that and only print the actual value? Alternatively, how do I call that value so that I can use it in some logic? -
PicklingError when trying to access user ID in Django form
This is a strange one. In a Django-based web application I've made, users chat in a public room, or can create private rooms with friends. All unseen messages aggregate in a separate section called unseen activity. When cleaning the submitted data for UnseenActivityForm, I need to run some validation for the specific user as well (thus I need the user_id in my form). To do this, I pass it like so (via a function-based view): if request.method == 'POST': form = UnseenActivityForm(request.POST,request=request) And in the form, I included: class UnseenActivityForm(forms.Form): comment = forms.CharField(max_length=250) group_reply = forms.CharField(max_length=500) class Meta: fields = ("comment", "group_reply", ) def __init__(self,*args,**kwargs): self.request = kwargs.pop('request', None) super(UnseenActivityForm, self).__init__(*args, **kwargs) Later while cleaning data, I do: def clean_comment(self): comment = self.cleaned_data.get("comment") if not can_reply(comment,self.request.user.id): raise forms.ValidationError('tip: write something different') return comment My problem is I get Can't pickle <type 'function'>: attribute lookup __builtin__.function failed if I try to submit a comment in the aforementioned setup. Highly peculiarly, I don't get this error if I remove request=request from my view, i.e. if I do: if request.method == 'POST': form = UnseenActivityForm(request.POST) But then of course, I can't access self.request.user.id for form validation. Why is this error happening, and what … -
model design for moving device to label
I am trying to add gmail feature of moving the mail to custom created label or already made label. It is a move to label feature. When you select the mail and then click on move to label actions, you will see lots of pre-defined label name such as important, sms, personal, work etc and also a create a new label in the dropdown. For having such feature, have i missed something important here ? Here is my model class Device(BaseDevice): """ This stores Device """ # Description is optional (can be blank, can be null) description = models.TextField(blank=True, null=True) created_on = models.DateTimeField(auto_now_add=True) updated_on= models.DateTimeField(auto_now=True) def __str__(self): return self.name class Label(models.Model): """ This creates a label """ # Name is required name = models.CharField(max_length=250, blank=False, null=False) device = models.ForeignKey(Device, related_name='label') -
Query Django ParentalKey of ForeignKey
I have a SectionMeta model that has ParentalKey relationship to a Section model that has a ForeignKey relationship to my Product model. The way it works is we have multiple sections of a menu, I.e. salads, pizza, pastas etc... and each section as meta data that can go with it, I.e "Add $3 for chicken, 2 for etc.." and that Section is a Foreign Key to the Product itself. I would have placed the SectionMeta as part of the Section, but the Section could belong to multiple menus I.e. Lunch, Dinner, Special etc... This isn't important, but I needed to mention it because it would have been the obvious thing to do. I need to print the SectionMeta on my template if one exists. This is the target template output Salads (FK-Section)(add chicken $3) <=SectionMeta Cobb (product.name) Ceasar (product.name) Pizza (FK-Section)(1/2 off during lunch) <=SectionMeta Supreme (product.name) Veggie (product.name) ... Section Model @register_snippet class Section(ClusterableModel): name = models.CharField(max_length=255, verbose_name='Section') panels = [ MultiFieldPanel( [ InlinePanel('section_meta', label='Section Meta'), ], heading='Section Meta', classname='collapsible' ), ] ... SectionMeta model class SectionMeta(models.Model): description = models.TextField(verbose_name='Section Meta', blank=True, help_text='OPTIONAL: This is an Optional description that displays aside the Section Title.') ... class SectionSectionMeta(Orderable, SectionMeta): page … -
Django templates json loops
I use python/django views to get an output as: {{ test }} in my template. Here is the output {'platform': 'xbox', 'amount': '50.00', 'title': 'title of something', 'description': 'description of something'} If I use {% for x in test %} {{ x }} {% endfor %} it outputs platform, amount, title, description How do I get the values and not the keys?