Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Class Based View acces a variable set in get_context in the get_queryset method
If I have a variable I set in the get_context_data function, is there a way to access that variable in the get_queryset function? def get_context_data(self, **kwargs): coindex_btc_price = requests.get("http://api.coindesk.com/v1/bpi/currentprice.json") def get_queryset(self, **kwargs): coindex_btc_price = requests.get("http://api.coindesk.com/v1/bpi/currentprice.json") I don't want to set it two times like that. -
Django CreateView with two forms at same page
I'm using Django and trying to display the detail of the person who has posted the data. So basically showing the username of the person who has posted the 'thing' defined in models.py In views.py I'm trying: def thing_detail_view(request, pk): thing_detail = Thing.objects.get(pk=pk) user = User.objects.get(request.user) return render(request, 'thing_detail.html', {'thing_detail': thing_detail, 'user': user}) Im getting error: 'User' object is not iterable But I know I should not use request.user because thats basically means the user who is having current session or currently logged in. Any idea how can I get the username of the user who has posted the data of a particular 'pk' and show it in the html? -
Graphene Django and react-router-relay
I'm having real trouble figuring out the way that Graphene Django should be used with react-router-relay. Let's say I can use the following GraphQL query fine via the GraphiQL console on my Django server: query { allThreads { edges { node { id } } } } This is presumably Graphene's alternative to the commmon viewer wrapper used because Relay doesn't support connections on root queries. So I understand that allThreads is really a node (of type ThreadNodeConnection), and has an edges connections that I can query. The trouble is I can't figure out how to use this with Relay, and specifically react-router-relay. I have a React view with a fragment on it like this (with a child Thread component elsewhere): fragments: { store: () => Relay.QL` fragment on Query { allThreads (first:300) { edges { node { // child's fragment included here } }, } } `, }, Webpack checks this against my live schema and likes it. Then I create the following in my index.js for router: const ViewerQueries = { store: () => Relay.QL`query { allThreads(first:300) }` }; ReactDOM.render( <Router forceFetch environment={Relay.Store} render={applyRouterMiddleware(useRelay)} history={browserHistory} > <Route path='/' component={ThreadList} queries={ViewerQueries} /> </Router> , document.getElementById('container') ) Already I'm feeling … -
Django postman setup
I'm having trouble setting up the postman module in my django project. I am in a conda environment. I have installed the package using the instructions found here: https://anaconda.org/pypi/django-postman (pip install basically...) I first tried to run a conda install but that returns with an error saying no package found. I then included 'postman' in my installed apps. When I run my project I get the error 'no module named postman'. Any ideas on what is going wrong? -
I have to use replica of AWS RDS, How should I set the django setting?
My django application have to read rds(maridadb) a lot. So I thought How I solve this performance problem. RDS has replica. I want to set django that use multi db. So I googled about django setting that use replica. There are nowhere. If you know about django setting with replica. Could you share me the information, please? -
Django go return all objects whoes latest state is false
I have two models: Camera and TimeStamp. Timestamp has a foreign key to Camera, a timestamp, and a current state. I want to return all Cameras whos latest state is false. 'faulty': Camera.objects.filter(timestamp__state=False) This returns all camera who have ever had a timestamp that is false. But I just want the cameras who's most recent timestamp_state is false. -
Having a hard time importing mySQL data to Django
I have a .sql file that I want to import into django (or atleast the insert statements). I've been having a hard time trying to find out how to do this. There is about 50,000 entries in 4 insert statements in the form of: INSERT INTO `tweets` VALUES (..........), (........), ... , (......). I've been trying to understand fixtures and I'm not sure if its want I want, and if it is how to use it. EDIT: Forgot to mention, I've also got Django set up for a sqlite3 database because its been giving me a huge pain to change to mysql (perhaps because im using the windows linux subsystem?) so not sure if this makes a difference on inserting. -
PyCharm professional edition cannot support Django
I have PyCharm professional edition, and I have been trying to PyCharm and Django. However, it seems that I could not enable Django support in PyCharm. As shown in the following figure, when I try to enable Django support in the PyCharm setting, there is nothing shown for Django. Can anyone help me identify the issue? -
Django + Heroku + S3: boto -> local variable "region_name" referenced before assignment
I'm getting a very strange error that got me really stuck for many hours now. I did my deploy with Heroku for the first time and am using S3 for Media files. First thing I noticed was that I never had a migration working successfully after installing boto and django-storages-redux, not sure why. Anyway I kept going. My configurations seemed to be working in AWS, since my staticfiles did go to my bucket the first time I tried it, but I got some img files not coming through, so I decided to reinstall boto and django-registration-redux (to see if it would migrate properly). In the end it never migrated as expected and now I'm getting the following error: UnboundLocalError: local variable 'region_name' referenced before assignment in my BOTO package when collectstatic. I don't understand why migrate won't work and why I started to get this error when I re-installed boto and django-storages-redux. terminal: You have requested to collect static files at the destination location as specified in your settings. This will overwrite existing files! Are you sure you want to do this? Type 'yes' to continue, or 'no' to cancel: yes Traceback (most recent call last): File "/Users/Alex/Desktop/Allugare/src/manage.py", line 22, … -
Django template not retrieving recent datachanges in DB
I have two apps for my website, and they both use the same User model. However, when I create or delete a user through the admin panel, when I refresh the template, the page doesnt seem to get that actual data (I test it with this code: var info_user= [{%for User in everything %} '{{ User.username}}. {{ User.town}}. {% endfor %} ]; console.log(info_user); whereas when I restart the server it works. How can this be done without restarting the server? -
How to combine two models and make only one form in admin section?
I have two models Products and ProductImages. But i have to submit those differently from admin section. Is there is any option to combine all the fields of two models in a single form in admin. i have one to many relationship between products and images. class Products(models.Model): product_name = models.CharField(max_length = 50) sku = models.CharField(max_length = 50) details = models.TextField(null = True) price = models.FloatField(default='0.00') created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __unicode__(self): return '%s %s' % (self.product_name, self.sku) class ProductImages(models.Model): product = models.ForeignKey('Products', on_delete=models.CASCADE) images = models.ImageField(upload_to = 'images/product_images/', default = '') created_date = models.DateTimeField(auto_now_add=True)`enter code here` updated_date = models.DateTimeField(auto_now=True) -
TypeError: "ModelBase is not iterable"
I'm working on a small project to practice Django REST Framework (and later a React front-end) before applying the skills I learn to a much larger corporate project. The project is a back-end API that will allow for someone to see what potential crimes and torts a main character has committed in each episode of It's Always Sunny in Philadelphia. To this end, I've made this GitHub repository and put a Django project in it. I find myself getting an error in the browser debug view that I'm not quite able to figure out when I add a new model/serializer/view for the site: Environment: Request Method: GET Request URL: http://127.0.0.1:8000/characters/ Django Version: 1.10.6 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', 'rest_framework', 'offense_api.apps.OffenseApiConfig'] 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 "/Users/person/.virtualenvs/IASIP/lib/python3.6/site-packages/django/core/handlers/exception.py" in inner 42. response = get_response(request) File "/Users/person/.virtualenvs/IASIP/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response 187. response = self.process_exception_by_middleware(e, request) File "/Users/person/.virtualenvs/IASIP/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response 185. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Users/person/.virtualenvs/IASIP/lib/python3.6/site-packages/django/views/decorators/csrf.py" in wrapped_view 58. return view_func(*args, **kwargs) File "/Users/person/Workspace/IASIP_API/offense_api/views.py" in character_list 70. return JsonResponse(serializer.data, safe=False) File "/Users/person/.virtualenvs/IASIP/lib/python3.6/site-packages/rest_framework/serializers.py" in data 729. ret = super(ListSerializer, self).data File "/Users/person/.virtualenvs/IASIP/lib/python3.6/site-packages/rest_framework/serializers.py" in data 262. self._data = self.to_representation(self.instance) File "/Users/person/.virtualenvs/IASIP/lib/python3.6/site-packages/rest_framework/serializers.py" in to_representation … -
UWSGI + nginx repeated logging in django
I am having some weird issues when I run my application on a dev. server using UWSGI+nginx.. It works fine when my request completes within 5-6 mins.. For long deployments and requests taking longer than that, the UWSGI logs repeats the logs after around 5mins.. It's as if it spawns another process and I get two kinds of logs(one for current process and the repeated process). I am not sure why this is happening.. Did not find anything online. I am sure this is not related to my code because the same thing works perfectly fine in the lab env.. where I use the django runserver. Any insight would be appreciated.. -
How to add custom user model in admin panel?
I created a custom user model extending AbstractBaseUser class. code is below. class UserModel(AbstractBaseUser): sys_id = models.AutoField(primary_key=True, blank=True) name = models.CharField(max_length=127, null=False, blank=False) email = models.EmailField(max_length=127, unique=True, null=False, blank=False) mobile = models.CharField(max_length=10, unique=True, null=False, blank=False) user_type = models.PositiveSmallIntegerField(choices=user_type_choices, null=False, blank=True, help_text="Admin(1)/Institute(2)/Student(3)") access_valid_start = models.DateTimeField(null=True, blank=True) access_valid_end = models.DateTimeField(null=True, blank=True) created_when = models.DateTimeField(null=True, blank=True ) created_by = models.BigIntegerField(null=True, blank=True) last_updated_when = models.DateTimeField(null=True, blank=True) last_updated_by = models.BigIntegerField(null=True, blank=True) notes = models.CharField(max_length=2048, null=True, blank=True) is_active = models.BooleanField(default=True) # this field is required to login super user from admin panel is_staff = models.BooleanField(default=True) # this field is required to login super user from admin panel is_superuser = models.BooleanField(default=False) objects = MyUserManager() USERNAME_FIELD = "email" # REQUIRED_FIELDS must contain all required fields on your User model, # but should not contain the USERNAME_FIELD or password as these fields will always be prompted for. REQUIRED_FIELDS = ['name', 'mobile', 'user_type'] class Meta: app_label = "accounts" db_table = "users" def __str__(self): return self.email def get_full_name(self): return self.name def get_short_name(self): return self.name # this methods are require to login super user from admin panel def has_perm(self, perm, obj=None): return self.is_superuser # this methods are require to login super user from admin panel def has_module_perms(self, app_label): return self.is_superuser Now in … -
What is the hostname in a http request sent be an iPhone?
I am really new to building rest APIs. I have just recently built one using django and wanted to find out a little more about the security side of it. So, one thing that I wanted to understand is what exactly is a host and who will be the host for a request sent via a phone? Will allowed_hosts be ['*'] or can i restrict it to just phone devices? I would also appreciate django-specific security concerns that I should keep in mind before going to the market (I am new to this stuff so even if you could just mention some basic security stuff, it would be great). -
Django in Google Cloud App Engine: ImportError: No module named 'src'
I'm trying to deploy my Django 1.10 app in Google Cloud App Engine flexible environment but i'am having the following error: ImportError: No module named src I'm following the official tutorial, located in: https://cloud.google.com/python/django/flexible-environment The error is generated when I run the following command: gcloud app deploy after a while, the console showme this error: ERROR: (gcloud.app.deploy) Error Response: [9] Application startup error: [1] [INFO] Starting gunicorn 19.7.1 [1] [INFO] Listening at: http://0.0.0.0:8080 (1) [1] [INFO] Using worker: sync [9] [INFO] Booting worker with pid: 9 [9] [ERROR] Exception in worker process Traceback (most recent call last): File "/usr/lib/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) ImportError: No module named src.settings [9] [INFO] Worker exiting (pid: 9) [1] [INFO] Shutting down: Master [1] [INFO] Reason: Worker failed to boot. This is my app.yaml config: # [START runtime] runtime: python env: flex entrypoint: gunicorn -b :$PORT core.wsgi beta_settings: cloud_sql_instances: nazkter-zed:us-central1:nazkter-zed runtime_config: python_version: 3 # [END runtime] and this is my proyect structure: - core/ -- app.yaml -- requeriments.txt -- manage.py -- core/ --- __init__.py --- settings.py --- wsgi.py --- urls.py -- app1/ --- __init__.py --- admin.py --- apps.py --- models.py --- views.py --- urls.py I'm been arround this error all day and I … -
Django set autofield value in bulk_create
I'm trying to bulk_create a lot of records in a new table in my PostgresQL db. The primary key on the table is an AutoField called id. As of Django 1.10 (which I'm using), this should work in Postgres: https://docs.djangoproject.com/en/1.10/ref/models/querysets/#bulk-create However, the bulk_create is failing with the following error. django.db.utils.IntegrityError: null value in column "id" violates not-null constraint Which suggests that the id field isn't automatically assigned a value. Does anyone know how to resolve this? -
How to display image? Django
I've tried inserting "static" in the tag but doesnt return the image. Rather it returns a white box. Users are able to upload their own pictures. The directory where this is stored is Aviation -> Uploads -> Aircraft. Where exactly am I going wrong? list.html <div class="box"><img src="{{ aircraft.image }}" /> Settings. py STATIC_URL = '/static/' STATICFILES_DIRS = [ map_path('static'),] MEDIA_ROOT = os.path.join(BASE_DIR,'media') MEDIA_URL = '/media/' View.py def list_aircraft(request): aircraft = Aircraft.objects.all() favorited_aircraft_ids = None if request.user.is_authenticated(): favorited_aircraft_ids = list(FavoritedAircraft.objects.filter(user__id=request.user.id).values_list('id', flat=True)) print (favorited_aircraft_ids) return render(request, 'aircraft/aircraft_list.html', { 'aircraft': aircraft, 'favorited_aircraft_ids': favorited_aircraft_ids, }) -
How can I convert JSON into Python dictionary and list? [duplicate]
This question already has an answer here: Reading JSON from a file? 4 answers I have below structure of JSON and I want to parse it from JSON to dictionary and list so that I can iterate through for loop. My JSON is: {'cart': [{'item_id': '101', 'quantity': '2'}, {'item_id': '102', 'quantity': '1'}, {'item_id': '103', 'quantity': '4'}]} So here after parsing it, I want a dictionary with single key "cart" containing value as list for its corresponding value. Then again when I parse the list, then I should be able to get multiple dictionaries for every item (which have 2 fields item_id and quantity). -
Django, extract value from formset
I have overridden save_formset method to extract data from admin page. Here is how my code looks like, def save_formset(self, request, form, formset, change): for f in formset: print('Voter address is: ', f['voter_address'] ) super().save_formset(request,form, formset, change) I get output as Voter address is: Voter address is: But I want to extract actual value which is "klncklas," and for second one I would like to know that there is no value present. How I can achieve this? -
How to update data from DB without rerunning the server? (Django)
so I have multiple apps for my website; one to register, one to view a map with the users locations plotted on, and one to view the users' profiles. But those three apps need access to the same model, namely: User. (On the register page it gets created and added to DB, the map page needs its hometown in order to locate it on the map, and the profile pages also need it obviously). But whenever I add a new user on the admin page, I first have to rerun the server in order for it to appear on the map. Beforehand when the model was defined in just one app, I just needed to refresh the page to see the change. I have created the User model in the Register app and redirected to it in other apps like this: class Meta(models.Model): db_table = 'register_User' I hope u can help out -
Django TemplateSyntaxError
Currently working through an online tutorial and running into a TemplateSyntaxError: Could not parse the remainder: '“personal/header.html”' from '“personal/header.html”' My files can be found below. This is my first post to StackOverflow so please let me know if there's additional information I should include to make things more clear in the future. header.html file <!DOCTYPE html> <html lang="en"> <head> <title>Jamie Smith</title> <meta charset="utf-8" /> </head> <body class="body" style="background-color:#f6f6f6"> <div> {% block content %} {% endblock %} </div> </body> </html> home.html file {% extends “personal/header.html” %} {% block content %} <p>Hey, welcome to my website! I am a wannabe programmer!</p> {% endblock %} Template Error Template error: In template /Users/jamie/Desktop/Django Tutorials/mysite/personal/templates/personal/home.html, error at line 16 Could not parse the remainder: '“personal/header.html”' from '“personal/header.html”' 6 : <title></title> 7 : <meta name="Generator" content="Cocoa HTML Writer"> 8 : <meta name="CocoaVersion" content="1504.81"> 9 : <style type="text/css"> 10 : p.p1 {margin: 0.0px 0.0px 0.0px 0.0px; line-height: 17.0px; font: 15.0px Courier; color: #660066; -webkit-text-stroke: #660066} 11 : p.p2 {margin: 0.0px 0.0px 0.0px 0.0px; line-height: 17.0px; font: 15.0px Courier; color: #000000; -webkit-text-stroke: #000000} 12 : span.s1 {font-kerning: none} 13 : </style> 14 : </head> 15 : <body> *16 : <p class="p1"><span class="s1"> {% extends “personal/header.html” %} </span></p>* 17 … -
How to combine django "prefetch_related" and "values" methods?
How can "prefetch_related" and "values" method be applied in a combination ? Previously, I had the following code. Limiting fields in this query is required for performance optimization. Organizations.objects.values('id','name').order_by('name') Now, I need to prefetch its association and append it in the serializer using "prefetch_related" method. Organizations.objects.prefetch_related('locations').order_by('name') Here, I cannot seem to find a way to limit the fields after using "prefetch_related". I have tried the following, but on doing so serializer does not see the associated "locations". Organizations.objects.prefetch_related('locations').values("id", "name").order_by('name') Model Skeleton: class Organizations(models.Model): name = models.CharField(max_length=40) class Location(models.Model): name = models.CharField(max_length=50) organization = models.ForeignKey(Organizations, to_field="name", db_column="organization_name", related_name='locations') class Meta: db_table = u'locations' -
Unable to use custom authentication backend in Django
I created a custom user model using AbstractBaseUser class. Code for the same is here. class UserModel(AbstractBaseUser): user_type_choices = ( (constants.USER_TYPE_ADMIN, 'Admin'), (constants.USER_TYPE_INSTITUTE, 'Institute'), (constants.USER_TYPE_STUDENT, 'Student') ) sys_id = models.AutoField(primary_key=True, blank=True) name = models.CharField(max_length=127, null=False, blank=False) email = models.EmailField(max_length=127, unique=True, null=False, blank=False) mobile = models.CharField(max_length=10, unique=True, null=False, blank=False) user_type = models.PositiveSmallIntegerField(choices=user_type_choices, null=False, blank=True, help_text="Admin(1)/Institute(2)/Student(3)") access_valid_start = models.DateTimeField(null=True, blank=True) access_valid_end = models.DateTimeField(null=True, blank=True) created_when = models.DateTimeField(null=True, blank=True ) created_by = models.BigIntegerField(null=True, blank=True) last_updated_when = models.DateTimeField(null=True, blank=True) last_updated_by = models.BigIntegerField(null=True, blank=True) notes = models.CharField(max_length=2048, null=True, blank=True) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=True) objects = MyUserManager() USERNAME_FIELD = "email" # REQUIRED_FIELDS must contain all required fields on your User model, # but should not contain the USERNAME_FIELD or password as these fields will always be prompted for. REQUIRED_FIELDS = ['name', 'mobile', 'user_type'] class Meta: app_label = "accounts" db_table = "users" def __str__(self): return self.email def get_full_name(self): return self.name def get_short_name(self): return self.name def is_access_valid(self): if self.access_valid_end > utility.now(): return True else: return False def save(self, *args, **kwargs): if not self.sys_id: self.created_when = utility.now() self.last_updated_when = utility.now() return super(UserModel, self).save(*args, **kwargs) Code for its manager is as below. class MyUserManager(BaseUserManager): use_in_migrations = True def create_user(self, email, name, mobile, user_type, password): return create_superuser(self, email, name, … -
ImportError: cannot import name HTMLCalendar
File "managers.py", line 2, in from django.contrib.sites.models import Site File "/usr/lib/python2.7/dist-packages/django/contrib/sites/models.py", line 7, in from django.db import models File "/usr/lib/python2.7/dist-packages/django/db/models/init.py", line 6, in from django.db.models.query import Q, QuerySet, Prefetch # NOQA File "/usr/lib/python2.7/dist-packages/django/db/models/query.py", line 16, in from django.db.models import sql File "/usr/lib/python2.7/dist-packages/django/db/models/sql/init.py", line 2, in from django.db.models.sql.subqueries import * # NOQA File "/usr/lib/python2.7/dist-packages/django/db/models/sql/subqueries.py", line 9, in from django.db.models.sql.query import Query File "/usr/lib/python2.7/dist-packages/django/db/models/sql/query.py", line 17, in from django.db.models.aggregates import Count File "/usr/lib/python2.7/dist-packages/django/db/models/aggregates.py", line 5, in from django.db.models.expressions import Func, Star File "/usr/lib/python2.7/dist-packages/django/db/models/expressions.py", line 7, in from django.db.models import fields File "/usr/lib/python2.7/dist-packages/django/db/models/fields/init.py", line 19, in from django import forms File "/usr/lib/python2.7/dist-packages/django/forms/init.py", line 6, in from django.forms.fields import * # NOQA File "/usr/lib/python2.7/dist-packages/django/forms/fields.py", line 21, in from django.forms.utils import from_current_timezone, to_current_timezone File "/usr/lib/python2.7/dist-packages/django/forms/utils.py", line 12, in from django.utils.html import escape, format_html, format_html_join, html_safe File "/usr/lib/python2.7/dist-packages/django/utils/html.py", line 13, in from django.utils.http import RFC3986_GENDELIMS, RFC3986_SUBDELIMS File "/usr/lib/python2.7/dist-packages/django/utils/http.py", line 4, in import calendar File "/home/homa/Desktop/zinnia/calendar.py", line 4, in from calendar import HTMLCalendar ImportError: cannot import name HTMLCalendar from calendar import HTMLCalendar class Calendar(HTMLCalendar): """ Extension of the HTMLCalendar. """