Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to configure nginx to use SSL Certificate in ubuntu 16.04
https://www.petercuret.com/how-ssl-encrypt-your-django-heroku-projects-free-lets-encrypt/ This article about encrypt django app is a great tutorial. I did most of the process, except the last one. "Adding the security certificate to Heroku", mine is cloud server with Ubuntu 16.04. So it's not adapted to my server. Googled around about "Nginx ssl encrypt", and found this tutorial I configured nginx server as this tutorial. When all finished, I tested it with "curl https://example.com(my domain)", it returns "Failed to connect to example.com port 443: Connection refused" PS: nginx runs in host, and Django app runs in a docker container Some results of my server: root@i-atbxncfv:~# sudo ufw status Status: active To Action From -- ------ ---- Nginx Full ALLOW Anywhere 443/tcp ALLOW Anywhere 443 ALLOW Anywhere 22/tcp ALLOW Anywhere Nginx Full (v6) ALLOW Anywhere (v6) 443/tcp (v6) ALLOW Anywhere (v6) 443 (v6) ALLOW Anywhere (v6) 22/tcp (v6) ALLOW Anywhere (v6) root@i-atbxncfv:~# sudo ufw app list Available applications: Nginx Full Nginx HTTP Nginx HTTPS OpenSSH root@i-atbxncfv:~# docker ps -a CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES b082bf17c218 e5b11bf09f49 "/usr/sbin/sshd -D" 2 days ago Up 2 days 0.0.0.0:21->22/tcp, 0.0.0.0:32789->80/tcp, 0.0.0.0:32788->5000/tcp django_app_1 root@i-atbxncfv:/etc/nginx/sites-enabled# cat example-com.conf server { listen 80; server_name example.com; location / { proxy_set_header X-Real-IP $remote_addr; proxy_set_header Host … -
NoReverseMatch at / Reverse error with urlresolvers, get_absolute_url()
Error with url reverse() in function get_absolute_url() can't reverse the url in models Serial(serial_slug) this is models.py class Season(models.Model): id = models.AutoField(primary_key=True) name_of_the_season = models.CharField(max_length=40) slug = models.SlugField(unique=False, blank=True) name_for_easy_access = models.CharField(max_length=40) preview_of_season = models.ImageField(upload_to="previews/preview_for_season/", default=None,width_field="width_field", height_field="height_field") width_field = models.IntegerField(default=150) height_field = models.IntegerField(default=150) number_of_released_series = models.IntegerField(default=0) serial_for_this_season = models.ForeignKey("Serial", on_delete=models.CASCADE, default=True) a_lot_of_series = models.ManyToManyField("Series", default=None, blank=True) year = models.IntegerField(default=2017) timestamp = models.DateTimeField(auto_now_add=True, auto_now=False) updated = models.DateTimeField(auto_now_add=False, auto_now=True) is_active = models.BooleanField(default=True) def get_absolute_url(self): return reverse('series:post_of_season', kwargs= {'serial_slug': self.serial_for_this_season.slug, 'season_slug': self.slug, }) def __str__(self): return "%s" % self.name_for_easy_access class Meta: ordering = ["-timestamp"] verbose_name = 'Season' verbose_name_plural = 'Seasons' class Serial(models.Model): id = models.AutoField(primary_key=True) rus_name_of_seriall = models.CharField(max_length=40) eng_name_of_seriall = models.CharField(max_length=40) slug = models.SlugField(unique=False, blank=True) number_of_serial = models.DecimalField(max_digits=10, decimal_places=2, default=True) preview_of_serial = models.ImageField(upload_to="previews/preview_for_serials/", default=None,width_field="width_field", height_field="height_field") width_field = models.IntegerField(default=0) height_field = models.IntegerField(default=0) seasonss = models.ManyToManyField(Season, default=None, blank=True) timestamp = models.DateField(auto_now_add=True) end_or_in_proccess = models.ForeignKey(Status, default=None) timestamp = models.DateTimeField(auto_now_add=True, auto_now=False) updated = models.DateTimeField(auto_now_add=False, auto_now=True) is_active = models.BooleanField(default=True) def get_absolute_url(self): return reverse('series:post_of_serial', kwargs={'serial_slug': self.slug}) def __str__(self): return "%s" % self.rus_name_of_seriall class Meta: ordering = ["-timestamp"] verbose_name = 'Serial' verbose_name_plural = 'Serials' class Series(models.Model): id = models.AutoField(primary_key=True) rus_name = models.CharField(max_length=60) eng_name = models.CharField(max_length=60) is_active = models.BooleanField(default=True) serial_of_this_series = models.ForeignKey(Serial, on_delete=models.CASCADE, default=True) season_of_this_series = models.ForeignKey(Season, on_delete=models.CASCADE, default=True) number_of_series = … -
Run python script in Django website when clicking on button submit
I would like to create a button that when launching a python script. This script opens a data.txt file and transforms it into json so that I can integrate it into my database in the future. What I want to do today is just to create a button that when clicking starts the script (I would check in my documents if the file json result.txt has been created which allows me to check if the function works ). That I have done : In urls.py url(r'whatever^$', views.recup_wos, name='recup_wos'), In views.py def recup_wos(request): if request.method == 'POST': import newscript.py os.system('python newscript.py') return redirect('accueil') Template accueil.html <form action='{% url recup_wos %}' method="POST"> <input value="Executer" type="submit"> </form> The error message is the following : Reverse for '' with arguments '()' and keyword arguments '{}' not found. 0 pattern(s) tried: [] [enter image description here]1 I think the error mainly locates it in the view, maybe a syntax error. Thank you in advance for your help. -
Frontend sending only OPTIONS request
I have a question about OPTIONS request. I have an application, with Angular2 on frontend and Nginx-uWSGI-Django backend. All parts of app are working fine, except for Angular Datatables. Frontend and backend are on the same domain but different subdomains, but as I understood that is no CORS used. Except for Datatables, at that time Angular sending OPTIONS request, and after server answers with 200, no GET request is sended. Just OPTIONS and nothing else. How it can be solved, or what problem can cause it? Thanks a lot. P.S. I have Access-Allow-Origin header "turned on" and on local machine with django dev-server all working fine. -
Can't install django-scheduler
I'm trying to install django scheduler, i've done the following: pip install django-scheduler added 'schedule', to INSTALLED_APPS, i didn't add django.core.context_processors.request to TEMPLATE_CONTEXT_PROCESSORS, since i'm getting unresolved refence and i assume it's django.template.context_processors.request. pip install django-bower added to INSTALLED_APPS: 'djangobower', added STATICFILES_FINDERS = [ 'djangobower.finders.BowerFinder', ] added BOWER_COMPONENTS_ROOT = os.path.join(BASE_DIR, 'components') added BOWER_INSTALLED_APPS = ( 'jquery', 'jquery-ui', 'bootstrap' ) and the moment i have to install bower dependencies with: python manage.py bower install, i'm getting this: BowerNotInstalled: Bower not installed, read instruction here - http://bower.io/ -
'list' object has no attribute 'startswith'
I want to upload the profile picture. the image is not getting uploaded. It gives the error AttributeError at /profile/ 'list' object has no attribute 'startswith' def userDetail(request): current_user = request.user if(request.method == 'POST'): form = UserDetailDataForm(request.POST, request.FILES) if(form.is_valid()): profileImg = request.FILES['profileImg'] try: userprofile = UserDetail.objects.get(user_id = current_user.id) if userprofile: userprofile.profileImg = profileImg userprofile.save() context = {'username': current_user.username, 'image' : userprofile.profileImg, 'MEDIA_ROOT': settings.MEDIA_ROOT} return render_to_response('user_profile.html', context) else: form = UserDetailDataForm() return render_to_response('profile.html', {'form': form}) Models.py profileImg = models.ImageField(upload_to='/images/',blank=True, null=True,default="images/default-profile.jpg") Settings file: BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) MEDIA_ROOT = [ os.path.join(BASE_DIR, 'firstapp/static/'),] -
Can a python pip package access the database in django?
Can a python pip package access the database? Is it possible for a library, installed via pip, can access the entire database of a django project? -
Saving list against single value in database using django?
I have a list of university that i want to store with news id. My model is this:- from __future__ import unicode_literals from django.db import models from cms.models.universities import Universities from cms.models.newsMappings import NewsMappings class NewsUniversityMappings(models.Model): id = models.IntegerField(db_column="id", max_length=11, help_text="") newsMappingId = models.ForeignKey(NewsMappings, db_column='newsMappingId' ,max_length=11, help_text="") universityId = models.ForeignKey(Universities, db_column='universityId', max_length=11, help_text="") createdAt = models.DateTimeField(db_column='createdAt', auto_now=True, help_text="") class Meta: managed = False db_table = 'news_university_mappings' my views is:- if request.method =='POST': university = request.POST.getlist('universityId') newsId = 1; add_news_university_mappings = NewsUniversityMappings(universityId=university, newsMappingId=newsId) add_news_university_mappings.save(using="cms") messages.success(request, 'Successfully added to the university list') now, how can i save the university list againt single value of newsid in database. -
Cumulative sum with django orm and postgresql
Is it possible to calculate the cumulative sum using django's orm? Consider the following model: class AModel(models.Model): a_number = models.IntegerField() with a set of data where a_number = 1. I'd like to be able to return the following: AModel.objects.annotate(cumsum=??).values('id', 'cumsum').order_by('id') >>> ({id: 1, cumsum: 1}, {id: 2, cumsum: 2}, ... {id: N, cumsum: N}) Ideally I'd like to be able to limit/filter the cumsum. So in the above case I'd like to limit the result to cumsum <= 2 I believe that in postgresql one can achieve a cumulative sum using window functions. How is this translated to the ORM? -
Sequence in the django model access between model through foreign key to model how to fix my models?
I have such a problem that can be turned into a lesson, a hack, with models, and with url-routing, it turns out Need to be sequenced, that is, by url Series / serial_slug / season_slug / series_slug / But to get access to the seasons of the series you need so Series / serial_slug / season_slug / It turns out I do not have access to the series / serial_slug / season_slug / no access to serial_slug in the Season model, since it is important for jango that if any model needs access, then the model must be on top of the requested momme, and thus access to There is no serial model, since it is below the season model, if they are reversed, it will not work, although the idea should be like this: In the "Serial" model there is a lot of seasonal that is "ManyToMany" to the model "Season" that is the logical field there is a model Serial from above, then there is the model Season, then comes the Series, but it does not robit! In the "Season" model there are a lot of series, that is, "ManyToMany" for the Series model, and to get a … -
django Error: django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet
I am getting an error in Django. I saw a lot of similar questions but am not able to find a working solution. I think the error is in importing the User model. I am not able to find a solution to this. Basically, it seems that it is not able to get the User model. Please help. Traceback (most recent call last): File "C:\Python34\lib\site-packages\django\utils\autoreload.py", line 226, in wrapper fn(*args, **kwargs) File "C:\Python34\lib\site-packages\django\core\management\commands\runserver.py", line 113, in inner_run autoreload.raise_last_exception() File "C:\Python34\lib\site-packages\django\utils\autoreload.py", line 249, in raise_last_exception six.reraise(*_exception) File "C:\Python34\lib\site-packages\django\utils\six.py", line 685, in reraise raise value.with_traceback(tb) File "C:\Python34\lib\site-packages\django\utils\autoreload.py", line 226, in wrapper fn(*args, **kwargs) File "C:\Python34\lib\site-packages\django\__init__.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Python34\lib\site-packages\django\apps\registry.py", line 85, in populate app_config = AppConfig.create(entry) File "C:\Python34\lib\site-packages\django\apps\config.py", line 90, in create module = import_module(entry) File "C:\Python34\lib\importlib\__init__.py", line 109, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 2254, in _gcd_import File "<frozen importlib._bootstrap>", line 2237, in _find_and_load File "<frozen importlib._bootstrap>", line 2226, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 1200, in _load_unlocked File "<frozen importlib._bootstrap>", line 1129, in _exec File "<frozen importlib._bootstrap>", line 1471, in exec_module File "<frozen importlib._bootstrap>", line 321, in _call_with_frames_removed File "E:\Python\TheRandomSite\investor\__init__.py", line 1, in <module> from . import urls File "E:\Python\TheRandomSite\investor\urls.py", line 18, in … -
model object is reflecting object instead of title
In django when ever I am trying to view my [Post.objects.all()] its results Post:Post Object instead of Post: title. I have already added def str(self): return self.post_title enter image description here -
Django Bootstrap list
I have displayed some of models in a bootstrap tree. Now i have to display the details of a particular node of that tree in a bootstrap list. I know i need to use AJAX view for this. But I am not getting any clear idea. Please help me. Following is my view def get_context_data(self, **kwargs): context = dict() organization = Organization.objects.all() orglocations = Orglocations.objects.all() locationprocessarea = Locationprocessarea.objects.all() processareaasset = Processareaasset.objects.all() processtaglink = Processareaassettaglink.objects.all() context["TreeStructure"] = [ { 'text': organizations.name, 'nodes': [ { 'text': orglocationss.name, 'nodes': [ { 'text': processarea.name, 'nodes': [ { 'text': processasset.name, 'nodes':[{ 'text':processareafilter.name, 'nodes':[{ 'text':taglink.name }for taglink in processtaglink.filter(areaassetid=processareafilter.id)] }for processareafilter in processareaasset.filter(parentassetid=processasset.id)] } for processasset in processareaasset.filter(processareaid=processarea.id).filter(parentassetid__isnull=True)] } for processarea in locationprocessarea.filter(locationid=orglocationss.id)] } for orglocationss in orglocations.filter(organizationid_id=organizations.id)] } for organizations in organization.filter(id=1)] return { "tree_view": context } and the script i have used in my template is, <script> var test_tree = {{ tree_view.TreeStructure | safe }}; $('#tree').treeview({data: test_tree}); </script> Please help me..!! thanks in advance -
querying using Q objects and also using Q single object
i have 2 cases which i have to join using '|' and get apply the query on the object.First i have list of countries i.e eu countries.and second i have a country from which the user is logged in.I want to join both objects and get the result using Q.basically it can q = Q(country=auth.country) and q2 = Q(country = settings.euContries),currently working around this is not helping. Any help in this matter is highly appreciated -
array_sum in python/django
Is there any function similar to PHP array_sum function ? I mean I have an object, for an instance: obj = {} obj['t'] = 2 obj['x'] = 4 obj['z'] = 6 and I would like to sum it without any loop, by one function. Is this possible in python / django framework ? Thanks in advance for help -
I can't map my "about page view" in my application urls.py
I can not map my "about page view" in my application urls.py file. I tried to find solutions on the internet but I could not. Reinstalled django, created again new project but the same error appers. The error is SyntaxError. Help me please. I do not know where I have made mistake. Note that I want to map application urls.py in another file. Then join application urls.py file to the project's. My python version is 2.7 My django version is 1.8 This is my views.py file. from django.shortcuts import render from django.http import HttpResponse def index(request): return HttpResponse("Rango says hello world! <a href='/rango/about'> About </a>") def about(request): return HttpResponse("Rango Says: Here is the about page <a href='/rango/'> Index </a>") This is my application urls.py file. from django.conf.urls import patterns, url from rango import views urlpatterns = patterns('', url(r'^$', views.index, name='index') urlr('^rango/about', views.about, name='about')) This is my project urls.py file. from django.conf.urls import include, url from django.contrib import admin urlpatterns = [ # Examples: # url(r'^$', 'projectX.views.home', name='home'), # url(r'^blog/', include('blog.urls')), url(r'^admin/', include(admin.site.urls)), url(r'^rango/', include("rango.urls")) ] -
Leaflet remove current marker and add a new one on click
I'm currently routing to a marker, but I want to be able to choose another route and the current marker will then be rerouted. Image one shows the current routing. On click of the 'Route to here' button the current marker must be removed and replaced with the new marker. function showPosition(position) { //Set the map view to be the users location var map = L.map('map').setView([position.coords.latitude, position.coords.longitude], 14); L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', { attribution: '&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors' }).addTo(map); //Change the users marker to a unique red & show users location on click L.marker([position.coords.latitude, position.coords.longitude], { icon: L.AwesomeMarkers.icon({prefix: 'fa', markerColor: 'red'}) }).addTo(map).bindPopup("<b>Your location: </b>" + position.coords.latitude + "," + position.coords.longitude); L.Routing.control({ waypoints: [L.latLng(users_lat_coords, users_lng_coords), L.latLng(x, y)], lineOptions: {addWaypoints: false} } ).addTo(map); } -
Problems while installing requirements.txt?
The package python-urllib3 needs to be reinstalled, but I can't find an archive for it. getting this error -
comparing model A's fields values in model B's field django
I have 1 Lakh records in both model 'A' and in model 'B' Ex: class A(models.Model): user_email = models.EmailField(null=True, blank=True) user_mobile = models.CharField(max_length=30, null=True, blank=True) book_id = models.CharField(max_length=255, null=True, blank=True) payment_gateway_response = JSONField(blank=True, null=True) class B(models.Model): order = models.ForeignKey(A, null=True, blank=True) pay_id = models.CharField(max_length=250, null=True, blank=True) user_email = models.EmailField(null=True, blank=True) user_mobile = models.CharField(max_length=30, null=True, blank=True) created = models.DateTimeField(blank=True, null=True) total_payment = models.DecimalField(decimal_places=3, max_digits=20, blank=True, null=True) now i want to get B's objects using A's values for example all_a = A.objects.all() for a in all_a: b = B.objects.filter(user_email=a.user_email, user_mobile=a.user_mobile) So this is fine i am getting the results. But as it's 1Lakh records it's taking too much time. for loop iteration is taking time. Is there any faster way to do this in django? -
Get models related directly and indirectly to filtered results, django-mptt
I have the following code: class Category(MPTTModel): name = models.CharField(max_length=100) parent = TreeForeignKey('self', null=True, blank=True, related_name="subcategories", related_query_name="subcategory") class Item(models.Model): name = models.CharField(max_length=200) category = models.ForeignKey(Category) I want to get the categories in a level are indirectly or directly related to a group of filtered items. The database and the filtered results would be huge so iterating over the models is not an option. *Django 1.10, Postgress, django-mptt -
Django Reverse Foreignkey Based on a Field of Second Table
I have the following two tables in Django. class TeamSubscriptions(models.Model): user = models.ForeignKey(User, unique=True) soccer_team = models.ForeignKey(SoccerTeam) .... .... class Meta: db_table = 'soccer_team_subscriptions' class MatchSubscriptions(models.Model): team_subscriber = models.ForeignKey(TeamSubscriptions, related_name='soccer_user_matches') soccer_match = models.IntegerField(db_index=True) winning_team_guess = models.CharField(max_length=50, default='') ... ... class Meta: db_table = 'soccer_game_subscriptions' unique_together = ("team_subscriber", "soccer_match") I want to fetch all subscribers from Teamsubscriptions. For all of them, I want to find the corresponding rows from MatchSubscriptions with a specific soccer_match ID. The purpose is to get winning_team_guess from the second table for some specific soccer_match IDs. Is there any way to do this (Reverse ForeignKey) for a specific soccer_match ID..?? -
AttributeError: 'module' object has no attribute 'TwilioRestClient'
Trying to integrate django 1.10 application with twilio 6.0.0 and django-twilio==0.8.0 referring link and getting below error in my shell.. 7 def send_twilio_message(to_number, body): ----> 8 client = twilio.rest.TwilioRestClient( 9 settings.TWILIO_ACCOUNT_SID, settings.TWILIO_AUTH_TOKEN) 10 AttributeError: 'module' object has no attribute 'TwilioRestClient' -
Django CBV: reuse form with fields subset
I have a FormView with a ModelForm to create a particular model. Now let's say I want to be able to edit that model, but only a subset of fields, so only these can be modified and validation will be run only on these, and not the others (and the others won't appear as "required", etc). Is it possible to reuse the existing ModelForm in this scenario, or do I have to create a new form altogether? -
Nginx+Uwsgi+Django+Redis internal server error
I use nginx+uwsgi+django+redis combination to use websockets in django. I suppose that problem in Nginx because on local machine everything is OK, when I test server via manage.py runserver it's OK too, and I have no traceback with Debug=True - only Internal server error message. Problem appeared on vds. Nginx conf: server { listen 80 default_server; server_name 188.225.38.189; access_log /var/log/nginx/example.log; location /static/ { root /root/shebeke_social/shebeke_social/; expires 30d; } location /ws/ { proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; proxy_pass http://188.225.38.189:8081/; } location / { include /etc/nginx/uwsgi_params; uwsgi_pass 188.225.38.189:8000; } } location / and /ws/ calls Internal server error, /static/ - 403 Forbidden, inter alia, I don't know why 403 appears too because the whole directory was granted by 777 permission. This is a start server script: /etc/init.d/nginx restart /etc/init.d/mysql restart uwsgi --virtualenv /root/shebeke_social --socket 188.225.38.189:8000 --buffer-size=32768 --workers=5 --master --module SocialNetwork.wsgi_django & uwsgi --virtualenv /root/shebeke_social --http-socket 188.225.38.189:8081 --gevent 1000 --http-websockets --workers=2 --master --module SocialNetwork.wsgi_websocket & I don't know if you need more information. -
Django passing **kwargs between Form and List view
I'm fairly new to Django and am trying to complete some code in which I have a form where the user enters a date range so "start_date & end_date" once entered i want it to redirect to a list view and to pass the **kwargs. I've had a lot of trouble with this and finally came up with a way to go about it, but it probably looks like a developers nightmare. My issues so far is when i had it as two separate views i couldn't get the **kwargs to pass over at all, it just listed all results. Views.py class BirthdayRangeFormView(FormView): template_name = 'snippets/date_selection_form.html' form_class = datefilterform def get_form_kwargs(self): kwargs = super(BirthdayRangeFormView, self).get_form_kwargs() kwargs ['request'] = self.request return kwargs def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['title'] = "Date Selection" context['header'] = "Please select date range" return context def form_valid(self, form): self.start_date = (form.cleaned_data['start_date'], Person.next_birthday) self.end_date = (form.cleaned_data['end_date'], Person.next_birthday) return self.redirect_to_results() def redirect_to_results(self): self.success_url = "dates:birthdays" return redirect( self.get_success_url(), ) if redirect_to_results: class BirthdayRangeFormView(ListView): template_name = 'dates/birthdays.html', context_object_name = "people" people = True def get_queryset(self, **kwargs): if self.people: qs = qs.filter( classification__in=people, ) else: qs = qs.exclude( classification__in=people, ) qs = qs.filter( next_birthday__range=( parse( kwargs.get( 'start_date', month_start(timezone.now()).date().strftime('%Y-%m-%d') ) ), …