Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Creating a JSON Object in views and passing it in HTML
views.py - Django 2.0.2 def hotels(request): list_of_hotels = Hotel.objects.order_by('hotel_name') template = loader.get_template('myapp/hotels.html') data = {} for each in list_of_hotels: data[str(each.hotel_name)] = 'null' json_data = json.dumps(data) context = { 'list_of_hotels': list_of_hotels, 'json_data': json_data, } return HttpResponse(template.render(context, request)) hotels.html <div class="row"> <div class="col s12"> <div class="row"> <div class="input-field col s12"> <i class="material-icons prefix">search</i> <input type="text" id="autocomplete-input" class="autocomplete"> <label for="autocomplete-input">Search</label> </div> </div> </div> </div> <script> var jsonObj = "{{json_data}}"; $(document).ready(function(){ $('input.autocomplete').autocomplete({ data: jsonObj, }); }); </script> I'm trying to parse a JSON Object from Django views into a script located inside the corresponding HTML page. I tried everything, but it just doesn't seem to work. I searched StackOverflow for about an hour now, and based on all the answers came to these snippets of code, which still don't work. Any leads on how to go about it would be highly appreciated! P.S: In the script in hotels.html, the data takes in a JSON Object. For more details on the initialisation, refer to this. P.P.S: I am an absolute noob in JavaScript/ jQuery, so please be patient before down voting the answer. Thanks in advance! -
PyCharm can't import CaptchaField
I'm using python3.6 Django 2.0 and pip install django-simple-captcha after makemigrations,I code from captcha.fields import CaptchaField CaptchaField has a red underline,it means PyCharm can't import CaptchaField I don't downgrade my python and Django version. Anyone know how to deal with this issue?Many thanks! -
Django - oauth2client.client.HttpAccessTokenRefreshError: disabled_client
Below is the settings.py config for Google Drive integration. GOOGLE_DRIVE_STORAGE_JSON_KEY_FILE = os.path.join(PROJECT_PATH, 'media') + '/edure-81e107c05989.json' The same file is used in production server and it is working good. But i am not able to compile in local development environment. I have added few model changes .I am getting below error while running ./manage.py migrate (edure_env_dev) Priyabratas-MacBook-Air:Edure.CO uprince$ python manage.py migrate "/Users/uprince/PycharmProjects/Edure.CO/edure_env_dev/lib/python2.7/site-packages/googleapiclient/discovery.py", line 276, in _retrieve_discovery_doc resp, content = http.request(actual_url) File "/Users/uprince/PycharmProjects/Edure.CO/edure_env_dev/lib/python2.7/site-packages/oauth2client/transport.py", line 159, in new_request credentials._refresh(orig_request_method) File "/Users/uprince/PycharmProjects/Edure.CO/edure_env_dev/lib/python2.7/site-packages/oauth2client/client.py", line 749, in _refresh self._do_refresh_request(http) File "/Users/uprince/PycharmProjects/Edure.CO/edure_env_dev/lib/python2.7/site-packages/oauth2client/client.py", line 819, in _do_refresh_request raise HttpAccessTokenRefreshError(error_msg, status=resp.status) oauth2client.client.HttpAccessTokenRefreshError: disabled_client: The OAuth client was disabled. The site is running good in prod. The same Drive API is used in local. but its throwing the above error. Any suggestions where i am doing wrong? -
Voice Message Chat app
Can anyone help me in implementing a chat application in which users can send voice message or recorded messages.I am only familiar with android and django and what I need is a just a kick starter for how to do this.Please someone guide me or provide me some valuable resources so that I can accomplish my task. I am not getting any suitable help anywhere -
Django query set across foreign keys with count
I am in need of some assistance with a query. I have three models linked by foreign keys these are Suppliers <-> Restaurants <-> Ingredients. I need to get the names of the five suppliers who have the largest number of ingredients to restock. My models can be seen below, from my understanding I will need to firstly filter for just the ingredients that have a stock_status = "out of stock". I will then need to perform a count on them probably through annotation, taking this Count and ordering it. Finally I will take take the first five using on the .orderby()[5:]. I am unsure as to how to put this all together, and would appreciate any help available. class Ingredients(models.Model): out_of_stock = "out_of_stock" partial = "partial" full = "full" STOCK_CHOICES = ( (out_of_stock, 'Out of stock'), (partial, 'Partial'), (full, 'Full'), ) name = models.CharField(max_length=32, blank=False, null=False) restaurant_name = models.ForeignKey(Restaurant, on_delete=models.CASCADE) class Restaurant(models.Model): name = models.CharField(max_length=32, blank=False, null=False) supplier_name = models.ForeignKey(Supplier, on_delete=models.CASCADE) class Supplier(models.Model): name = models.CharField(max_length=32, blank=False, null=False) Sorry if it is a little unclear, I am struggling to put together what is in my mind and what I am writing at the moment. If you need any clarification … -
Django Method Not Allowed (POST): password_reset/done
I'm new on Django / Python. I'm trying to implement a mechanism to reset user's password via e-mail. In order to do that I'm trying to use as much as possible the Django native library django.contrib.auth Although, when processing my custom made password_reset_form.html (see below) I got an error: Method Not Allowed (POST): /accounts/password_reset/done/ <form method="post" class="m-t" role="form" action="{% url 'password_reset_done' %}"> {% csrf_token %} <div class="form-group"> <input type="email" class="form-control" id="id_forgot_email" name="email" placeholder="Email address" required=""> </div> <button type="submit" class="btn btn-primary block full-width m-b">Reset password</button> </form> Anyone has clue why post method is not permitted? I've checked the following Django Tutorial that uses a post method in exactly the same file... Cheers, TC -
How to run `Model.objects.values()` with command-line option?
In Django, I'm making a manage.py command called some_command. Here's what I have in management/commands/some_command.py so far. class Command(BaseCommand): def add_arguments(self,parser): parser.add_argument( "--fields", dest="fields", required=True, help="Fields to query; Enter in pipe-delimited format", ) def handle(self, *args, **options): Model= apps.get_model(app_label="my_app", model_name="MyModelName") print Model.objects.values(tpl(fields.split('|'))) This gives me the error: AttributeError: 'tuple' object has no attribute 'split'. The option fields is a string of columns I want to query, delimited by the pipe character. So it will look something like "col1|col2". How do I query just those fields via this custom Django command line process? -
Django - Custom for loop on ModelForm select field raises 'invalid choice' error
I'm using Django forms with a RadioSelect widget for one of the fields - field1. Rendering the form in the template as {{ form.field1 }} doesn't raise any errors (i.e. not an invalid choice), but I want to add a little bit more customisation to the radio select widget. The following code is the general for loop that I'm writing in my template to loop over each choice to style them... {% for choice in acc.field1 %} <label> <div class='...'><input type='radio' name='field1'/></div> <div class='...'>{{ choice }}</div> </label> {% endfor %} ...which raises the error 'invalid choice'. Is there anything I'm doing wrong here? Thanks -
Django Query Get all User Items from my Accounts
I am trying to figure out the best (simplest) ways to call all the "Items" from my different User "Accounts." The Account has the User ForeignKey. class Acct ( models.Model ): user = models.ForeignKey ( settings.AUTH_USER_MODEL) The Item has the Account foreignKey. class Items ( models.Model ): acct = models.ForeignKey ( Acct ) So when I have a list of Acct's - what is the best way to get all the User's Items for the different accounts? I can get all the Accounts with something like this: a = request.user.acct_set.all ().filter ( active = 1 ) Now what is the next call to get the Items for those Accounts? Only thing I can figure out is to add the User foreignKey to the Accounts also. (I would also have to add the Active field.) I hope this makes sense. Thank you. -
Adding an array to a froeign key django models
class Route(models.Model): id = models.AutoField(primary_key=True) van = models.ForeignKey(Van, on_delete=models.CASCADE) orders = models.ForeignKey(Order, on_delete=models.CASCADE) def __repr__ (self): return '<Route %s>' % str(self.id) def __str__ (self): return str(self.id) class Order(models.Model): id = models.AutoField(primary_key=True) order_types = ( ('0', 'pickup'), ('1', 'delivery'), ) location = models.ForeignKey(Location, on_delete=models.CASCADE) timestamp = models.CharField(max_length=120, default='') def __repr__ (self): return '<Order %s>' % self.id def __str__ (self): return self.id I want to be able to formulate my route so it can accept orders/and have multiple orders. order1 = Order.objects.get(id=1) order2 = Order.objects.get(id=2) van = Van.objects.get(id=1) route = Route(orders=[order1,order2],van=van) route.save() ValueError: Cannot assign "[<Order 1>, <Order 2>]": "Route.orders" must be a "Order" instance. How would I be able to pass in an array to my ForeignKey field? -
copy django package to another folder
I want to copy the folder for django in such a way to allow it to be used on another server (where I can't fetch django remotely). I can do this in my python shell: >>> import django >>> import sys >>> sys.path ['', '/usr/local/Cellar/python3/3.6.1/Frameworks/Python.framework/Versions/3.6/lib/python36.zip', '/usr/local/Cellar/python3/3.6.1/Frameworks/Python.framework/Versions/3.6/lib/python3.6', '/usr/local/Cellar/python3/3.6.1/Frameworks/Python.framework/Versions/3.6/lib/python3.6/lib-dynload', '/usr/local/lib/python3.6/site-packages', '/Users/Jakob/Desktop/dev_projects/django_install/django'] $ which django-admin /usr/local/bin/django-admin Which folder do I need to copy? -
Django JsonRequest in generic view always returns a string
(using Django2.0) This is my first time trying to collaborate with a frond-end developer and I am trying to serialize a Django model from a generic ListView. Even though I manage to send a JsonResponse with my objects as json, they are always a string: "[{\"model\": \"questions.question\", \"pk\": 9535, \"fields\": {\"created\": \"2018-04-14T17:02:38.559Z\", \"modified\": \"2018-04-14T18:04:14.264Z\", \"question\": \"TEST\", \"category\": \"Rules\", \"event\": \"Beyonce\", \"answer\": \"aergaergaergaer\", \"verified\": true, \"verified_by\": [\"someotheruser\"], \"count\": 0, \"user_created\": [\"someuser\"]}}]" the way the front-end developer solved this issue is by calling a JSON.parse(). (see: https://www.w3schools.com/js/js_json_parse.asp). Is this the correct way to do it or should I return the objects without a string? If I am wrong and there is a way to do this without the strings here is my view and url: views.py: from events.models import Event from django.core import serializers from django.http import JsonResponse class EventView(LoginRequiredMixin, ListView): login_url = '/accounts/login/' model = Question template_name = 'faq/faq.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) events_list = Event.objects.all() context['events_list'] = events_list return context def get_queryset(self): event = Event.objects.get(event=self.kwargs['event']) queryset = Question.objects.filter(event=event) return queryset def get(self, request, *args, **kwargs): queryset = self.get_queryset() data = serializers.serialize("json", queryset, use_natural_foreign_keys=True) return JsonResponse(data, status=200, safe=False) urls.py urlpatterns += [ path('<str:event>/', EventView.as_view(), name='event'), ] What I also … -
Possible to do this in a Django template tag? {{ string_field.rjust(8, '0') }}
Possible to do this in a Django template tag? {{ string_field.rjust(8, '0') }} -
Can't create new project with django-admin
I installed django using the following command on my Ubuntu 16.04 machine: sudo apt-get install python3-django Then when I run django-admin web web to create a new project, I get the following error: Traceback (most recent call last): File "/usr/lib/python3/dist-packages/django/core/management/__init__.py", line 179, in fetch_command app_name = commands[subcommand] KeyError: 'web' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/usr/bin/django-admin", line 21, in <module> management.execute_from_command_line() File "/usr/lib/python3/dist-packages/django/core/management/__init__.py", line 354, in execute_from_command_line utility.execute() File "/usr/lib/python3/dist-packages/django/core/management/__init__.py", line 346, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/usr/lib/python3/dist-packages/django/core/management/__init__.py", line 182, in fetch_command settings.INSTALLED_APPS File "/usr/lib/python3/dist-packages/django/conf/__init__.py", line 48, in __getattr__ self._setup(name) File "/usr/lib/python3/dist-packages/django/conf/__init__.py", line 42, in _setup % (desc, ENVIRONMENT_VARIABLE)) django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. I tried searching, but all I found was people encountering this error while working with existing projects, not making a completely new one. What exactly am I doing wrong here? -
How to test Exception in signal?
I have a signal: create_flat_referral = django.dispatch.Signal(providing_args=["request", "user"]) And I have a receiver: @receiver(create_flat_referral, sender=None) def save_flat_referral(sender, request, user, **kwargs): referral_link = request.POST.get('referral', None) if not referral_link: referral_link = request.GET.get('ref', None) try: if referral_link: link = Link.objects.get(token = referral_link) referral = FlatReferral.objects.create( referrer = link.user, referred = user ) except Link.DoesNotExist: logger.exception('...') except ValidationError: logger.exception('...') I want to cover all the exceptions with the tests. In addition to what I want to get assertRaises, I also want to get assertRaisesMessage What's the best way to do this? If I'm trying to do something like this: self.assertRaises( ValidationError, lambda: signals.create_flat_referral.send( sender = None, request = post_request, user = self.referred ) ) That I fail the test: AssertionError: ValidationError not raised by lambda -
Beginning Django: Access elements via foreign key
I recently started with using django and have been stuck for a while now. I have created three models: class Depot(models.Model): depot_name = models.CharField(max_length = 200) def __str__(self): return self.depot_name class Stock(models.Model): stock_key = models.CharField(max_length = 200) company_name = models.CharField(max_length = 200) price = models.FloatField() def __str__(self): return self.company_name def get_price(self): return self.price class Asset(models.Model): depot = models.ForeignKey(Depot, on_delete= models.CASCADE) stock = models.ForeignKey(Stock, on_delete= models.CASCADE, related_name="testName") number_of_stocks = models.IntegerField(default=0) def value(self): p = self.testName.price return p*self.number_of_stocks def __str__(self): return str(self.stock)+" "+str(self.number_of_stocks)+" "+str(self.value()) Basically to calculate the value of an asset I need the price of its stock. I have not found anything how to access the data of the class stock via the ForeignKey. Maybe it is to trivial. I would really appreciate your help. -
How to check if the choices selected by the candidate are correct in a Quiz Application in Django?
I am making a Quiz application in Django and I wanted to know how I can get the number of questions answered correctly by the user? -
How to share Django sessions across newly added subdomains
I've recently added some new subdomains (e.g x.example.com) to my django site (all under the same app), and I'd like users to stay logged in across these subdomains. According to the Django docs, I can simply set the SESSION_COOKIE_DOMAIN setting to be ".example.com" to do this, but the docs mention this warning: Be cautious when updating this setting on a production site. If you update this setting to enable cross-domain cookies on a site that previously used standard domain cookies, existing user cookies will be set to the old domain. This may result in them being unable to log in as long as these cookies persist. Given that I'm currently using standard domain cookies, this certainly applies to me! However, the docs offer no solution. How can I switch the SESSION_COOKIE_DOMAIN to be cross-domain without messing up my existing users' sessions (and ideally, without forcing them to log out)? -
connections does not see the table relations of a second database during testing with pytest-django
I have a problem where my django connections object seems to get the wrong database information. I stumbled upon this issue when I was querying on a table in the 'customers' DB and Django told me the relation does not exist. With the settings.py database section was set up like below: DATABASES = { 'default': { 'NAME': 'user_data', 'ENGINE': 'django.db.backends.postgres', 'USER': 'postgres_1', 'PASSWORD': 'superS3cret' }, 'customers': { 'NAME': 'customer_data', 'ENGINE': 'django.db.backends.postgres', 'USER': 'postgres_1', 'PASSWORD': 'superS3cret' } } Both cursors below get the information from the 'default' database when I run 'pytest' on the directory with: sql = """SELECT table_name FROM information_schema.tables WHERE table_nameschema='public'""" default = connections["default"].cursor() default.execute(sql) raw_data = default.fetchall() sql_columns = [col[0] for col in default.description] df1 = pd.DataFrame(raw_data, columns=sql_columns) customers = connections["customers"].cursor() customers.execute(sql) raw_data = customers.fetchall() sql_columns = [col[0] for col in customers.description] df2 = pd.DataFrame(raw_data, columns=sql_columns) The results of df1 and df2 are exactly the same: Only the table names in the 'default' database. This happens with pytest-django and using a second Postgres database. In the query above I would expect df1 and df2 to be different, so far as the 'default' and 'customers' databases are different. However, the connections cursor does not properly 'see' the second … -
Django 2.0: Send data from a view to a template that is included in another template (2 different Apps)
I'm working on a Django Project that has two apps, home and contact. I would like to send the context dictionary from the contact view to the contact_form.html template, which is included in the home.html template. I can't figure out the way to pass the values to the contact_form.html template because there's not a url for the contact\views.py. home\urls.py: from django.urls import path from . import views app_name = 'home' urlpatterns = [ path('', views.home, name='home'), ] home\views.py: from django.shortcuts import render def home(request): return render(request, "home/home.html", {}) templates\home\home.html: {% extends "base.html" %} {% block content %} <h1>Home template</h1> {% include 'contact/contact_form.html' %} {% endblock %} contact\views.py: def contact_view(request): context = {'hello_contact': 'hello from contact view'} return render(request, 'contact/contact_form.html', context) templates\contact\contact_form.html: <h2>Contact Template</h2> <p>{{ hello_contact }}</p> Thanks for your help :) -
Does anyone have a solution to this error in "models.py" in Django
Can you help me figure out where the error is? I am a beginner in Python 3. I have the file in Django: models.py from __future__ import unicode_literals from django.db import models #Create your models here. class Interaction(models.Model): input = models.CharField(max_length=100) output = models.TextField() script = models.TextField() execute_script = models.BooleanField(default=False) def __unicode__(self): return self.input def get_output(self, binds): return self.output % binds def execute(self): try: exec self.script dic = script() return dic except Exception as ex: return 'ERRO', str(ex) class Meta: db_table = 'interaction' I get this error: ... exec self.script ^ SyntaxError: Missing parentheses in call to 'exec' I'm a beginner in Python and in stackoverflow. It may seem like a simple problem, but to me it's a new world, so I need you to help me. -
Database connection is not working even after providing proper settings in settings.py in django
i am trying to connect mysql in one of my django settings and then try to run django-admin db shell in command line but it is not working. here is my code for settings.py: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'investors_data', 'USER': 'root', 'PASSWORD': '', 'HOST': '127.0.0.1', 'PORT': '3306', } } and when i am trying to run django-admin dbshell then i am fgetting the following error: Traceback (most recent call last): File "c:\users\nishant singh\appdata\local\programs\python\python36-32\lib\runpy.py", line 193, in _run_module_as_main "__main__", mod_spec) File "c:\users\nishant singh\appdata\local\programs\python\python36-32\lib\runpy.py", line 85, in _run_code exec(code, run_globals) File "C:\Users\Nishant Singh\AppData\Local\Programs\Python\Python36-32\Scripts\django-admin.exe\__main__.py", line 9, in <module> File "c:\users\nishant singh\appdata\local\programs\python\python36-32\lib\site-packages\django\core\management\__init__.py", line 364, in execute_from_command_line utility.execute() File "c:\users\nishant singh\appdata\local\programs\python\python36-32\lib\site-packages\django\core\management\__init__.py", line 356, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "c:\users\nishant singh\appdata\local\programs\python\python36-32\lib\site-packages\django\core\management\base.py", line 283, in run_from_argv self.execute(*args, **cmd_options) File "c:\users\nishant singh\appdata\local\programs\python\python36-32\lib\site-packages\django\core\management\base.py", line 322, in execute saved_locale = translation.get_language() File "c:\users\nishant singh\appdata\local\programs\python\python36-32\lib\site-packages\django\utils\translation\__init__.py", line 195, in get_language return _trans.get_language() File "c:\users\nishant singh\appdata\local\programs\python\python36-32\lib\site-packages\django\utils\translation\__init__.py", line 59, in __getattr__ if settings.USE_I18N: File "c:\users\nishant singh\appdata\local\programs\python\python36-32\lib\site-packages\django\conf\__init__.py", line 56, in __getattr__ self._setup(name) File "c:\users\nishant singh\appdata\local\programs\python\python36-32\lib\site-packages\django\conf\__init__.py", line 39, in _setup % (desc, ENVIRONMENT_VARIABLE)) django.core.exceptions.ImproperlyConfigured: Requested setting USE_I18N, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. I am getting a similar error when … -
What is the most efficient way to delete a duplicate Django model object before saving?
I can't have duplicate objects with the same account_id and region so I have to delete the existing one before saving the updated one. Is it more efficient to check if an item exists before attempting to delete? In my case the item will almost always exist so I think just attempting delete would be best? Is there any better way of doing this I'm not even aware of? class Name(models.Model): primary_key = models.AutoField(primary_key=True) name = models.CharField(max_length=50) region = models.CharField(max_length=20) account_id = models.IntegerField(null=True) def save(self, *args, **kwargs): if Account.objects.filter(account_id=self.account_id, region=self.region).exists(): Account.objects.filter(account_id=self.account_id, region=self.region).delete() # Do some other stuff return super(Name, self).save(*args, **kwargs) -
InterfaceError: Error binding parameter 0 - probably unsupported type when runing my django script
i have the following function def get_id(entityName, text): """Retrieve an entity's unique ID from the database, given its associated text. If the row is not already present, it is inserted. The entity can either be a sentence or a word.""" tableName = entityName + 's' columnName = entityName cursor.execute('SELECT rowid FROM ' + tableName + ' WHERE ' + columnName + ' = ?', (text,)) row = cursor.fetchone() row = cursor.fetchone() if row: return row[0] else: cursor.execute('INSERT INTO ' + tableName + ' (' + columnName + ') VALUES (?)', (text,)) return cursor.lastrowid when ever this method get called it producing this error cursor.execute('SELECT rowid FROM ' + tableName + ' WHERE ' + columnName + ' = ?', (text,)) InterfaceError: Error binding parameter 0 - probably unsupported type. currently this error is producing when i am running this in django otherwise its working fine. what can be the reason ? -
get unique values from query_set Django
I'm trying to get unique results from s query_set. Example. ID | NOMBRE | CLASIFICACION 1 Escoba Limpieza 2 Trapeador Limpieza 3 Tornillo Herramienta I want to get "Limpieza and Herramienta" only. currently I'm getting "Limpieza, Limpieza and Herramineta" my views.py: class ItemListView(ListView): model= Items def get_context_data(self,**kwargs): context = super(ItemListView, self).get_context_data(**kwargs) context['clasificacion'] =Items.objects.order_by('nombre').distinct('clasificacion') return context my models.py from django.db import models # Create your models here. class Items(models.Model): nombre = models.CharField(max_length=250) descripcion = models.CharField(max_length=250) codigo_proveedor = models.CharField(max_length=250) clasificacion = models.CharField(max_length=250) c_minima = models.IntegerField() c_actual = models.IntegerField() proveedor = models.ForeignKey('Proveedores',on_delete=models.CASCADE) active = models.BooleanField() def __str__(self): return self.nombre + ' ----- ' + self.clasificacion + ' ----- ' + str(self.c_actual) class Proveedores(models.Model): nombre = models.CharField(max_length=250) telefono = models.CharField(max_length=250) direccion1 = models.CharField(max_length=250) direccion2 = models.CharField(max_length=250, null=True) active = models.BooleanField() def __str__(self): return self.nombre Thanks for the help!