Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
SSL on Django, Nginx, and Gunicorn
I am using Nginx and gunicorn to serve my Django project. I currently have it working for ssl (https), but do not quite understand the correct settings for the settings file and nginx. Could someone have a look at my setup and tell me if anything blatantly looks wrong, or horribly executed? My Nginx File, Please Note that some lines are commented out. When I uncomment them, the site stops working. Edit: When I uncomment them all at the same time/ server { server_name example.com; listen 443 ssl; ssl on; ssl_certificate /etc/ssl/mycrt.crt; ssl_certificate_key /etc/ssl/mykey.key; location = /favicon.ico {access_log off; log_not_found off;} location /static/ { gzip on; gzip_types text/css; alias /home/project/static/; } location / { include proxy_params; # proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto https; # proxy_set_header Host $http_host; # proxy_redirect off; proxy_pass http://unix:/home/project/myproject/project.sock; } } server { listen 80; server_name example.com www.example.com; return 301 https://example.com$request_uri; } My Gunicorn File [Unit] Description=gunicorn daemon After= network.target [Service] User=tyler Group=www-data Environment="Production=production" WorkingDirectory=/home/project/myproject ExecStart=/home/project/projectenv/bin/gunicorn --access-logfile - --workers 3 --bind unix:/home/projecty/myproject_a$ [Install] WantedBy=multi-user.target And lastly, the dajngo settings SECURE_SSL_REDIRECT = True SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https') SESSION_COOKIE_SECURE = True CSRF_COOKIE_SECURE = True Are there any issues with this setup? I am very confused about the Nginx settings … -
Passing Dict of Arrays using Ajax and Django
I have a dictionary of arrays that I would like to pass to my Django view. $.ajax({ url: '/fund_monitor/fund_directory', type: 'GET', data:{ filter_dict: filter_dict, }, success: function (data) { console.log(filter_dict); } }); And in my view I would like to receive this dict: if request.is_ajax(): filter_dict = request.GET.getlist('filter_dict') print("Is Ajax", filter_dict) But "Is Ajax []" gets printed out and just as an example, my filter_dict: Designated Broker:["BMO"] Fund Class:["OM"] Any ideas why a blank array gets passed? -
Django Rest Framework not hashing my password
I am trying to register a user in my Blog-API that I build using Django Rest Framework. Here is my code (serializers.py): from django.contrib.auth import get_user_model from django.contrib.auth.hashers import make_password from rest_framework.serializers import (ModelSerializer, HyperlinkedIdentityField, SerializerMethodField) User = get_user_model() class UserCreateSerializer(ModelSerializer): class Meta: model = User fields = [ 'username', 'email', 'password', ] extra_kwargs = { 'password': {'write_only': True} } def create(self, validated_data): username = validated_data['username'] email = validated_data['email'] password = validated_data['password'] user_obj = User(username=username, email=email) user_obj.set_password(password) user_obj.save() return validated_data In the Django admin the user will appear as expected. However, the password is said to be of invalid format. Can somebody point me toward a solution ? -
Temasys WebRTC for Django
Has anybody done a full fledged Django project using the WebRTC libraries of Temasys? If yes please provide a link to your GitHub Repo. I want to refer to how the JS is included in the HTML page. That is if you're okay with the sharing of the Repo. Thanks a ton. Note: Starting to scratch the surface of Django, so forgive the naivete. -
css file not working in django
I am making a blog in django, when i try to make add css to my html files nothing chances. The css file is not working. here is my code: Urls.py: from django.conf.urls import url from . import views from .feeds import LatestPostsFeed urlpatterns = [ # post views url(r'^$', views.post_list, name='post_list'), url(r'^tag/(?P<tag_slug>[-\w]+)/$', views.post_list, name='post_list_by_tag'), #url(r'^$', views.PostListView.as_view(), name='post_list'), url(r'^(?P<year>\d{4})/(?P<month>\d{2})/(?P<day>\d{2})/(?P<post>[-\w]+)/$', views.post_detail, name='post_detail'), url(r'^(?P<post_id>\d+)/share/$', views.post_share, name='post_share'), url(r'^feed/$', LatestPostsFeed(), name='post_feed'), url(r'^search/$', views.post_search, name='post_search'), ] Projects url.py: from django.conf.urls import include, url from django.contrib import admin from django.contrib.sitemaps.views import sitemap from blog.sitemaps import PostSitemap from django.contrib.staticfiles.urls import staticfiles_urlpatterns sitemaps = { 'posts': PostSitemap, } urlpatterns = [ url(r'^admin/', include(admin.site.urls)), url(r'^blog/', include('blog.urls', namespace='blog', app_name='blog')), url(r'^sitemap\.xml$', sitemap, {'sitemaps': sitemaps}, name='django.contrib.sitemaps.views.sitemap'), ] urlpatterns += staticfiles_urlpatterns() settings.py static_url: STATIC_URL = '/static/' -
Adding HTML elements in a Django ModelForm
One of the fields in my form should display a static currency symbol as the first character in the field. This character should not be able to be deleted from the field. I understand that I can use <span> elements to insert the symbol into the field. The Problem I don't know how to put <span> tags around my form fields. Currently, this part of the site looks like the following: forms.py class JobForm(forms.ModelForm): class Meta: model = Job fields = [ 'Date', 'Time_Start', 'Time_End', 'Employee', 'Client', 'Service', 'Price', ] views.py def jobs_add(request): if request.method == "POST": form = JobForm(request.POST) if form.is_valid(): form = JobForm(request.POST) form.save() return HttpResponseRedirect(reverse('jobs')) else: form = JobForm() return render(request, 'home/jobs_edit.html', {'form': form, 'new_job': True}) page.html {% block content %} <form method="POST"> {% if new_job %} <h1>You are adding a new job</h1> {% else %} <h1>You are editing the details for job # {{ Job.Job_ID }}</h1> {% endif %} {% csrf_token %} {% form.as_ul %} <input type="submit" value="Save" /> {% if new_job %} {% else %} <input type="submit" name="delete" value="Delete" /> {% endif %} </form> {% endblock %} -
Django: AttributeError: 'FundAccountListView' object has no attribute 'object_list'
I have an ajax call which I would like to serve inside my class based view using the get function. Here is my ajax call: $.ajax({ url: '/fund_monitor/fund_directory', type: 'GET', data:{ filter_dict: filter_dict, csrfmiddlewaretoken:$('input[name=csrfmiddlewaretoken]').val() }, success: function (data) { console.log(data); } }); and here is my class based view: class FundAccountListView(ListView): model = FundAccount def get_context_data(self, **kwargs): context = super(__class__, self).get_context_data(**kwargs) context['nbar'] = 'fund_monitor' context['sbar'] = 'fundaccount_list' context['transmission'] = 3 url_dict = defaultdict(list) for fund in context['fundaccount_list']: end_date = str(NAV.objects.filter(fund= fund.id, transmission=3).values('valuation_period_end_date').order_by('-valuation_period_end_date')[0]['valuation_period_end_date']) start_date = str(NAV.objects.filter(fund= fund.id, transmission=3).values('valuation_period_end_date').order_by('-valuation_period_end_date')[1]['valuation_period_end_date']) url_dict[fund.account_description].extend([fund.id,context['transmission'], start_date, end_date]) context['obj_items'] = dict(url_dict) return context def get(self, request, *args, **kwargs): context = self.get_context_data() if request.is_ajax(): print(self.get_template_names()) return self.render_to_response(context) def render_to_response(self, context, **response_kwargs): response_kwargs.setdefault('content_type', self.content_type) return self.response_class( request=self.request, template=self.get_template_names(), context=context, using=self.template_engine, **response_kwargs ) But I get the following error: File "/usr/local/lib/python3.5/site-packages/django/views/generic/list.py", line 130, in get_context_data django_1 | queryset = kwargs.pop('object_list', self.object_list) django_1 | AttributeError: 'FundAccountListView' object has no attribute 'object_list'. Any ideas why? -
How can I present a Line graph using Cassandra 3.0, Python Djano 1.11 in a website
This is my first project with Cassandra and Python Django. I have all the data in Cassandra and I have synced Cassandra with Python Django. Now I have to present Cassandra data as a graphs in a website. How can I achieve this? Please share any guidelines or approach or useful libraries. -
what did i do wrong while implementing slug url in django?
I am getting the following error after I modified the urls.py, views.py and models.py file in my blog application to accomodate a slug string in the url. Reverse for 'post_detail' with keyword arguments '{'pk': 3}' not found. 1 pattern(s) tried: ['(?P[-\w\d]+),(?P\d+)/$'] I am attaching the link to the github repository for the project here, as I don't have any idea what went wrong please let me know where to look. git repository -
Django TestCase: recreate database in self.subTest(...)
I need to test a function with different parameters, and the most proper way for this seems to be using the with self.subTest(...) context manager. However, the function writes something to the db, and it ends up in an inconsistent state. I can delete the things I write, but it would be cleaner if I could recreate the whole db completely. Is there a way to do that? -
Django Inlineformset Only Saving the Last Row Added
I am using inlineformset to create extra rows when needed in a form. Both tables render on the same HTML page but are called from two separate html templates. The first table called new performs as I would expect it would -i.e. adds new rows, collects the data, counts the number of TOTAL_FORMS correctly in Form Data, and saves to the database. The second table renew adds new rows and collects the data but does not increment the count in TOTAL_FORMS and only saves the last row to the database. I believe I have debugged this problem to the html template files but can provide views.py and forms.py if I am wrong and is needed. I need help figuring how to get the second table renew to count the number of TOTAL_FORMS correctly and thus allowing it to be saved in the database. formset_new.html (this one works) {% for form in formset.forms %} {% if forloop.first %} <thead> <tr> {% for field in form.visible_fields %} <th>{{ field.label|capfirst }}</th> {% endfor %} </tr> </thead> {% endif %} <tr class="{% cycle 'row1' 'row2' %} formset_row {{formset_class_name}}"> {% for field in form.visible_fields %} <td> {# Include the hidden fields in the form #} … -
Django Rename dictionary value
I have a dictionary context['income'] = Income.objects.filter(assigned_to__username=self.request.user). \ filter(status=Income.STATUS_PENDING). \ annotate(month=ExtractMonth('created')).values('month'). \ annotate(value=Coalesce(Sum('value'), 0)).values('month', 'value') which will return everytime something like this: <QuerySet [{'month': 9, 'value': Decimal('12.50')}]> Instead the month number i wish to display the month in words: 1 - January, 2 - February ... 9 - September etc. I want to use this in a chart where monthly there will be displayed the total value in a month. template.html <script type="text/javascript"> $(document).ready(function () { Morris.Bar({ element: 'Income', data: [ {% for item in income %} { Month: '{{ item.month }}', Income: '{{ item.value }}' }, {% endfor %} ], xkey: 'Month', ykeys: ['Income'], labels: ['Euro'], resize: true, lineColors: ['#33414E', '#95B75D'] }); }); </script> -
Best way to iterate through which report groups a user belongs for security and speed
I have a model for User (Django Built-in), Reports, ReportGroups and ReportGroupMembers. A User can create a Report, that belongs to a single ReportGroup. The user can only write reports for ReportGroups they belong (hence ReportGroupMembers). In my view (below), I'd like to only show groups the user owns or is a member of and have a decorator or someway to easily prevent people from writing to groups they don't belong. ReportGroups can have a password associated (which is used to join a group). I'm not too sure the best way to design/accomplish this and have it scale well. If I didn't need it to scale I'd just for loop iterate through groups they belong. View: def dashboard(request): group_list = ReportGroup.objects.all() return render(request, 'dashboard/main.html', {'group_list': group_list}) Model: class ReportGroup(models.Model): group_name = models.CharField(max_length=64, blank=False, null=False) description = models.TextField(blank=True, null=True) avatar = models.ImageField(upload_to='profiles', null=True, blank=True) user = models.ForeignKey(User) class Meta: managed = True db_table = 'report_group' def __str__(self): return 'Group: %s - User: %s' % (self.group_name, self.user.username) class Report(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) name = models.CharField(max_length=264, unique=False) users = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) group = models.OneToOneField(ReportGroup, on_delete=models.CASCADE) class Meta: managed = True db_table = 'intelligence_report' def __str__(self): return '%s (%s)' % (self.name, self.users.username) … -
Getting django-ajax_selects to work in my search form in Django
I'm trying to make a search form that uses AJAX Select so that when I type an entry into a field, there will be a dropdown that contains a list of an attribute from all of the model objects that match the text typed in. Here is the relevant code: models.py class Student(models.Model): student_id = models.CharField(max_length=128, unique=True, null=True, blank=True) first_name = models.CharField(max_length=128) last_name = models.CharField(max_length=128) ssn = USSocialSecurityNumberField(null=False) gender = models.CharField(max_length=128, choices=GENDER_CHOICES) dob = models.DateField(auto_now=False, auto_now_add=False, db_column="date of birth") location = models.CharField(max_length=128, choices=LOCATION_CHOICES, default='south_plainfield') lookups.py @register('first_name') class FirstNameLookup(LookupChannel): model = Student def get_query(self, q, request): return self.model.objects.filter(first_name__icontains=q).order_by('first_name')[:50] def format_item_display(self, obj): return u"<span class='first_name'>%s</span>" % obj.first_name forms.py class StudentSearchForm(forms.Form): student_id = forms.CharField(max_length=64, required=False, label="Student ID") ssn = USSocialSecurityNumberField(widget=forms.TextInput(attrs={'class': 'form-control'}), label="SSN", help_text="Format: xxx-xx-xxxx", required=False) #Pay attention to this first_name = AutoCompleteSelectMultipleField('first_name', max_length=128, required=False, label="First Name") last_name = forms.CharField(max_length=128, required=False, label="Last Name") course = forms.ChoiceField(choices=STUDENT_SEARCH_COURSES, required=False) location = forms.ChoiceField(choices=STUDENT_SEARCH_LOCATION_CHOICES, required=False) dob = forms.DateField(widget=DateInput(), required=False, label="Date of Birth") gender = forms.ChoiceField(choices=STUDENT_SEARCH_GENDER_CHOICES, required=False) views.py def search_student(request): form = StudentSearchForm() if request.method == 'GET' and request.GET != {}: form = StudentSearchForm(request.GET) if form.is_valid(): cleaned_form = form.cleaned_data student = Student.objects.none() for key in cleaned_form: value = cleaned_form[key] if value == '' or value == None: continue else: … -
django-leaflet installation exception
I'm new to Django and I would like to install leaflet to show the map. I've followed the installation instructions, and while the pip command seemed to work well, when I go to settings.py to add leaflet to my installed apps, when I save the file I get this error: Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x000002494D622730> At the end of the traceback there is this: django.core.exceptions.ImproperlyConfigured: Could not find the GDAL library (tried "gdal201", "gdal20", "gdal111", "gdal110", "gdal19"). Is GDAL installed? If it is, try setting GDAL_LIBRARY_PATH in your settings. In the installed apps section of settings.py I've tried adding 'leaflet' or 'django-leaflet'. What am I missing? -
Heroku Django app works locally, but not deployed (django-tables2)
I am trying to integrate the django-tables2 package into my Heroku Django app. When I remove django-tables2 from my app, it works both locally and when deployed on Heroku. However, when I use it the app works locally, but not when deployed. The error I get is: relation "blagajna_ucenik1" does not exist LINE 1: SELECT COUNT(*) AS "__count" FROM "blagajna_ucenik1" "Blagajna" is the name of my Django app, while Ucenik1 is the name of my model. -
Django app not updating static files in browser
The static files from third-party apps are not being updated in my Django site when it is served up in a browser with runserver. Here is my file structure (with many more static files): - mysite - mysite - settings.py - wsgi.py . . . - myapp - templates - base.html - myapp.html - models.py - forms.py . . . - static - MyApp - mystyle.css - autocomplete-light - select2.css base.html: {% load static %} <!DOCTYPE html> <html> <head> <title> {% block title %}Portal{% endblock title %} </title> {% block stylesheets %} <link rel="stylesheet" type="text/css" href="{% static 'myapp/mystyle.css' %}?{% now "U" %}"/> {% endblock stylesheets %} </head> <body> {% block content %} {% endblock content %} </body> <footer> {% block footer %} {% endblock footer %} </footer> </html> myapp.html: {% extends "myapp/base.html" %} {% load static %} {% load crispy_forms_tags %} {% block title %}My App{% endblock title %} {% block stylesheets %} {{ block.super }} {% endblock stylesheets %} {% block content %} {% crispy formset helper %} {% endblock content %} {% block footer %} <script type="text/javascript" src="{% static 'admin/js/vendor/jquery/jquery.js' %}?{% now "U" %}"></script> {{ formset.media }} {% endblock %} settings.py (relevant piece): STATIC_ROOT = 'C:/Users/username/mysite/static/' STATIC_URL = … -
NoReverseMatch at ... django issue
When I try delete my post Django show me error. How I should repair it? I try some options... views.py: def delete_post(request, slug): post= get_object_or_404(Post, post=slug) post.delete() return redirect('post:post_detail') models.py class Post(models.Model): post= models.CharField(max_length=15) description_post = models.CharField(max_length=15) def get_absolute_url(self): return reverse("board:delete_card", kwargs={"slug": self.post}) def __str__(self): return self.post HTML( delete link) <a class="nav-link" href="{% url 'board:delete_post' slug=post %}"> urls.py: url(r'^table/post/delete/$', views.delete_post, name='delete_post') Reverse for 'delete_post' with arguments '' not found. Thanks in advance! -
Initiate a Model based on another model's field in Django (Model inheritance)
I am trying to build an attendance management application.In this application, a user while creating an institute can choose from two attendance types : Daily or Subject wise. Based on the type chosen while creating a new institute instance I wish to initiate the corresponding Attendance model for the same. Here are the models I have planned so far: class Institute(models.Model): attendance_type = models.CharField(choices=ATTENDANCE_CHOICES) #other fields class AttedanceMixin(models.Model): institute = models.ForeignKey(Institute) #other fields class Meta: abstract = True class DailyAttendance(AttendanceMixin): #fields for dailyattendance class SubAttendance(AttendanceMixin): #fields for subject wise attendance So, for example when I choose attendance type to be Daily while creating an Institute object then all the attendance objects which are linked to that particular institute should be of DailyAttendance model and I can use the fields of DailyAttendance model. Any idea about how I can proceed further? -
hide site label from django admin
I am a beginner in django and i used sites framework to make multiple instances of a website use the same code and database but in my django admin page i noticed that it display a label site in each model to make the get or create queries based on the selected site but i want to make it use the current site to get or create objects and remove this selection from all models. how can i do this ? thanks. This is the admin.py code in my models: from survey.models import * from django.forms.models import ModelForm from django.forms.widgets import RadioSelect from django import forms from django.utils.safestring import mark_safe from django.contrib import admin admin.site.register(AnswerRange, AnswerRangeAdmin) admin.site.register(Role,RolAdmin) admin.site.register(Indicator, IndicatorAdmin) admin.site.register(CharacteristicCategory) admin.site.register(Characteristic, CharacteristicAdmin) admin.site.register(Practice, PracticeAdmin) admin.site.register(UserProfile, UserProfileAdmin) admin.site.register(Macro) admin.site.register(ReportPassword) admin.site.register(Demographic, DemographicAdmin) admin.site.register(Message) admin.site.register(Comment) admin.site.register(InstanceSetting) admin.site.register(UsersWaitingList) admin.site.register(ticket) admin.site.register(Answer) admin.site.register(Option) -
Django forms.media pulling media from pip installed app
I have created a customized python app package which is a custom widget I can use in my Django Project. The custom widget is pip installed from my requirements.txt and can be found in my environment folder env/lib/python2.7/site-packages/custom_widget... Inside that there is a static folder with js and css files. The forms.Widget object itself is created with its own form assets.. see below: css = { 'all': ( 'css/datatables/dataTables.bootstrap.css', 'css/custom-widget.css', ), } js = ( 'js/plugins/datatables/jquery.dataTables.js', 'js/plugins/datatables/dataTables.bootstrap.js', 'js/custom-widget.js', ) The dataTables css and js are an older version than that of the ones in my Django Project staticfiles directory. Other locations in my Django project use newer versions of datatables. When I use the widget in an app under my project and try to include the form assets in the template with {{form.media}}, it pulls the dataTables css and js from my Django Project staticfiles directory rather than the static directory defined under my custom widget. This is a problem because they are different versions and my widget does not behave correctly. I am wondering if there is a way to pull my assets from the custom app that has been pip installed rather than from the static files defined … -
SSH and FTP showing different files
I am using a host to try and deploy my Django site but I am confused by the SSH vs. FTP. Background info: I got the IP address, name and password from my host for the VPS. I logged in using the same information via Putty and via WinSCP. Both show me as having accessed root@[VPS IP Address]. Running ls on Putty shows nothing (no files or folders). So I created a file hello.txt. WinSCP shows a lot of folders at the root, unlike Putty. I then searched all the folders for the hello.txt that I created and it's nowhere to be found. Why would accessing the same VPS via two different methods show completely different things? -
How can I get the number of content of output parsed excel?
I wanna parse excel and put data in the model(User). I wrote in views.py #coding:utf-8 from django.shortcuts import render import xlrd import os import glob book = xlrd.open_workbook('./data/excel1.xlsx') sheet = book.sheet_by_index(0) rate_dict = {} for row_index in range(1,sheet.nrows): rows = sheet.row_values(row_index) print(rows) for i in range(len(rows)): print(rows[i]) In print(rows),I got these data [empty:'', text:'1', text:'America', text:'●', text:'●', text:'×', text:'100'][empty:'', text:'2', text:'UK', text:'●', text:'●', text:'●', text:'50'][empty:'', text:'3', text:'China', text:'×', text:'●', text:'×', text:'80'][empty:'', text:'4', text:'India', text:'×', text:'×', text:'×', text:'40'] Now I wanna get the number of these data,so I wrote for i in range(len(rows)):,but this code counts the number of elements of one list.So len(rows) is 6(='1','America',text:'●',text:'●',text:'×',text:'100').I wanna count the number of rows,so print out 4.How can I do my ideal thing?Why can't i use len? -
JSON parsing under django framework
I'm currently learning both django and javascript I passed a json string from python to javascript and this is the string i got. [{"model": "polls.question", "pk": 1, "fields": {"question_text": "anything", "pub_date": "2017-09-07T09:36:07Z"}}, {"model": "polls.question", "pk": 2, "fields": {"question_text": "hi", "pub_date": "2017-09-07T10:01:39Z"}}] whenever I use the JSON.parse method my javascript crashes javascript: let mylist = "{{ question_list_as_json | escapejs }}"; let temp = JSON.parse(mylist); python: question_list = Question.objects.all() question_list_as_json = serializers.serialize('json', question_list) return render(request, 'polls/index.html', {'question_list': question_list, 'question_list_as_json': question_list_as_json}) -
Which field to use for storing a multiple dictionaries in Django models?
I was about to use buy_data=ArrayField(ArrayField(models.FloatField(default=0.0)),blank=False,default=[0.0,0.0]) for storing data like [123.0,321.0] for a stock where the first element in the data corresponds to the buying price and the second to the quantity of the stock bought, when I stumbled upon some articles which said that it is a bad practice. What I plan to store are multiple data entries with each one preferably like this {'buy_price': 123.0, 'quantity': 100}.Which field should be the most apt.