Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to connect html feilds in django forms
This is my bootstrap html page i am trying to establish the connection between models and html feilds. contact.html {% load static from staticfiles %} <!DOCTYPE html> <html lang="en"> <head> <style> body{ background: url('{% static "img/new4.jpg" %}') no-repeat center fixed; - webkit- background: cover; - moz - background: cover; - o - background: cover; background-size: cover; } </style> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <meta name="description" content=""> <meta name="author" content=""> <title>Personality Leading.com</title> <!-- Bootstrap core CSS --> <link href="{% static 'vendor/bootstrap/css/bootstrap.min.css' %}" rel="stylesheet"> <!-- <link rel="stylesheet" type="text/css" href="{% static 'vendor/bootstrap/css/Custom' %}"> --> <link rel="stylesheet" type="text/css" href="{% static 'vendor/bootstrap/css/Custom.css' %}"> <!-- Custom fonts for this template --> <link href="{% static 'vendor/font-awesome/css/font-awesome.min.css' %}" rel="stylesheet" type="text/css"> <link href='https://fonts.googleapis.com/css?family=Lora:400,700,400italic,700italic' rel='stylesheet' type='text/css'> <link href='https://fonts.googleapis.com/css?family=Open+Sans:300italic,400italic,600italic,700italic,800italic,400,300,600,700,800' rel='stylesheet' type='text/css'> <!-- Custom styles for this template --> <link href="{% static 'css/clean-blog.min.css' %}" rel="stylesheet"> </head> <body> <!-- Navigation --> <div class="mynav"> <div class="p-3 mb-2 bg-info text-white"><strong> PERSONALITY LEADING </strong></div> <nav class="navbar navbar-expand-lg navbar-light fixed-top" id="mainNav"> <div class="container"> <a class="navbar-brand" href="index.html"></a> <button class="navbar-toggler navbar-toggler-right" type="button" data-toggle="collapse" data-target="#navbarResponsive" aria-controls="navbarResponsive" aria-expanded="false" aria-label="Toggle navigation"> Menu <i class="fa fa-bars"></i> </button> <div class="collapse navbar-collapse" id="navbarResponsive"> <ul class="navbar-nav ml-auto"> <li class="nav-item"> <a class="nav-link" href="/home/">Home</a> </li> <li class="nav-item"> <a class="nav-link" href="/about/">About</a> </li> <li class="nav-item"> <a class="nav-link" href="/services/">Services</a> … -
How to filter empty value in a Django queryset?
I want to filter out empty value on email column. So I tried this: users = User.objects.filter(email__iexact='') But, record has empty value would not be appeared. Anyone know why is that? Model is: class User(models.Model): email = models.EmailField(blank=True) -
ImproperlyConfigured SECRET_KEY error using django-environ
In my settings, I'm using django-environ to set the key: import environ env = environ.Env() SECRET_KEY = env.read_env('SECRET_KEY') At the root of my project, I do have a .env file with the actual secret key: .env: SECRET_KEY=qgw6s66n3e$27mmddfua*8yq6n%gz(!mx8e=@zbixk50-h020 The error will run during collectstatic. Here's the traceback: Traceback (most recent call last): File "./manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/Users/sju/.virtualenvs/blog-api/lib/python2.7/site-packages/django/core/management/__init__.py", line 364, in execute_from_command_line utility.execute() File "/Users/sju/.virtualenvs/blog-api/lib/python2.7/site-packages/django/core/management/__init__.py", line 356, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/Users/sju/.virtualenvs/blog-api/lib/python2.7/site-packages/django/core/management/__init__.py", line 194, in fetch_command settings.INSTALLED_APPS File "/Users/sju/.virtualenvs/blog-api/lib/python2.7/site-packages/django/conf/__init__.py", line 56, in __getattr__ self._setup(name) File "/Users/sju/.virtualenvs/blog-api/lib/python2.7/site-packages/django/conf/__init__.py", line 41, in _setup self._wrapped = Settings(settings_module) File "/Users/sju/.virtualenvs/blog-api/lib/python2.7/site-packages/django/conf/__init__.py", line 110, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "/usr/local/Cellar/python/2.7.12_2/Frameworks/Python.framework/Versions/2.7/lib/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) File "/Users/sju/Dev/django/blog-api/src/blog/settings/base.py", line 27, in <module> SECRET_KEY = env('SECRET_KEY') File "/Users/sju/.virtualenvs/blog-api/lib/python2.7/site-packages/environ/environ.py", line 130, in __call__ return self.get_value(var, cast=cast, default=default, parse_default=parse_default) File "/Users/sju/.virtualenvs/blog-api/lib/python2.7/site-packages/environ/environ.py", line 275, in get_value raise ImproperlyConfigured(error_msg) django.core.exceptions.ImproperlyConfigured: Set the SECRET_KEY environment variable What am I missing? -
How to get the number of items in Page object?
I've learned a little about django pagination from here : https://docs.djangoproject.com/en/2.0/topics/pagination/#page-objects And I want to know how to get the number of items in certain Page object. I thought a way like this : Page.end_index() - Page.start_index() + 1 But I think maybe it is not good or inaccurate way to get result. Is there good way to get correct result? -
heroku django can't load my static files django 2.0.2
i have been working to fix it for a week but still not find the solution i've tried all of the solution but can't work my project is fine at local , but when deployed is not like my expect i hav run collectstatic on heroku but still not work the result is like this my heroku app my settings.py import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) TEMPLATES_DIRS = os.path.join(BASE_DIR,'templates') STATIC_DIR = os.path.join(BASE_DIR,'static') #STATICFILES_STORAGE = 'whitenoise.django.GzipManifestStaticFilesStorage' # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.11/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '=i(73nmd3&e&m)&@ivj)av4!yrrcle45t#eoegug-4dn4%m^ba' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = False ALLOWED_HOSTS = ['*'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'portfolio_app', ] 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', 'whitenoise.middleware.WhiteNoiseMiddleware', ] ROOT_URLCONF = 'portfolio.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [TEMPLATES_DIRS], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'portfolio.wsgi.application' # Database # https://docs.djangoproject.com/en/1.11/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } # add this import … -
how to render html form in django
As i am trying to make use bootstrap file in my django application i am not able to make connections my models i am able to see the bootstrap theme when i run server but when i enter data and click on submit button data is not storing in my database and it is not visible in admin panel also please help with this. (When i use simple html file without bootstrap i am able to save the data in dataenter code herebase and it is also showing in admin panel) **my models.py** from django.db import models from django.contrib.auth.models import User class student(models.Model): name = models.CharField(max_length=50) email = models.EmailField(max_length=50) phone = models.CharField(max_length=25) message = models.TextField(max_length=500) def __str__(self): return self.email **my views.py** from django.shortcuts import render from .models import * from .forms import * from django.http import * def contact(request): if request.method == 'POST': form = details_forms(request.POST) name = request.POST.get('name', '')#name model email = request.POST.get('email', '')#email model phone = request.POST.get('phone', '')#phone model message = request.POST.get('message', '')#message model details_obj = student(name=name,email=email,phone=phone,message=message) details_obj.save() form = details_forms() else: form = details_forms() return render(request,'contact.html',{'form':form}) **mycontact.html file** {% load static from staticfiles %} <!DOCTYPE html> <html lang="en"> <head> <style> body{ background: url('{% static "img/new4.jpg" %}') no-repeat … -
'ellipsis' object has no attribute 'lower' - When I run python3 manage.py runserver
I am running a web application(wagtail cms) on linux ubuntu. I am getting this error when I run python3 manage.py runserver 0.0.0.0:8000 Please see the error message on the console. Performing system checks... System check identified no issues (0 silenced). March 22, 2018 - 15:27:33 Django version 1.11.1, using settings 'ntdl.settings' Starting development server at http://0.0.0.0:8000/ Quit the server with CONTROL-C. Internal Server Error: / Traceback (most recent call last): File "/usr/local/lib/python3.6/dist- packages/django/core/handlers/exception.py", line 41, in inner response = get_response(request) File "/usr/local/lib/python3.6/dist-packages/django/utils/deprecation.py", line 138, in __call__ response = self.process_request(request) File "/usr/local/lib/python3.6/dist- packages/django/middleware/security.py", line 25, in process_request host = self.redirect_host or request.get_host() File "/usr/local/lib/python3.6/dist-packages/django/http/request.py", line 105, in get_host if domain and validate_host(domain, allowed_hosts): File "/usr/local/lib/python3.6/dist-packages/django/http/request.py", line 579, in validate_host if pattern == '*' or is_same_domain(host, pattern): File "/usr/local/lib/python3.6/dist-packages/django/utils/http.py", line 291, in is_same_domain pattern = pattern.lower() AttributeError: 'ellipsis' object has no attribute 'lower' "GET / HTTP/1.1" 500 11959 Internal Server Error: /favicon.ico Traceback (most recent call last): File "/usr/local/lib/python3.6/dist- packages/django/core/handlers/exception.py", line 41, in inner response = get_response(request) File "/usr/local/lib/python3.6/dist-packages/django/utils/deprecation.py", line 138, in __call__ response = self.process_request(request) File "/usr/local/lib/python3.6/dist- packages/django/middleware/security.py", line 25, in process_request host = self.redirect_host or request.get_host() File "/usr/local/lib/python3.6/dist-packages/django/http/request.py", line 105, in get_host if domain and validate_host(domain, allowed_hosts): File "/usr/local/lib/python3.6/dist-packages/django/http/request.py", line … -
Display file from django database
I have some pdf files in database. Now I want to display only the file name and when some one clicks on that, user will be able to view the pdf file in browser. views.py def user_sign(request): obj = UserSelection.objects.get(user=request.user) if obj.user_type == 'candidate': print('candidate') form = CandidateDetailForm() return render(request, 'candidate/fill_details.html', {'form':form}) else: cand_dtl = CandidateDetail.objects.all() return render(request, 'employer/get_details.html', {'candidate':cand_dtl}) template file {% extends "base.html" %} {% block content %} <form method="POST" enctype="multipart/form-data"> <h2>Employer</h2> {% for item in candidate %} {{item.first_name}} {{item.last_name}} <a href="#">{{item.resume}}</a> {% endfor %} </form> {% endblock %} -
Django - Template populate table using query {{}}
I'm using Django and I'm trying to make a table that looks like this: Instead it looks like this: I'm using this in the template: <table> {% for procap in procaps %} <tr> <th>{{procap.program.mcpc}}-{{procap.program.title}}</th> <th>{{procap.fy.fy_year}}</th> </tr> <tr> <th> {{procap.rating}} </th> </tr> {% endfor %} </table> This is my model: class Procap(models.Model): id = models.CharField(primary_key=True, max_length=50) rating = models.CharField(max_length=255, blank=True,null=True) fy = models.ForeignKey(Year,related_name='procap', blank=True, null=True) program_task = models.ForeignKey(Ptask,related_name='ptmodel',blank=True,null=True) program = models.ForeignKey(Program, related_name='procappro', blank=True, null=True) task = models.ForeignKey(Task, related_name='ptpro', blank=True, null=True) objects = ProcapManager() Views: procaps = Procap.objects.filter(task=Task_id) How can I make the first table work using {{}}? -
Django Webpack ModuleNotFoundError
I'm trying to follow this guide to set up my django/react project but when I try to runserver in step 4, I get a ModuleNotFoundError: No module named 'webpack_loader'. I have already done pip3 install django-webpack-loader (and pip install django-webpack-loader but I'm using Python 3.6 as the interpreter for the project). When I print(sys.path), it prints: ['', '/anaconda3/lib/python36.zip', '/anaconda3/lib/python3.6', '/anaconda3/lib/python3.6/lib-dynload', '/anaconda3/lib/python3.6/site-packages', '/anaconda3/lib/python3.6/site-packages/aeosa'] When I look into '/anaconda3/lib/python3.6/site-packages', I don't see 'webpack_loader'. Any help? -
Django No Connection Could be Made Because the Machine Actively Refused It
I'm trying to navigate within a website and keep recieving the error: ConnectionError at /exchange/provider Error 10061 connecting to 127.0.0.1:6379. No connection could be made because the target machine actively refused it. Request Method: GET Request URL: http://127.0.0.1:8000/exchange/provider Django Version: 2.0.2 Exception Type: ConnectionError Exception Value: Error 10061 connecting to 127.0.0.1:6379. No connection could be made because the target machine actively refused it. Exception Location: C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python36_64\lib\site-packages\redis\connection.py in connect, line 489 Python Executable: C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python36_64\python.exe Python Version: 3.6.4 Python Path: ['C:\\Users\\sdres\\Documents\\Django\\github_repo\\32018\\innovatorsedge', 'C:\\Program Files (x86)\\Microsoft Visual ' 'Studio\\Shared\\Python36_64\\python36.zip', 'C:\\Program Files (x86)\\Microsoft Visual Studio\\Shared\\Python36_64\\DLLs', 'C:\\Program Files (x86)\\Microsoft Visual Studio\\Shared\\Python36_64\\lib', 'C:\\Program Files (x86)\\Microsoft Visual Studio\\Shared\\Python36_64', 'C:\\Program Files (x86)\\Microsoft Visual ' 'Studio\\Shared\\Python36_64\\lib\\site-packages', 'C:\\Users\\sdres\\Documents\\Django\\github_repo\\32018\\innovatorsedge'] Server time: Wed, 21 Mar 2018 20:50:37 -0700 Error during template rendering In template C:\Users\sdres\Documents\Django\github_repo\32018\innovatorsedge\common\templates\common\base.html, error at line 0 Error 10061 connecting to 127.0.0.1:6379. No connection could be made because the target machine actively refused it. 1 {% include "common/header.html" %} 2 {% block content %}{% endblock %} 3 {% include "common/footer.html" %} Traceback Switch to copy-and-paste view C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python36_64\lib\site-packages\django_redis\cache.py in _decorator return method(self, *args, **kwargs) ... ▶ Local vars C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python36_64\lib\site-packages\django_redis\cache.py in get client=client) ... ▶ Local vars … -
Django/Jquery PreventDefault works only with the first item on for loop
i'm trying to use Jquery PreventDefault to use some AJAX on my django blog post for loop but the PreventDefault works only with the Top post only template {% for posts in list %} #{{ posts.title }} and other stuff goes here <a href="" data-href=" " id="like-btn"></a> <span data-likes=" {{ posts.like.count }} " id="{{posts.id}}" > {{ posts.like.count }} </span> {% endfor %} jquery $(document).ready(function(){ $("#like-btn").click(function(e){ e.preventDefault() }) the preventDefault works fine with the first post but it doesn't work with any other post -
Django - Problems displaying option in query
I have this form: <div id=from_programs> {% for program in programs %} <div class=rate_boxes> <label class=plabels><a href=""> Program: {{program.program.num}}-{{program.program.title}}</a> <ul class=cap_box2><br> <label id=cap_labeltitle for="cap_box2">Title</label> <form action="" method="POST"> {% csrf_token %} {% for year in years %} <li class=cap_select2> <div id=fyc2>{{year.fy_year}}</div> <select name="rating2"> <option value ="{{progam.ptmodel.rating | default_if_none:"Choose from List"}}" {% if program.ptmodel.rating == current_program %} selected="selected" {% endif %}>{{program.ptmodel.rating}}</option> <option class=High value="High">High</option> <option class=Medium value="Medium">Medium</option> <option class=Low value="Low">Low</option> <option class=N/A value="N/A">N/A</option> </select> <input type="hidden" name="fy_years" value={{year.fy_year}}> <input type="hidden" name="cap_id" value="{{program.task.id}}-{{program.program.id}}-{{year.id}}"> <input type="hidden" name="pt_id" value="{{program.task.id}}-{{program.program.id}}"> <input type="hidden" name="task" value="{{program.task.id}}"> <input type="hidden" name="program" value="{{program.program.id}}"> </li> {% endfor %} <br> <input id=save_cap2 type="submit" value="Save"> </form> After I save the form, I want the page to display the selected value on the page and I'm unable to make that happen. This: <option value ="{{progam.ptmodel.rating | default_if_none:"Choose from List"}}" {% if program.ptmodel.rating == current_program %} selected="selected" {% endif %}>{{program.ptmodel.rating}}</option> is not working. I'm unable to access the rating. I have the following models: class Ptask(models.Model): id = models.CharField(primary_key=True,max_length=10) program = models.ForeignKey(Program, related_name='protask', blank=True, null=True) task = models.ForeignKey(Task, related_name='taskpro', blank=True, null=True) ppt = models.TextField(blank=True, null=True) class Meta: ordering=['program'] objects = PtaskManager() class Procap(models.Model): id = models.CharField(primary_key=True, max_length=50) rating = models.CharField(max_length=255, blank=True,null=True) year = models.ForeignKey(Year,related_name='procap', blank=True, null=True) … -
Connecting Django and SqlLite issues
I am having a huge problem getting my database to work with my code. I am super new to this but I have tried joining it in my terminal and through my code but on my login page it still does not work. I am trying to login and display that I am logged in here is my code.... server.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } models.py def validate_login(self, post_data): # initiate error message list errors = [] # checks for matching email in db if len(self.filter(email=post_data['email'])) > 0: # stores matching email into a variable named 'user' user = self.filter(email=post_data['email'][0]) # check to see if hashes match if not bcrypt.checkpw(post_data['password'].encode(), user.password.encode()): errors.append('email/password incorrect') else: errors.append('email/password incorrect') # if the if errors: return errors return user class User(models.Model): first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) email = models.EmailField(unique=True) password = models.CharField(max_length=255) created_at = models.DateTimeField(auto_now_add=True) objects = UserManager() def __str__(self): return self.email views.py def login(request): result = User.objects.validate_login(request.POST) if type(result) == list: for err in result: messages.error(request, err) return redirect('/') request.session['user_id'] = result.id messages.success(request, 'Successfully logged in!') return redirect('/success') def success(request): return render(request, 'login_reg/success.html') -
Can't import django app files
I want to run a script that imports from app2.models. My folder structure is as follows: \web \web ... settings.py \app2 ... models.py \database_tools Controller.py app2 is listed in installed apps in ./web/settings. In the script ./app2/database_tools/Controller.py, I want to import models.py from ./app2 So I add the path and import os.environ.setdefault("DJANGO_SETTINGS_MODULE", "app2.settings") # Gives ModuleNotFoundError: No module named 'stats' from app.models import SomeModel The error above is when executing $python app2/database_tools/Controller.py directly. The same import statement (i.e. from stats.app2 ...) works when executing unittests via manage.py -
Django - Sum related fields that belongs to the same FK, for every object
So I'm trying to get the sum of every score in all games related to the according player and how many game he has played class Player(models.Model): name = models.CharField() class Game(models.Model): points = models.IntegerField() user = models.ForeignKey(User, on_delete=models.CASCADE) My desired output is: { "name": "asdf", "total_points": "9999" "games_played": "12" } I thought I could do it getting a value list of my players then looking the sum of all games and count games played for every value on the list, but I don't know how to do it. I know how to do it for an specific Player, but I want to get the entire list. I see this as a loop where every Player counts by its own. Thanks -
How do I overwrite a Django form field in JavaScript?
I have 2 Django forms in a template, in which I also have a Google Map: <form id="user_form" method="post" action="{% url 'register' %}" enctype="multipart/form-data"> {% csrf_token %} {{ user_form.as_p }} {{ profile_form.as_p }} <input type="submit" name="submit" value="Register" /> </form> In the profile_form there is a field with name="latitude" and id="id_latitude". When the user clicks on the map, I want to update that field with the new latitude from the Google map. Here is my JS: var geocoder; var infowindow; var marker; var map; function initMap() { geocoder = new google.maps.Geocoder(); infowindow = new google.maps.InfoWindow; var uluru = {lat: 55.8642, lng: 4.2518}; map = new google.maps.Map(document.getElementById('map'), { zoom: 8, center: uluru }); marker = new google.maps.Marker({ position: uluru, map: map }); google.maps.event.addListener(map, 'click', function(event) { showAddressFromLatLng(geocoder, map, infowindow, event.latLng); var latlng = new google.maps.LatLng(event.latLng.lat(), event.latLng.lng()); marker.setPosition(latlng); //$('#id_latitude').val(event.latLng.lat()); //$('#id_longitude').val(event.latLng.lng()); $('input[name=latitude]').val(event.latLng.lat()); $('input[name=longitude]').val(event.latLng.lng()); console.log("Latitude:" + document.getElementById("id_latitude").value); //document.getElementById("id_latitude").value = event.latLng.lat(); //document.getElementById("id_longitude").value = event.latLng.lng(); }); } Here is my models.py: At the end of the JS you can see all the ways I tried to change the latitude field. The console shows the accurate latitude on each click, but for some reason when the submit button is pressed, the default value of the field isn't overwritten. … -
Serialize related models in Django Rest Framework
I have django models that are simplified as: class Client(models.Model): name = models.CharField(max_length=255) def __str__(self): return self.name class ClientDetail(models.Model): client = models.ForeignKey(Client, on_delete=models.CASCADE) business_format = models.CharField(max_length=255) def __str__(self): return "Details for {}".format(self.client.name) class ClientAssignment(models.Model): client = models.ForeignKey(Client, on_delete=models.CASCADE) assignment = models.ForeignKey(Assignment, on_delete=models.CASCADE) def __str__(self): return "Assignment: {} for Client: {}".format(self.assignment.name, self.client.name) class Assignment(models.Model): name = models.CharField(max_length=255) def __str__(self): return self.name I am using django-rest-framework and would like to create a view where I can provide client_id and receive a serialized object that contains all 3 related models. I tried using PrimaryKeyRelatedField as follows but I'm not sure if I'm using this correctly. class CompleteClientObject(ModelSerializer): assignment = PrimaryKeyRelatedField(many=True, queryset=ClientAssignment.objects) detail = PrimaryKeyRelatedField(many=True, queryset=ClientDetail.objects) client = PrimaryKeyRelatedField(queryset=Client) class Meta: model = Client fields = ("id", "name", "detail", "assignment",) How can I achieve this using serializers? -
How does database indexing work with Lookups in Django?
I wanted to include the models country, region and cities in a Django Project. To do so, I used the library django-cities-light But I had trouble understanding the utility of the class ToSearchTextField. def to_ascii(value): """ Convert a unicode value to ASCII-only unicode string. For example, 'République Françaisen' would become 'Republique Francaisen' """ return force_text(unidecode(value)) def to_search(value): """ Convert a string value into a string that is usable against City.search_names. For example, 'Paris Texas' would become 'paristexas'. """ return ALPHA_REGEXP.sub('', to_ascii(value)).lower() class ToSearchIContainsLookup(lookups.IContains): """IContains lookup for ToSearchTextField.""" def get_prep_lookup(self): """Return the value passed through to_search().""" value = super(ToSearchIContainsLookup, self).get_prep_lookup() return to_search(value) class ToSearchTextField(models.TextField): """ Trivial TextField subclass that passes values through to_search automatically. """ ToSearchTextField.register_lookup(ToSearchIContainsLookup) class AbstractCity(Base): """ Base City model. """ display_name = models.CharField(max_length=200) search_names = ToSearchTextField( max_length=4000, db_index=INDEX_SEARCH_NAMES, blank=True, default='') -
How to refer to the current object in a Django ModelForm?
I have two related models, Company and Package. Each company can have several packages, but only one default_package. Here are the models: class Company(models.Model): default_package = models.OneToOneField( Package, blank=True, null=True, related_name='default_for_%(class)s') and for Package, class Package(TimeStampedModel): company = models.ForeignKey('lucy_web.Company') I'm trying to make a generic CreateView and UpdateView for the company as follows: class EditViewsMixin(DashboardAccessMixin, SuccessMessageMixin): model = Company success_url = reverse_lazy('dashboard:companies') form_class = CompanyForm class CompanyCreate(EditViewsMixin, CreateView): template_name = 'companies/new.html' success_message = "Company '%(name)s' was created successfully" class CompanyUpdate(EditViewsMixin, UpdateView): template_name = 'companies/edit.html' success_message = "Company '%(name)s' was updated successfully" def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['packages'] = self.object.package_set.order_by('name') return context The CompanyForm is similar to the following: class CompanyForm(forms.ModelForm): class Meta: model = Company fields = [ 'name', 'default_package', ] The problem is that in this form, the default_package drop-down menu shows all packages, whereas I would like it to the packages in the package_set of the company under consideration, similar to what is done by referring to self.object in the view's get_context_data method. In essence, I'd like to do something like this in the CompanyForm: default_package = forms.ModelChoiceField( queryset=Package.objects.filter(company=self.instance) ) However, this is not possible because self is not defined at this level. Is there some kind … -
Django celery 4 - ValueError: invalid literal for int() with base 10 when start celery worker
I have configured my celery.py as its documents but I put my celery broker url to AWS SQS but I cannot start it to work. When I run the celery worker, I get the ValueError as: File "/Users/abd/Desktop/proj-aws/lib/python3.6/site-packages/celery/bin/base.py", line 244, in __call__ ret = self.run(*args, **kwargs) File "/Users/abd/Desktop/proj-aws/lib/python3.6/site-packages/celery/bin/worker.py", line 255, in run **kwargs) File "/Users/abd/Desktop/proj-aws/lib/python3.6/site-packages/celery/worker/worker.py", line 99, in __init__ self.setup_instance(**self.prepare_args(**kwargs)) File "/Users/abd/Desktop/proj-aws/lib/python3.6/site-packages/celery/worker/worker.py", line 120, in setup_instance self._conninfo = self.app.connection_for_read() File "/Users/abd/Desktop/proj-aws/lib/python3.6/site-packages/celery/app/base.py", line 752, in connection_for_read return self._connection(url or self.conf.broker_read_url, **kwargs) File "/Users/abd/Desktop/proj-aws/lib/python3.6/site-packages/celery/app/base.py", line 828, in _connection 'broker_connection_timeout', connect_timeout File "/Users/abd/Desktop/proj-aws/lib/python3.6/site-packages/kombu/connection.py", line 181, in __init__ url_params = parse_url(hostname) File "/Users/abd/Desktop/proj-aws/lib/python3.6/site-packages/kombu/utils/url.py", line 34, in parse_url scheme, host, port, user, password, path, query = _parse_url(url) File "/Users/abd/Desktop/proj-aws/lib/python3.6/site-packages/kombu/utils/url.py", line 52, in url_to_parts parts.port, File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/urllib/parse.py", line 167, in port port = int(port, 10) ValueError: invalid literal for int() with base 10: 'xi' I've been looking around but seems to have no clue how to fix this. Please help me out with this! Much appreciated! -
querysets with left join in django
how can I perform the following query in a view.py django select plan.unidad_negocio_clave,plan.id as folio_plan,objetivo.id as objetivo,objetivo.descripcion as descripcion_objetivo,actividad.id as actividad,actividad.descripcion as descripcion_actividad, plan.responsable,plan.autorizador ,plan.status from `planeacion_plan` as plan left join `planeacion_objetivo` as objetivo on objetivo.plan_id = plan.id left join `planeacion_actividadobjetivo` as actividad on actividad.objetivo_id = objetivo.id where plan.anio = 2018 -
Crashing deploy to heroku
I configured my project for using Django but the following error occurred while deploying: -----> Python app detected -----> Installing python-3.6.4 -----> Installing pip Traceback (most recent call last): File "/app/tmp/buildpacks/779a8bbfbbe7e1b715476c0b23fc63a2103b3e4131eda558669aba8fb5e6e05682419376144189b29beb5dee6d7626b4d3385edb0954bffea6c67d8cf622fd51/vendor/pipenv-to-pip", line 23, in <module> main() File "/app/tmp/buildpacks/779a8bbfbbe7e1b715476c0b23fc63a2103b3e4131eda558669aba8fb5e6e05682419376144189b29beb5dee6d7626b4d3385edb0954bffea6c67d8cf622fd51/vendor/pipenv-to-pip", line 11, in main lockfile = json.load(f) File "/app/.heroku/python/lib/python3.6/json/__init__.py", line 299, in load parse_constant=parse_constant, object_pairs_hook=object_pairs_hook, **kw) File "/app/.heroku/python/lib/python3.6/json/__init__.py", line 354, in loads return _default_decoder.decode(s) File "/app/.heroku/python/lib/python3.6/json/decoder.py", line 339, in decode obj, end = self.raw_decode(s, idx=_w(s, 0).end()) File "/app/.heroku/python/lib/python3.6/json/decoder.py", line 357, in raw_decode raise JSONDecodeError("Expecting value", s, err.value) from None json.decoder.JSONDecodeError: Expecting value: line 1 column 2 (char 1) ! Push rejected, failed to compile Python app. ! Push failed Same problem occurres when i'm trying to install modules "gunicorn" and "django-heroku" thgrough "pipenv". But when i'm use just "pip3" it's install as usuall. -
Django: How to dynamically load form to current html page
I have a simple form class MyForm(forms.ModelForm): class Meta: model = Track fields = ['website', 'keyword'] labels = {'website': 'Website URL', 'keyword': 'Keyword'} and a view def track(request): if request.method != 'POST': form = MyForm() else: form = MyForm(request.POST) if form.is_valid(): form.save() return HttpResponseRedirect(reverse('tb_main:index')) context = {'form': form} return render(request, 'tb_main/track.html', context) and html form template(track.html) <form action="{% url 'tb_main:track' %}" method='post'> {% csrf_token %} {% bootstrap_form form %} <button name='submit'>Submit</button> <input type='hidden' name='next' value="{% url 'tb_main:dashboard' %}" /> </form> I would like to be able to dynamically load the form when a user clicks on a button on the homepage without changing the url. I am assuming this could be accomplished using AJAX but I am not sure how to approach this. If i just do an AJAX call to track.html the view functionality won't come with it How can I dynamically load the view & html template to the home page after a button click? I tried <button href="{% url 'tb_main:track' %}">load form</button> but that doesn't work. Would be happy to hear from some of the more experienced developers on how to approach this. Thank you -
Subquery using Django ORM
I have been trying to wrap my head around this but to no avail. The table is as : +--------------------------+-------------+------+-----+---------+----------------+ | Field | Type | Null | Key | Default | Extra | +--------------------------+-------------+------+-----+---------+----------------+ | id | int(11) | NO | PRI | NULL | auto_increment | | | rating | varchar(1) | NO | | NULL | | | product_id | int(11) | NO | MUL | NULL | | | user_id | int(11) | YES | MUL | NULL | | | created_at | datetime(6) | NO | | NULL | | | modified_at | datetime(6) | NO | | NULL | | +--------------------------+-------------+------+-----+---------+----------------+ A user can rate a product multiple times. We do not update the rating but create a new record every time the user rates again for analytics purpose such as to show the trend line etc. Rating is stored as char and has 3 options - G for good, B for bad, N for neutral. So what i am trying to get as output is (just representing in JSON for better readability): { { rating:'G', no_users_rated: 50 }, { rating:'B', no_users_rated: 150 }, { rating:'N', no_users_rated: 20 } } I worked out the raw …