Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Differences between RESTful API and urlpatterns router in Django
Am new to web developpement and wonderinf the differencew between: Django Restful API and standard Django URL routers urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^$', views.index, name='Index'), url(r'^getvalue/$', views.get_points, name='Get Points'), url(r'^putvalue/$', views.insert_points, name='Insert Points'), ] What are the benefits of setting Django restful API when interacting with Javascript components since both are JSON sending URL ? -
Django : Authenticate user login return none
I'm trying to create login form. In login.html when user type name and password, then it become user object. If there is return than it should redirect to loggedin.html and if else it should redirect to invaild.html. However it keeps return none. This is my setting.py #Authentication backends AUTHENTICATION_BACKENDS = ( 'django.contrib.auth.backends.ModelBackend', ) #added for login authentification LOGIN_REDIRECT_URL = 'home' urls.py #user auth url url(r'^login/$', auth_views.login, {'template_name': 'forum/login.html'}, name='login'), url(r'^auth/$', views.auth_view, name='auth'), url(r'^logout/$', auth_views.logout, {'template_name': 'forum/logout.html'}, name='logout'), url(r'^loggedin/$', views.loggedin, name='loggedin'), Model.py from django.contrib import auth from django.contrib.auth import logout, authenticate from django.http.response import HttpResponseRedirect from django.shortcuts import render from django.template import context from django.template.context_processors import request, csrf from forum.models import Article def login(request): c = {} c.update(csrf(request)) return render(request, 'forum/login.html', c) def auth_view(request): name = request.POST.get('name', '') password = request.POST.get('password', '') user = auth.authenticate(username=name, password=password) print(user) if user is not None: auth.login(request, user) return HttpResponseRedirect('/loggedin.html') else: return HttpResponseRedirect('/invalid.html') def base(request): return render(request, 'forum/base.html', context) def loggedin(request): return render(request, 'forum/loggedin.html', {'name': request.user.name}) def logout(request): return render(request, 'forum/logout.html') login.html <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Insert title here</title> </head> <body> {% block title %}Login{% endblock %} {% if from.errors %} not valid name or password {% endif %} {% block content %} … -
django jeft join query
I have following models: class TestCaseStatus(models.Model): name = models.CharField(default='n/a', max_length=50) def __str__(self): return self.name class TestCase(models.Model): id = models.CharField(unique=True, max_length=100, primary_key=True) name = models.CharField(default='n/a', max_length=200) def __str__(self): return self.name class TestRun(models.Model): test_id = models.ForeignKey(TestCase) run_id = models.CharField(max_length=100, default='0') datetime = models.DateTimeField() status = models.ForeignKey(TestCaseStatus) messages = models.CharField(default='n/a', max_length=500) def __str__(self): return self.run_id, self.test_id, self.status I want to execute following SQL query: select a.test_id_id, a.status_id, b.status_id from runscompare_testrun as a left join runscompare_testrun as b on a.test_id_id = b.test_id_id where a.run_id = 1 and b.run_id=2 SQL output: I assume that there is a django way to do it to avoid using raw() call, but I can't seems to find it. -
QuerySet to JSON with nested objects
I have 2 classes EligibilityCriteria, Scholarship. Scholarship references EligibilityCriteria as a foreign key. class EligibilityCriteria(models.Model): criteria_id = models.AutoField(primary_key=True) gender = models.ForeignKey(Gender, null=True, blank=True) minimum_age = models.IntegerField(blank=True, null=True) maximum_age = models.IntegerField(blank=True, null=True) eligibility_colleges = models.TextField(blank=True, null=True) state = models.ForeignKey(State, blank=True, null=True, on_delete=SET_NULL) caste = models.ForeignKey(Caste, blank=True, null=True, on_delete=SET_NULL) religion = models.ForeignKey(Religion, blank=True, null=True, on_delete=SET_NULL) education_level = models.ForeignKey(Education_level, blank=True, null=True, on_delete=SET_NULL) minimum_percentage = models.CharField(max_length=100, blank=True, null=True) income_ceiling = models.IntegerField(blank=True, null=True) other_criteria = models.TextField(blank=True, null=True) def __unicode__(self): return str(self.education_level) + "_" + str(self.state) + "_" + str(self.gender) class Scholarship(models.Model): scholarship_id = models.AutoField(primary_key=True) name = models.CharField(max_length=500) description = models.TextField() eligibility_criteria = models.ForeignKey(EligibilityCriteria, null=True, on_delete=models.CASCADE) scholarship_category = models.ForeignKey(ApplicantCategory, blank=False, null=False, on_delete=CASCADE) end_date = models.DateTimeField(null=True, blank=True) availability_count = models.IntegerField(null=True, blank=True) website_link = models.CharField(max_length=500, blank=True, null=True) amount = models.CharField(max_length=100, blank=True, null=True) selection_procedure = models.TextField(blank=True, null=True) def __unicode__(self): return str(self.name) Now when I convert QuerySet of Scholarships to json, the values of EligibilityCriteria are missing: def get_all_scholarships(request): scholarships_list = Scholarship.objects.all() # return JsonResponse(scholarships_list, safe=False) response_obj = serializers.serialize('json', scholarships_list, fields=('name','description', 'eligibility_criteria', 'scholarship_category', 'end_date', 'availability_count', 'website_link', 'amount', 'selection_procedure')) return django.http.HttpResponse(__set.encode('utf-8'), content_type='application/json') How do I convert QuerySet of Scholarship objects to json in such a way that even values within eligibility criteria are visible? -
Ace editor getValue newline format?
Ace editor only accept (\n) setting: You can see setValue's content has \n and \" tag. var editor1 = ace.edit("editor1"); editor1.setTheme("ace/theme/twilight"); editor1.getSession().setMode("ace/mode/python"); editor1.setFontSize(15); editor1.setValue("def main():\n # Your code goes here\n\nif __name__ == \"__main__\":\n main()"); But when I use editor1.getValue()to get value from ace editor. It will get non \n tag like below: def main(): # Your code goes here if __name__ == "__main__": main() But How to use non \n's value to editor1.setValue again. I want to implement the function that can modify old code store in database. The code will store editor1.getValue() into database. So it will be wrong to editor1.setValue( def main(): # Your code goes here if __name__ == "__main__": main() ) How to solve this? Thank you very much. -
Cant Access Django app at Heroku with super user-This account is inactive
I uploaded my apps to heroku hosting. (first time) Created super user with: heroku run python manage.py createsuperuser got a message: Superuser created successfully. then I am running heroku ps:scale web=1 and heroku open but when I input my login info at my site I get from django This account is inactive. What is the problem? I is my first deployment so sorry if I missed something obvious. -
Is there a way to add data to a Response object?
I want to subclass a view from a third party library, by calling super and then adding some extra data to the Response object from django-rest-framework. However, I'm not sure how that can be done, as all examples show data being wrapped in the Response object only on instantiation. If further context is needed: I'm trying to do so with the ObtainJSONWebToken view of django-rest-framework-jwt, in an effort to add user data. Right now the Response that view adds only contains the JWT. -
Python QuerySet is not iterable or serializable
I have a dictionary of String, QuerySet. How do I convert it to json? How do I iterate over QuerySet? Any library django provides that simplifies this? P.S Forgive my bad question forming, have been up since last 24 hours, and its getting grumpy here. -
How to serve static index with Apache and mod_wsgi
So I'm using Apache and mod_wsgi to serve a django webapp. My client is a single-page application, which talks to the django back-end. Since the actual index is a static html file, I would like it so that when my user navigates to '/', then Apache serves them my static index.html, but when they visit '/foo/' or '/bar/', then they get dynamic content from the django backend. Relevant apache conf: Alias /static /path/to/static <Directory /path/to/static> Require all granted </Directory> <Directory /path/to/django/site> <Files wsgi.py> Require all granted </Files> </Directory> WSGIDaemonProcess sitename python-home=/path/to/env python-path=/path/to/django WSGIProcessGroup sitename WSGIScriptAlias / /path/to/sitename/wsgi.py WSGIPassAuthorization On However, if I try to Alias / /path/to/static/ then django doesn't get to do its thing, since it clashes with WSGIScriptAlias / /path/to/sitename/wsgi.py. Is there any way to make Apache serve a static file in what would otherwise be django's namespace? -
Viewing a different templates based on if object exists
I have a link as part of my main nav (base.html) that leads to a TempalateView for an object called CompanyProfile. I am trying to have this link do one of two things based on if CompanyProfile Object exists: If the CompanyProfile Object exists, use the CompanyProfileView(TemplateView). If the CompanyProfile Object does not exist, use the CompanyProfileCreate(generic.CreateView). This object gets displayed at /accounts/companyprofile. Is this possible? I'm pretty sure I shouldn't be building the view logic into the template here but I cannot figure out how to do it otherwise. urls.py from django.conf.urls import url, include from django.contrib import admin from company_account.views import * from company_account import views urlpatterns = [ url(r'accounts/companyprofile/create/$', CompanyProfileCreate.as_view(), name='createprofile'), url(r'accounts/companyprofile/(?P<pk>[0-9]+)/$', CompanyProfileUpdate.as_view(), name='updateprofile'), url(r'^accounts/companyprofile/$', CompanyProfileView.as_view(), name='companyprofile'), ] views.py from django.views.generic.edit import CreateView, UpdateView, DeleteView from company_account.models import CompanyProfile from company_account.forms import CompanyProfileForm from . import models from django.core.urlresolvers import reverse_lazy class CompanyProfileCreate(generic.CreateView): model = CompanyProfile form_class = CompanyProfileForm template_name = 'accounts/companyprofile_form.html' success_url = reverse_lazy('companyprofile') class CompanyProfileUpdate(generic.UpdateView): model = CompanyProfile form_class = CompanyProfileForm template_name = 'accounts/companyprofile_form.html' success_url = reverse_lazy('companyprofile') class CompanyProfileView(generic.TemplateView): template_name = 'accounts/companyprofile.html' def get_context_data(self, **kwargs): context = super(CompanyProfileView, self).get_context_data(**kwargs) context['company_profiles'] = CompanyProfile.objects.all return context Model.py from __future__ import unicode_literals from django.db import models from django.core.urlresolvers … -
Django Form Validation using build it is_valid()
Traceback: File "/usr/local/lib/python3.5/site-packages/django/core/handlers/exception.py" in inner 39. response = get_response(request) File "/usr/local/lib/python3.5/site-packages/django/core/handlers/base.py" in _get_response 187. response = self.process_exception_by_middleware(e, request) File "/usr/local/lib/python3.5/site-packages/django/core/handlers/base.py" in _get_response 185. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/usr/local/lib/python3.5/site-packages/django/contrib/auth/decorators.py" in _wrapped_view 23. return view_func(request, *args, **kwargs) File "/app/views.py" in create 64. if not create_form.is_valid(): File "/usr/local/lib/python3.5/site-packages/django/forms/forms.py" in is_valid 169. return self.is_bound and not self.errors File "/usr/local/lib/python3.5/site-packages/django/forms/forms.py" in errors 161. self.full_clean() File "/usr/local/lib/python3.5/site-packages/django/forms/forms.py" in full_clean 372. self._post_clean() File "/usr/local/lib/python3.5/site-packages/django/forms/models.py" in _post_clean 398. self.instance.full_clean(exclude=exclude, validate_unique=False) Exception Type: TypeError at /create Exception Value: full_clean() missing 1 required positional argument: 'self' So I'm using the built in Django forms.ModelForm and then calling form.is_valid() in views.py and am getting this error and for the life of me have no idea why. -
Application error on Django heroku (from SQLlite to Postgres)
I am deploying first time my django project on heroku . I developed my apps with sqlite. Followed this tutorial to deploy https://djangogirls.gitbooks.io/django-girls-tutorial-extensions/content/heroku/#pick-an-application-name Build is successful. When I do database migration I get (rent_unit_venv) C:\Users\PAPA\DEV\rent_unit\src>heroku run python manage.py migrate Running python manage.py migrate on liberte... up, run.9683 (Free) /app/.heroku/python/lib/python2.7/site-packages/csvimport/models.py:26: RemovedInDjango19Warning: django.db.models.get_models is deprecated. allmodels = models.get_models() /app/.heroku/python/lib/python2.7/site-packages/django/db/models/init.py:55: RemovedInDjango19Warning: The utilities in django.db.models.loading are deprecated in favor of the new application loading system. from . import loading Operations to perform: Synchronize unmigrated apps: easy_pdf, dal, crispy_forms, staticfiles, csvimport, messages, django_tables2, django_filters, concurrency, author, wkhtmltopdf, ajax_select, dal_select2, psycopg2 Apply all migrations: registration, conditions, admin, sessions, lease, contenttypes, client, payment, auth, unit, explorer Synchronizing apps without migrations: Creating tables... Running deferred SQL... Installing custom SQL... Running migrations: No migrations to apply. I assume since it moved the migration folders .No migrations applied. Should I deploy but add migration folders to gitignore now? when i run the app I get Application error An error occurred in the application and your page could not be served. If you are the application owner, check your logs for details. My log on heroku is : 2017-02-12T00:05:00.746246+00:00 heroku[run.9683]: Process exited with status 0 2017-02-12T00:05:00.743794+00:00 heroku[run.9683]: State changed from … -
how to access the same instance of a class in django view from 2 different ajax requests
Ok so i'm using django to generate my webpage and i have some views which are accessable via ajax. The issue i'm having is that i want to call one of the views which creates an object instance, then i want to call a second view but i want the second view to use the object instance of the first view. Example: def view1(request): x = MyClass() def view2(request): y = x.some_method() return JsonResponse(y) Do i need to move to a class based view? or is there a way to do the above? Many thanks in advance :D -
Django Haystack __contains field lookup not working
Recently I use Haystack and whoosh for keyword search in my django project.But I use SearchQuerySet to filter with "__contains" and return error result.There is model and index. class Team(models.Model): name = models.CharField(max_length=NAME_MAX_LENGTH, default='') leader = models.CharField(max_length=NAME_MAX_LENGTH, default='') slogan = models.CharField(max_length=SHORT_TEXT_LENGTH, default='') about = models.CharField(max_length=LONGTEXT_MAX_LENGTH, default='') b_type = models.IntegerField(default=0) ... class TeamIndex(indexes.SearchIndex, indexes.Indexable): text = indexes.CharField(document=True, use_template=True) team_name = indexes.CharField(model_attr='name') team_logo = indexes.CharField(model_attr='logo_path') team_about = indexes.CharField(model_attr='about') team_type = indexes.CharField(model_attr='b_type') def get_model(self): return Team def index_queryset(self, using=None): return self.get_model().objects.all() As fallow, I want search some result which contains key words.such as use "student" to match "The student is good.". condition = reduce(operator.and_, (Q(content__contains=x) for x in keys)) res = SearchQuerySet().filter(condition).models(model) But It also return null.So I look up the indexes which whoosh return.It can return a good result. enter image description here But when I use haystack to filter the result, It return error result. (1)"__contains" looks like "__exact" >>> SearchQuerySet().filter(text='rw\n').count() 3 >>> SearchQuerySet().filter(content='rw\n').count() 3 >>> SearchQuerySet().all().filter(content__contains='w').count() 0 >>> SearchQuerySet().all().filter(text__contains='w').count() 0 (2)"__exact" return error result >>> SearchQuerySet().filter(text__contains='y\n1231').count() 3 But I only have one index which match "y\n1231". Exceptally, I try some ways but fails. use "NgramField" or "EdgeNgramField" instead of "CharField" use "SearchQuerySet().exclude(content="XXX").filter(content__contains='w').count()" -
Unable to log into uwsgi console
so I'm running python with django and uwsgi [uwsgi] socket = 127.0.0.1:3031 chdir = /path1 wsgi-file = path/wsgi.py processes = 4 threads = 2 stats = 127.0.0.1:9191 autoreload=1 but doing print() from python won't print out anything....also tried logging.warning('something') but something wont get outputted how do I log something out to the console in uwsgi? -
How to add MIME type to django local server
How to add MIME type of any file extion type to django project for local host? how to do this? -
django-guardian remove several permissions of user which he get by group
How to remove several permissions of user which he get by the group without removing from the group? group = Group.objects.create(name='employees') assign_perm('change_task', group, task) joe.groups.add(group) joe.has_perm('change_task', task) True remove_perm('change_task', joe, task) joe.has_perm('change_task', task) True -
Is creating an accounts app in Django a good practice?
I am wondering if creating an accounts app in Django is a good practice. Say you have a Django project named mysite and you create inside two apps: core, which holds some business logic, and accounts. mysite/accounts/urls.py urlpatterns = [ url('^', include('django.contrib.auth.urls')), ] mysite/mysite/urls.py urlpatterns = [ url(r'^accounts/', include('accounts.urls')), url(r'^core/', include('core.urls')), ] mysite/accounts/templates/registration/login.html {% extends "base.html" %} {% block content %} {# Content of login page #} {% endblock %} mysite/core/templates/base.html <!DOCTYPE html> <html> <body> {% block content %}{% endblock %} </body> </html> And I create all the other necessary templates for the views in django.contrib.auth.urls. Of course we don't forget to plug the two apps: mysite/mysite/settings.py INSTALLED_APPS = [ 'accounts.apps.AccountsConfig', 'core.apps.CoreConfig', # ... ] Is all of this good practice or should I integrate the whole accounts and authentication management in the core app? -
page not found when serving static files via django
so in settings.py I have STATIC_URL = '/static/' and also INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'myapp.apps.MyappConfig' ] hence as you can see django.contrib.staticfiles is there and moreover Debug = True and in my app directory I have a file existing in this path myapp/static/css/myapp.css However, when I go to http://localhost/myapp/static/css/myapp.css it ends up returning Page not found (404) Request Method: GET what am I doing wrong and how can I get django to serve static files properly? -
invalid parameter server_name in /etc/nginx/sites-enabled/django
I've deployed a Django application on DigitalOcean. First off, when i try to secure this with https and ssl, I get this error. when i run nginx -t : nginx: [emerg] invalid parameter "server_name" in /etc/nginx/sites-enabled/django:12 nginx: configuration file /etc/nginx/nginx.conf test failed upstream app_server { server unix:/home/django/gunicorn.socket fail_timeout=0; } server { #listen 80 default_server; #listen [::]:80 default_server ipv6only=on; listen 443 ssl server_name domain.com ssl_certificate /etc/letsencrypt/live/domain.com/fullchain.pem ssl_certificate_key /etc/letsencrypt/live/domain.com/privkey.pem; root /usr/share/nginx/html; index index.html index.htm; client_max_body_size 4G; server_name _; keepalive_timeout 5; # Your Django project's media files - amend as required location /media { alias path/to/media; } # your Django project's static files - amend as required location /static { alias path/to/static; } # Proxy the static assests for the Django Admin panel location /static/admin { alias path/to/staticadmin; } location / { proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $host; proxy_redirect off; proxy_buffering off; proxy_pass http://app_server; } } server { listen 80; server_name domain.com; return 301 https://$host$request_uri; } Furthermore, I can access the website using the ip address but not the domain name registered.It results in a 400 bad request page. Could this be an issue with the settings.py ? for reference in settings.pyALLOWED_HOSTS=['*']. What list do I provide in the ip_addresses() function? Are these … -
How to redisplay form in Django?
This is after I got input from a Django form and pass the input assigned to b as context to a template a.html, I tried to pass the form as context and redisplayed using {{ form.as_p }} as before but did redisplay the form. What is wrong? return render(request, 'a.html', {'b': b, 'form': form }) a.html {{ form.as_p }} -
OperationalError (1054, "Unknown column 'month' in 'field list'")
I'm annotating price per month from my database, and I'm facing this error, I'm trying to figure out why, so in my model I have a DateTimeField, I have tried playing with data inside shell and everything is fine, I have it there, I also tried to look over db with MySQL Workbench and data is there, Full traceback and the rest of the code, can someone explain what is wrong with my annotation? models.py created = models.DateTimeField(auto_now_add=True) views.py from django.views.generic import ListView from django.db.models import Count, Sum from django.db import connection from projects.models import Project from .services import CurrencyConversionService class ProjectStatisticsList(ListView): model = Project template_name = 'statistics/statistics_list.html' paginate_by = 10 def get_context_data(self, **kwargs): context = super(ProjectStatisticsList, self).get_context_data(**kwargs) truncate_month = connection.ops.date_trunc_sql("year", "month") total_price_per_month = Project.objects.extra({"month": truncate_month}).values("month").annotate(sum_price=Sum("price_aux")) context['total_price_per_month'] = total_price_per_month return context And in template: <tr> {% for data in total_price_per_month %} <th class="aligh-left"> </th> {% endfor %} <td>Month: {{ data.month }}</td> <td>Price: {{ data.sum_price }}</td> </tr> -
How to make a queryset combining multiple ANDs and ORs in django
I need to filter something like this: (status = 0 OR status = 4) OR (parameter = NONE AND status = 1) how to I translate this into a django queryset? -
Starting postgres service in docker entry script
I am new to docker and I want to put my django website inside a docker container. I have setup the container as described here: http://michal.karzynski.pl/blog/2015/04/19/packaging-django-applications-as-docker-container-images/ I also created an entry script named entryPointScript.sh that contains the following: #!/bin/bash service postgresql start sleep 2s #sleep for two seconds source /srv/project/EnvProject/bin/activate python /srv/project/manage.py collectstatic --noinput # Collect static files python /srv/project/manage.py migrate_schemas # Apply database migrations # Prepare log files and start outputting logs to stdout touch /srv/logs/gunicorn.log touch /srv/logs/access.log tail -n 0 -f /srv/logs/*.log & # Start Gunicorn processes #echo Starting Gunicorn. # exec gunicorn project.wsgi:application \ # --name project \ # --bind 0.0.0.0:8000 \ # --workers 3 \ # --log-level=info \ # --log-file=/srv/logs/gunicorn.log \ # --access-logfile=/srv/logs/access.log \ # "$@" #Export Python Path PYTHONPATH=/srv/project/Envproject/bin # Start Uwsgi Process echo Starting Uwsgi exec uwsgi --http :8000 --socket 0.0.0.0:8000 --home /srv/project/Envproject/ --chdir /srv/project/project --wsgi-file /srv/project/project/wsgi.py --uid root --pythonpath /srv/project/Envproject/ However, when I start the container using the following command: docker run -i -t --entrypoint=/entryPointScript.sh nikssardana/project Django throws an error: django.db.utils.OperationalError: FATAL: the database system is starting up I think the postgresql service is taking too long to start. How can I avoid the error? -
How to make something similar to a registered model in the admin module
I'm trying to make an app that fills the database. I create a file named "filldata.py" in all my apps. This file imports the package. Then I implemented a callback function and is registered in the package filler.register (mycallback) I have a general application in which I implement a terminal command that fills the database. This is similar to the implementation of registration models in the admin module. This code is the implementation of a terminal command. And he did not like it. I think there is a better pythonic way to implement this import import importlib from django.conf import settings from django.core.management.base import BaseCommand class Command(BaseCommand): def handle(self, *args, **options): filler = None for app in settings.INSTALLED_APPS: try: filler = importlib.import_module(app + '.filldata') except ImportError: pass if filler: filler.filler.sort_callbacks() for msg in filler.filler.fill(): self.stdout.write(self.style.SUCCESS(msg))