Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Could anyone tell me about the lazy loading and transaction of django?
background like this: data = User.objects.get(pk=1) if data.age > 20: with transaction.atomic(): data.age -=2 data.save() I want to know ,if many process do the code at the same time,it like that,each process would get the data at the same time without transaction,for example ,age is 30. then,one process do the next,make age-2=28 and save. Then the next process do,when it do data.age -=2 ,the data get by data. age ,would be 18 or 20? If it is 20,did it means,the transaction add the wrong place? Or it means , the transaction would not work,because the transaction would add to the data do select lines,and can change and save.but the transaction add with out select line? second question: if I do like this: data = User.objects.get(pk=1) with transaction.atomic(): if data.age > 20: data.age -=2 data.save() this demo,add the transaction before the data.age > 20. For the lazy loading,the sql lines would do when I use it ,such as data.age > 20. But when it readly do sql lines,the transction had add before. So, I want to know,did this demo would add transaction on sql lines? thanks a lot,nice people. -
Override widget templates in Django
I have defined templates in settings.py as following: TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [ os.path.join(BASE_DIR, 'static/html/templates'), ], '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', ], }, }, ] and tree for html/templates is this: when I edit for e.g. change_form.html , the changes are reflected, even when I change any template inside includes that also takes effect. However, when I edit templates inside widgets directory, no changes are reflected. If I edit that inside /django/contrib/admin/templates/admin/widgets that takes effect. How am I supposed to override widgets? -
render video from mongod in django using html5
Here is my two errors-> Error : No video with supported format and MIME type found. & Error : 404 inside my requirement.txt file: pkg-resources==0.0.0 django==1.6.5 django-mongokit==0.2.6 pymongo==2.8 I am using Mongokit- python module for Mongodb. DjangoProject files: inside models.py from django_mongokit import connection from django_mongokit.document import DjangoDocument from mongokit import * import datetime connection = Connection() @connection.register class StoreLargeFiles(Document): __database__ = "test2" __collection__ = "largefiles" structure = { "title" : unicode, } gridfs = { 'files': ['source','template'], 'containers':['images'], } inside user.py urlfile from django.conf.urls import patterns, include, url urlpatterns = patterns('DjangoProject.App.views.user', url(r'^[/]$','User',name='User'), url(r'^/showimg/$','showimg',name='showimg'), ) inside user.py viewfile def showimg(request): instance=connection.test2.largefiles.StoreLargeFiles() for f in instance.fs.images.find(): de = f.read() html = '<video width="400" controls><source src="%s" type="video/mp4"></video>' %de return HttpResponse(html) -
error when installing django in virtualenv with dockerfile
FROM webdevops/base:ubuntu-16.04 RUN apt-get update && apt-get -y upgrade && apt-get install -y --no-install- recommends \ apache2 \ openssh-client \ python3 \ python3-dev \ python3-venv \ python3-psycopg2 \ python3-pip \ pyflakes3 \ pylint3 \ pep8 \ pep257 \ postgresql-client \ libapache2-mod-wsgi-py3 \ && apt-get clean \ && rm -fr /var/lib/apt/lists/* RUN mkdir /var/www/html/hotels-project RUN cd /var/www/html/hotels-project/ \ && python3 -m venv hotels-venv \ && /bin/bash -c "source hotels-venv/bin/activate" RUN pip install 'django<2.0' RUN pip install requests RUN pip install psycopg2 show message: ERROR: Service 'apache-python' failed to build: The command '/bin/sh -c pip install 'django<2.0'' returned a non-zero code: 127 -
deploy django-mysql application to windows server 2012 iis
i already deployed my django application to windows 2012 server iis succesfully, it works fine with mysql in local, but it showing error in windows server iis production as raise ImproperlyConfigured("Error loading MySQLdb module: %s" % e) ImproperlyConfigured: Error loading MySQLdb module: No module named MySQLdb i installed python-mysql package, django everything.still i am getting error Thanks -
Install hstore extension for django tests
I am trying to install the hstore extension before running django tests. For that, I have overridden the default DiscoverRunner's setup_databases method. However, the extension is not installed & the tests show this error django.db.utils.ProgrammingError: type "hstore" does not exist Here's my code to override the default discover runner. settings.py TEST_RUNNER = 'project.tests.CustomDiscovererRunner' tests.py from django.db import DEFAULT_DB_ALIAS, connections from django.test.runner import DiscoverRunner class CustomDiscovererRunner(DiscoverRunner): def setup_databases(self, **kwargs): result = super().setup_databases(**kwargs) connection = connections[DEFAULT_DB_ALIAS] cursor = connection.cursor() cursor.execute('CREATE EXTENSION IF NOT EXISTS HSTORE') return result -
How to change JSON object structure into JSON Array Structure for highcharts
I want to change this JSON object structure [ { "tahun": "2010", "apel": 100, "pisang": 200, "anggur": 300, "nanas": 400, "melon": 500 }, { "tahun": "2011", "apel": 145, "pisang": 167, "anggur": 210, "nanas": 110, "melon": 78 } [ into this JSON Array Structure for my highchart in django, [ ["2010",100], ["2010",200], ["2010",300], ["2010",400], ["2010",500], ["2011",145], ["2011",167], ["2011",210], ["2011",110], ["2011",78] ] or if u have any method like using AJAX it will be very helpful -
ConnectionAborted Error: [WinError 10053] in Django Service
I am working on Login,Registration of users through my Chrome extension. While registration in the extension, Django service is stopping abruptly and throughing some exceptions and errors. The error Message is as follows: " C:\Users\Anusha\Desktop\DjangoServices>python manage.py runserver Performing system checks... System check identified no issues (0 silenced). March 08, 2018 - 11:15:04 Django version 2.0.1, using settings 'hello.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. [08/Mar/2018 11:15:44] "POST /polls/? HTTP/1.1" 200 21 Traceback (most recent call last): File "C:\Users\Anusha\AppData\Local\Programs\Python\Python36-32\lib\wsgiref\handlers.py", line 138, in run self.finish_response() File "C:\Users\Anusha\AppData\Local\Programs\Python\Python36-32\lib\wsgiref\handlers.py", line 180, in finish_response self.write(data) File "C:\Users\Anusha\AppData\Local\Programs\Python\Python36-32\lib\wsgiref\handlers.py", line 274, in write self.send_headers() File "C:\Users\Anusha\AppData\Local\Programs\Python\Python36-32\lib\wsgiref\handlers.py", line 332, in send_headers self.send_preamble() File "C:\Users\Anusha\AppData\Local\Programs\Python\Python36-32\lib\wsgiref\handlers.py", line 255, in send_preamble ('Date: %s\r\n' % format_date_time(time.time())).encode('iso-8859-1') File "C:\Users\Anusha\AppData\Local\Programs\Python\Python36-32\lib\wsgiref\handlers.py", line 453, in _write result = self.stdout.write(data) File "C:\Users\Anusha\AppData\Local\Programs\Python\Python36-32\lib\socketserver.py", line 775, in write self._sock.sendall(b) ConnectionAbortedError: [WinError 10053] An established connection was aborted by the software in your host machine [08/Mar/2018 11:15:44] "POST /polls/? HTTP/1.1" 500 59 ---------------------------------------- Exception happened during processing of request from ('127.0.0.1', 52297) Traceback (most recent call last): File "C:\Users\Anusha\AppData\Local\Programs\Python\Python36-32\lib\wsgiref\handlers.py", line 138, in run self.finish_response() File "C:\Users\Anusha\AppData\Local\Programs\Python\Python36-32\lib\wsgiref\handlers.py", line 180, in finish_response self.write(data) File "C:\Users\Anusha\AppData\Local\Programs\Python\Python36-32\lib\wsgiref\handlers.py", line 274, in write self.send_headers() File "C:\Users\Anusha\AppData\Local\Programs\Python\Python36-32\lib\wsgiref\handlers.py", line 332, in send_headers self.send_preamble() File … -
How to I Fix django.utils.datastructures.MultiValueDictKeyError: in django
when I try to create a new instance of an Employee I get an error: django.utils.datastructures.MultiValueDictKeyError: "'bio'" When I print this line print(request.data) within the post method in 'EmployeeAddView` class I get: <QueryDict: {'joining_date': ['2018-03-04'], 'designation': ['1'], 'csrfmiddlewaretoken': ['5AeZ7lFOE2Z5j8cPNNZtygh208Esw65tvf5fzka56nCAj1oUFWCR3fcNHuOok2JK'], 'bio.marital_status': ['1'], 'bio.preferred_language': ['English'], 'tax_id_number': ['333333333ed'], 'bio.birthday': ['2018-03-04'], 'bio.user.first_name': ['Jack'], 'department': ['2'], 'bio.user.last_name': ['Sparrow'], 'bio.phone_number': ['9999999'], 'bio.main_id_type_no': ['459opppp'], 'bio.id_type': ['1'], 'bio.gender': ['1'], 'account_number': ['qwwwwwwww3r3']}> Internal Server Error: /hr/employee_add/ Traceback (most recent call last): File "/usr/local/lib/python3.5/dist-packages/django/utils/datastructures.py", line 83, in __getitem__ list_ = super(MultiValueDict, self).__getitem__(key) KeyError: 'bio' I have this at views.py class EmployeeAddView(generics.CreateAPIView): queryset=Employee.objects.all() serializer_class=EmployeeSerializer def post(self, request, format=None): print(request.data) designation = Group.objects.get(id=self.request.data['designation'],) department = Group.objects.get(id=self.request.data['department'],) bio = Bio.objects.get(id=self.request.data['bio'],) employee = Employee.objects.create( tax_id_number=request.data['tax_id_number'], account_number=request.data['account_number'], joining_date=request.data['joining_date'], designation =designation, department =department, bio=bio, ) return Response(status=status.HTTP_201_CREATED) Then I have created a serializer like this: # Nest Bio With User seriializer class EmployeeSerializer(serializers.ModelSerializer): # TODO: Define serializer fields here bio = BioSerializer() #user = UserSerializer() class Meta: model = Employee # fields = ['user','tax_id_number','account_number','joining_date','designation','department','gender','marital_status','id_type','birthday','ethnicity','preferred_language','phone_number','em_contact','address'] fields = '__all__' -
No 'Access-Control-Allow-Origin' header Javascript and Django
Here is my Django view @method_decorator(csrf_exempt,name='dispatch') def get_mail_by_id(request): if request.method == 'POST': try: # import pdb;pdb.set_trace() message_id = request.POST['message_id'] email = Email.objects.filter(message_id=message_id) if email.exists(): email = email[0] mail = email.mail_message return JsonResponse({'status':True,'data':mail}) else: return JsonResponse({'status':False,'data':None}) except Exception as e: print e return JsonResponse({'status':False,'data':None}) And here is my POST request $.post('http://127.0.0.1:8000/mail/get_mail_by_id/',{'message_id':message_id}) .done(function(response){ if(response.status){ console.log(response) $('.mail_message').text(response.data) } }); Problem is when I post a request to Django view it runs fine and Django view sends back response but on front end I get the following error: Failed to load http://127.0.0.1:8000/mail/get_mail_by_id/: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8000' is therefore not allowed access. I have also added {% csrf_token %} in my jinja template. -
Setting SECURE_HSTS_SECONDS can irreversibly break your site?
I'm wanting to implement SECURE_HSTS_SECONDS to my Django settings for extra security - however the warning from the Django docs is making me abit scared so I want some clarification. Here is what is says: SECURE_HSTS_SECONDS Default: 0 If set to a non-zero integer value, the SecurityMiddleware sets the HTTP Strict Transport Security header on all responses that do not already have it. Warning: Setting this incorrectly can irreversibly (for some time) break your site. Read the HTTP Strict Transport Security documentation first. What has to happen for it to "break my site"? I read the HTTP Strict Transport Security documentation first and it didn't make it any clearer. -
Is it possible to automate extraction and inlining of critical css with Django using gulp-critical or webpack?
I'm new to programming and I've recently built a website using Django + Bootstrap 4 and was trying to improve my pagespeed on Google SEO Google Page Speed Insights Page Speed Insights suggested using Critical and this led me to discover front-end tools such as Gulp and Webpack. I've read on tutorials on how to use Critical with Webpack here but the problem my django templates are fragmented to keep things organized using {% block content %}. This in turn hinders using the HTML Webpack Plugin + Critical combination to extract the critical css and inline it. Any suggestions or is my only option to manually extract my site's critical css? Hoping for a step-by-step answer or maybe a link to a website to guide me as I am relatively new to all this. Thanks in advance! -
I am getting a module error in my django project
I am building a new django application and for some reason I am getting an error while i am trying access the models from the models.py file from the forms.py file. Here is the error: File "/Users/omarjandali/Desktop/MySplit/mysplit/general/forms.py", line 13, in <module> from models import * ModuleNotFoundError: No module named 'models' Yet I have the general app added to the installed settings. and I have all the models saved. Why is it saying that the module is not there... I am going blank. I know it is a simple answer but for some reason I cant figure it out. here is the forms.py file: # all model imports related to this project from models import * class LoginForm(forms.Form): username = forms.CharField(max_length=20) password = forms.CharField(max_length=20, widget=forms.PasswordInput) here is the models.py file: from django.db import models from django.contrib.auth.models import User, UserManager from localflavor.us.models import USStateField, USZipCodeField # the following is the users profile model class Profile(models.Model): # users basic info user = models.ForeignKey(User, on_delete=models.CASCADE) f_name = models.CharField(max_length=25, default='first') l_name = models.CharField(max_length=25, default='last') bio = models.CharField(max_length=220, default='bio') # users location street = models.CharField(max_length=200, default='street address') city = models.CharField(max_length=100, default='city') state = USStateField(default='CA') zip_code = USZipCodeField(default=12345) # users other profile info phone = models.IntegerField(default="000-ooo-oooo") dob … -
django-wiki: how to list all articles under root article
I am a newbie in Django and am currently building a site. I have downloaded django-wiki ver 0.4a3 to have a wiki app for my site. Everything works fine, out-of-the-box. But instead of showing the root article as the main page, how can I show a list of all articles under the root article, so users can just click on any child article to open up that article? At the moment, users have to click a menu option to browse up one level or to browse at the current level to have a listing of all articles at that given level. I find this rather tedious. I rather have an "Windows Explorer tree-and-branch-like" navigation, e.g., root |_child 1 | |_child 1.1 | |_child 1.2 | |_child 2 | |_child 2.1 | |_child 2.1.1 | |_child 3 Please note I am asking how to get a list all of articles under the root article, not how to create a template to implement the tree-and-branch articles navigator. Once I know how to get a listing of all articles, I think I can implement the necessary HTML and CSS to have that kind of navigator. I appreciate any pointers. P.S. I have previously … -
Loop through items into Django 1.8 template
I have this method: def profile(request): parsedData = [] if request.method == 'POST': username = request.POST.get('user') req = requests.get('https://api.github.com/users/' + username + '/repos') jsonList = [] jsonList=req.json() userData = {} for data in jsonList: userData['html_url'] = data['html_url'] userData['created_at'] = data['created_at'] userData['updated_at'] = data['updated_at'] userData['forks_count'] = data['forks_count'] parsedData.append(userData) return render(request, 'app/profile.html', {'data': parsedData}) This code looks into an url like this githubtraining As You can see, the response contains lots of repositories, however, not every github user has more than 1 repo. Anyways, on my html view I have this: <div class="table-responsive"> <table class="table table-bordered table-hover table-striped tablesorter"> <thead> <tr> <th class="header"> Url <i class="icon-sort"></i></th> <th class="header"> Created at <i class="icon-sort"></i></th> <th class="header"> Updated at <i class="icon-sort"></i></th> <th class="header"> Forks count <i class="icon-sort"></i></th> </tr> </thead> <tbody> {% for key in data %} <tr> <td>{{ key.html_url }}</td> <td>{{ key.created_at }}</td> <td>{{ key.updated_at }}</td> <td>{{ key.forks_count }}</td> </tr> {% endfor %} </tbody> </table> </div> What happens then? Well, right now, if, for instance, I query the githubtraining user to see it's repos, it shows only the last one, on that and every other user, so, what am I doing wrong here? The loop is there, what am I missing? -
How do I create a Team Leader/Group Leader in Django?
I'm new(this is my first project) to web development. I'm creating an internal data management for the company i work for. We have different departments(like r&d, product development, etc) which I have instantiated as objects via Django admin. I have created employees as normal Users in django admin. I would like to know how I can create a model/anything which can tell me the department manager. -
Django Login Form Input Fields not showing up
working on a Django Web project for a class. Created an own template for the login page, that looks like this {% extends 'thirdauth/base.html' %} {% block content %} <h2>Login</h2> <div class="login-form"> <form method="post" action="{% url 'thirdauth:login' %}"> {{form.as_p}} {% csrf_token %} <input type="hidden" name="next" value="{{ next }}" /> <p><input type="submit" value="Login"></p> </form> </div> <br> <p><strong>-- OR --</strong></p> <a href="{% url 'thirdauth:social:begin' 'github' %}">Login with GitHub</a><br> {% endblock %} The only problem that I face is that the input fields for user and password + labels are not showing up when the sites initially loads. When I click on the Login button, the fields appear and I can enter everything and it works fine... Here is the urls.py from django.conf.urls import url, include from django.contrib import admin from django.contrib.auth import views as auth_views from . import views urlpatterns = [ url(r'^login/$', auth_views.login, name='login'), url(r'^logout/$', auth_views.logout, name='logout'), url(r'^auth/', include('social_django.urls', namespace='social')), url(r'^admin/', admin.site.urls), url(r'^accounts/login/$', views.authentication, name='authentication'), ] I'm thankful for help, I think it is just a small stupid mistake from me, but I'm not able to find it, most help on the internet focuses on self defined forms. -
Trying to push Django app to Heroku - error around anaconda?
I'm trying to push a Django app that uses NLTK and Scikit-learn. I have put all the relevant dependencies in the requirements.txt file, but I keep getting this error. Any suggestions? remote: -----> Installing requirements with pip remote: Collecting alabaster==0.7.10 (from -r /tmp/build_e87edffdf382e76739e44cf354aacd2b/requirements.txt (line 1)) remote: Downloading alabaster-0.7.10-py2.py3-none-any.whl remote: Collecting anaconda-client==1.6.5 (from -r /tmp/build_e87edffdf382e76739e44cf354aacd2b/requirements.txt (line 2)) remote: Could not find a version that satisfies the requirement anaconda-client==1.6.5 (from -r /tmp/build_e87edffdf382e76739e44cf354aacd2b/requirements.txt (line 2)) (from versions: 1.1.1, 1.2.2) remote: No matching distribution found for anaconda-client==1.6.5 (from -r /tmp/build_e87edffdf382e76739e44cf354aacd2b/requirements.txt (line 2)) remote: ! Push rejected, failed to compile Python app. remote: remote: ! Push failed remote: Verifying deploy... remote: remote: ! Push rejected to XXX. remote: To https://git.heroku.com/secure-mountain-49046.git ! [remote rejected] master -> master (pre-receive hook declined) error: failed to push some refs to 'https://git.heroku.com/XXX.git' -
Browser side cookie issue
I am creating a cookie to store some data( how many times the user visited a page)in the client side. Here I am trying to understand the client side cookie. I am able to achieve the desired result using a server side cookie. But in this client side cookie set up every time I visit the page the cookie count is not increasing. Below is the cookie code in my Django view, Please help me understand what I am doing wrong. def index(request): if 'visited' in request.COOKIES: visited = int(request.COOKIES['visited']) visited += 1 response = render(request,'index.html',context={'visited':visited}) else : response = render(request,'index.html',context={'visited':0}) response.set_cookie('visited',1) return response -
How to setup Django inside virtualenv on Windows?
Any Windows python developers here? I created a virtualenv, activated it and installed django. If I run pip3 list, it shows Django (2.0.3) as installed. The problem is when I try and use django, it never works, it just returns "no module django." When I try pip3 install django again, it says it's already installed at myname\envs...\site-packages. But when I use the django command it never looks at this path, it looks at appdata/local/programs/python/python36-32/python.exe (i.e. not the virtualenv but the python installation itself). Anyone have any ideas? -
Get only decimal django-money
I've instaled django-money module to a project. When try to render in a template, the money file is rendered: $100.00 Is there any method to only render the decimal value without the symbol? Such as: 100.00 -
Django 2.0 SQLite3 to MySQL loaddata error: "The database backend does not accept 0 as a value for AutoField."
I am attempting to transfer a database from sqlite to mysql. I've googled this error and found Stack Overflow matches, but havent seen how to debug/identify the offending "0 value AutoField" fields. I've tried skirting the issue by dumping/loading different tables, but all seem to generate the same error. I've attempted appending -e contenttypes, --natural-foreign, and --natural-primary to my datadump command, e.g., python manage.py dumpdata -e contenttypes --natural-foreign --natural-primary --indent=4 > datadump_3-7-18.json After running python manage.py loaddata --traceback datadump_3-7-18.json It produces the traceback error: (venv) ➜ bikerental git:(additional-features-march) ✗ python manage.py loaddata --traceback datadump_3-7-18.json Traceback (most recent call last): File "manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "/rentals/venv/lib/python3.6/site-packages/django/core/management/__init__.py", line 371, in execute_from_command_line utility.execute() File "/rentals/venv/lib/python3.6/site-packages/django/core/management/__init__.py", line 365, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/rentals/venv/lib/python3.6/site-packages/django/core/management/base.py", line 288, in run_from_argv self.execute(*args, **cmd_options) File "/rentals/venv/lib/python3.6/site-packages/django/core/management/base.py", line 335, in execute output = self.handle(*args, **options) File "/rentals/venv/lib/python3.6/site-packages/django/core/management/commands/loaddata.py", line 72, in handle self.loaddata(fixture_labels) File "/rentals/venv/lib/python3.6/site-packages/django/core/management/commands/loaddata.py", line 113, in loaddata self.load_label(fixture_label) File "/rentals/venv/lib/python3.6/site-packages/django/core/management/commands/loaddata.py", line 177, in load_label obj.save(using=self.using) File "/rentals/venv/lib/python3.6/site-packages/django/core/serializers/base.py", line 205, in save models.Model.save_base(self.object, using=using, raw=True, **kwargs) File "/rentals/venv/lib/python3.6/site-packages/django/db/models/base.py", line 759, in save_base updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields) File "/rentals/venv/lib/python3.6/site-packages/django/db/models/base.py", line 842, in _save_table result = self._do_insert(cls._base_manager, using, fields, update_pk, raw) File "/rentals/venv/lib/python3.6/site-packages/django/db/models/base.py", line 880, … -
Parsing JSON Github API - Django 1.8
I have this in my views.py: def profile(request): parsedData = [] if request.method == 'POST': username = request.POST.get('user') req = requests.get('https://api.github.com/users/' + username + '/repos') jsonList = [] jsonList.append(req.json()) userData = {} data = ['owner'] for data in jsonList: userData['html_url'] = data['owner'][0]['html_url'] userData['created_at'] = data['created_at'] userData['updated_at'] = data['updated_at'] userData['forks_count'] = data['forks_count'] parsedData.append(userData) return render(request, 'app/profile.html', {'data': parsedData}) This throws me: TypeError at /app/profile/ list indices must be integers, not str This is an example JSON returned by /repos on Github: { "id": 77549474, "name": "acp", "full_name": "kkoci/acp", "owner": { "login": "kkoci", "id": 3047897, "avatar_url": "https://avatars0.githubusercontent.com/u/3047897?v=4", "gravatar_id": "", "url": "https://api.github.com/users/kkoci", "html_url": "https://github.com/kkoci", "followers_url": "https://api.github.com/users/kkoci/followers", "following_url": "https://api.github.com/users/kkoci/following{/other_user}", "gists_url": "https://api.github.com/users/kkoci/gists{/gist_id}", "starred_url": "https://api.github.com/users/kkoci/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/kkoci/subscriptions", "organizations_url": "https://api.github.com/users/kkoci/orgs", "repos_url": "https://api.github.com/users/kkoci/repos", "events_url": "https://api.github.com/users/kkoci/events{/privacy}", "received_events_url": "https://api.github.com/users/kkoci/received_events", "type": "User", "site_admin": false }, "private": false, "html_url": "https://github.com/kkoci/acp", "description": null, "fork": true, "url": "https://api.github.com/repos/kkoci/acp", "forks_url": "https://api.github.com/repos/kkoci/acp/forks", "keys_url": "https://api.github.com/repos/kkoci/acp/keys{/key_id}", "collaborators_url": "https://api.github.com/repos/kkoci/acp/collaborators{/collaborator}", "teams_url": "https://api.github.com/repos/kkoci/acp/teams", "hooks_url": "https://api.github.com/repos/kkoci/acp/hooks", "issue_events_url": "https://api.github.com/repos/kkoci/acp/issues/events{/number}", "events_url": "https://api.github.com/repos/kkoci/acp/events", "assignees_url": "https://api.github.com/repos/kkoci/acp/assignees{/user}", "branches_url": "https://api.github.com/repos/kkoci/acp/branches{/branch}", "tags_url": "https://api.github.com/repos/kkoci/acp/tags", "blobs_url": "https://api.github.com/repos/kkoci/acp/git/blobs{/sha}", "git_tags_url": "https://api.github.com/repos/kkoci/acp/git/tags{/sha}", "git_refs_url": "https://api.github.com/repos/kkoci/acp/git/refs{/sha}", "trees_url": "https://api.github.com/repos/kkoci/acp/git/trees{/sha}", "statuses_url": "https://api.github.com/repos/kkoci/acp/statuses/{sha}", "languages_url": "https://api.github.com/repos/kkoci/acp/languages", "stargazers_url": "https://api.github.com/repos/kkoci/acp/stargazers", "contributors_url": "https://api.github.com/repos/kkoci/acp/contributors", "subscribers_url": "https://api.github.com/repos/kkoci/acp/subscribers", "subscription_url": "https://api.github.com/repos/kkoci/acp/subscription", "commits_url": "https://api.github.com/repos/kkoci/acp/commits{/sha}", "git_commits_url": "https://api.github.com/repos/kkoci/acp/git/commits{/sha}", "comments_url": "https://api.github.com/repos/kkoci/acp/comments{/number}", "issue_comment_url": "https://api.github.com/repos/kkoci/acp/issues/comments{/number}", "contents_url": "https://api.github.com/repos/kkoci/acp/contents/{+path}", "compare_url": "https://api.github.com/repos/kkoci/acp/compare/{base}...{head}", "merges_url": "https://api.github.com/repos/kkoci/acp/merges", "archive_url": "https://api.github.com/repos/kkoci/acp/{archive_format}{/ref}", "downloads_url": "https://api.github.com/repos/kkoci/acp/downloads", "issues_url": "https://api.github.com/repos/kkoci/acp/issues{/number}", "pulls_url": "https://api.github.com/repos/kkoci/acp/pulls{/number}", "milestones_url": "https://api.github.com/repos/kkoci/acp/milestones{/number}", "notifications_url": "https://api.github.com/repos/kkoci/acp/notifications{?since,all,participating}", … -
Django search "DoesNotExist"
I'm using Django to build a website for a football club, which contains many blog articles. I'm trying to include a search bar, but I can't make it work. When submitting the search term, the following error is shown: DoesNotExist at /web/search/ Articulo matching query does not exist. Here is my code: views.py def search(request): query = request.GET.get('q', '') if query: try: qset = ( Articulo(titulo__icontains=query) | Articulo(cuerpo_icontains=query) ) results = Articulo.objects.filter(qset).distinct() except Articulo.DoesNotExist: results = None else: results = [] return render_to_response('web/buscar.html',{"results": results, "query": query}) index.html <div id="busqueda" class="row"> <div class="col-md-12"> <span id="cruz" class="fas fa-times fa-2x"></span> <form method="GET" action="/web/search/" class="form my-2 my-lg-0"> <input id="searchBox" value="{{ query|escape }}" class="form-control mr-sm-2" type="text" name="q" placeholder="Buscar" aria-label="Buscar"> <button class="btn btn-outline-success my-2 my-sm-0" type="submit">Buscar</button> </form> </div> </div> urls.py url(r'^search/$', search), models.py class Articulo(models.Model): """Un artículo de la página""" id = models.AutoField(primary_key=True) titulo = models.CharField(max_length=100) slug = models.SlugField(unique=True, default="") CATEGORIAS = ( ('Primera y Sub 21', 'Primera y Sub 21'), ('Inferiores', 'Inferiores'), ('Básquet', 'Básquet'), ('Hockey', 'Hockey'), ('Gurises', 'Gurises'), ('Generales', 'Generales'), ('Institucionales', 'Institucionales'), ('Senior', 'Senior'), ) categoria = models.CharField( max_length=200, choices=CATEGORIAS ) cuerpo = RichTextField() fecha_hora= models.DateTimeField() foto = models.ImageField() url_video = models.CharField(help_text='Url del video de facebook (opcional). Para obtener el link, ir al video, apretar … -
Should i do db_index for charFields that I use in search?
I have the following that i use in a search bar: Model1 subject = models.CharField(max_length =200) last_updated = models.DateTimeField(auto_now_add = True, null=True) created_at = models.DateTimeField(auto_now_add = True,db_index = True ) Model2 first_name = models.CharField(max_length = 20) last_name = models.CharField(max_length = 20) full_name = models.CharField(max_length=40, null=True, blank=True ) I use full_name and subject charfield in a seach bar. the search bar works by autocomplete, where the results are filtered everytime a character is added to the search. Will db_index=True for the charfields help for a quicker search? Thank you:)