Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to Deploy Django on apache2 server using native python installation ?
I have developed an Django application which uses a python binding for c/C++ based dependency. Now How can I deploy this application without virtualenv using native python installation. My "000-default.conf" <VirtualHost *:80> # The ServerName directive sets the request scheme, hostname and port that # the server uses to identify itself. This is used when creating # redirection URLs. In the context of virtual hosts, the ServerName # specifies what hostname must appear in the request's Host: header to # match this virtual host. For the default virtual host (this file) this # value is not decisive as it is used as a last resort host regardless. # However, you must set it for any further virtual host explicitly. #ServerName www.example.com Alias /static /home/jai/myproject/protocol/static <Directory /home/jai/myproject/protocol/static> Require all granted </Directory> <Directory /home/jai/myproject/pep_learn> <Files wsgi.py> Require all granted </Files> </Directory> WSGIDaemonProcess myproject python-path=/home/jai/myproject:/home/jai/myproject/myprojectenv/lib/python2.7/site-packages WSGIProcessGroup myproject WSGIScriptAlias / /home/jai/myproject/pep_learn/wsgi.py ServerAdmin webmaster@localhost DocumentRoot /var/www/html # Available loglevels: trace8, ..., trace1, debug, info, notice, warn, # error, crit, alert, emerg. # It is also possible to configure the loglevel for particular # modules, e.g. #LogLevel info ssl:warn ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined # For most configuration files from conf-available/, which are # enabled or … -
Step by step with django-jet-demo
I am trying to see django-jet-demo in action, i.e. https://github.com/geex-arts/django-jet-demo, but It didn't work. git clone https://github.com/geex-arts/django-jet-demo.git mkvirtualenv venv cd django-jet-demo pip install -r requirements/base.txt django makemigrations I have the errors 1- configparser.NoSectionError: No section: 'common' If I remove config.get(..., 'common') inside application/settings.py 2- configparser.NoSectionError: No section: 'email' If I remove config.get(..., 'email') inside application/settings.py 3- configparser.NoSectionError: No section: 'database' How could I fix this problem? What are the steps to make django-jet-demo works? Does it work well on your computer? -
Django, when using ForeignKey field, which is better blank=True or null=True?
From: https://docs.djangoproject.com/en/2.0/ref/models/fields/#django.db.models.Field.null Avoid using null on string-based fields such as CharField and TextField. If a string-based field has null=True, that means it has two possible values for “no data”: NULL, and the empty string. In most cases, it’s redundant to have two possible values for “no data;” the Django convention is to use the empty string, not NULL. So What is better on ForeignKey Field? ForeignKey field is not string-based field, isn't it? I wonder what is convention for ForeignKey in django. null=True is better or blank=True is better? In performance, convenience or somewhat anything. -
unique_together with a field from a foreign key in a through table for a ManyToMany relation
I am developing a Django 2.0 project app. It has a (non-working) models.py file, which looks something like this: from django.db import models from django.utils import timezone class Computer(models.Model): name = models.CharField(max_length=25) def __str__(self): return "Computer {}".format(self.name) class Software(models.Model): name = models.CharField(max_length=25) description = models.CharField(max_length=1024, blank=True) def __str__(self): return self.name class SoftwareVersion(models.Model): software = models.ForeignKey(Software, on_delete=models.CASCADE, related_name="versions") version = models.CharField(max_length=100) released_at = models.DateTimeField(default=timezone.now) def __str__(self): return "{} {}".format(self.software, self.version) class ComputerSoftwareBundle(models.Model): computer = models.ForeignKey(Computer, on_delete=models.CASCADE, related_name="bundles") installed_at = models.DateTimeField(default=timezone.now) versions = models.ManyToManyField(SoftwareVersion, through="BundleSoftwareVersion", related_name="bundles") class BundleSoftwareVersion(models.Model): bundle = models.ForeignKey(ComputerSoftwareBundle, on_delete=models.CASCADE) version = models.ForeignKey(SoftwareVersion, on_delete=models.CASCADE) class Meta: unique_together = (("bundle", "version__software"),) The app tracks software bundles currently or previously installed on computers. The thing here is that a bundle should not contain more than one version of the same software. Also, SoftwareVersion should contain a reference to Software, because the same version string has a different meaning for different pieces of software. The code does not work as described in this Stackoverflow answer. I left the unique_together line in to illustrate what I am trying to achieve. I've tried to work around this limitation of Django (not being able to use fields referred to via a foreign key in unique_together) by … -
Validation error (required) in Django ModelForm when using a field that is extra to the Model fields
I have 2 models Company and CompanyLogo. class CompanyLogo(models.Model): company = models.ForeignKey(Company, on_delete=models.CASCADE) logo = models.ImageField(upload_to='st/a') Instead of using CompanyLogo as an inlineformset I want to use it like afield in the CopmanyModelForm. I do this because I need just a specific size of the logo, plus some asyncronus tasks, and I need specific template for the widget. class CompanyModelForm(forms.ModelForm): logo = forms.ImageField(widget=CompanyLogoWidget) class Meta: model = Company fields = ['name', 'short_description', 'description', 'address', 'city', 'zip'] when I save the Company object I save also the logo: def save(self, commit=True): company = super().save(commit=commit) CompanyLogo.objects.update_or_create(company=self.company, defaults={"logo": self.fields['logo']}) The logo field is mandatory/required to save the Company form and be an image. The issue is that even if the field is completed(added a file), I get a validation error "This fields is required". I suppose the error happens because the field is not in the Company Model, and this is why he doesn't see the value. -
Customize updated|timesince in a django template
I've a django template which displays the last time an element was updated in a database like this: <small>updated {{ updated|timesince }} ago</small> where updated is the timestamp of the last update of that element. I, however, don't like thw way it is displaying this information. For example if i's just updated it sais: 'updated 0 minutes ago' which looks kinda wierd. I would like it to say something like: 'updated just now' So I wrote this piece of code to try to make that happen: {% if is_updated%} {% if updated|timesince == '0 minutes' %} <small>updated just now </small> {% else %} <small>updated {{ updated|timesince }} ago</small> {% endif %} {% endif %} here is_updated is a context variable set like this: if element.updated != element.uploaded: is_updated = True however it's always showing me 'updated X minutes ago' even if the element hasn't been updated. What could I be doing wrong? Model for the element: title = models.CharField(max_length=120) identifier = models.SlugField(blank=True, null=True) category = models.CharField(max_length=120, default="uncategorized") description_short = models.CharField(max_length=300, default="none") description = models.TextField(default="none") uploaded = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) time = models.IntegerField() -
Wagtail customizing struct block template on admin
I have read the 'custom-editing-interfaces-for-structblock' section of documentation. Then I have written: settings = StructBlock([ ('width', blocks.CharBlock(required=False, max_length=20 ) ), ('background_color', blocks.CharBlock(max_length=10, required=False)) ], form_template = 'personal_web/admin_blocks/section_settings.html' ) I have copied the code in wagtail/admin/templates/wagtailadmin/block_forms/struct.html to my custom struct template for better customizing. On the admin there is an error: 'builtin_function_or_method' object is not iterable... In template /Users/burakk/BurakWorks/Web/VIRTUAL_ENVIRONMENTS/python3.6.1_dj_1_11/lib/python3.6/site-packages/wagtail/wagtailadmin/templates/wagtailadmin/block_forms/sequence_member.html, error at line 23 By the way I am using jinja as template renderer, django 1.11.6, python 3.6 -
Django Heroku App not compatible with buildpack
Sorry about bad English first. I'm trying to push my existing django project to heroku, and i try to use heroku-django-template to modify my django project. My interpreter(or compiler?) is Python 2.7.14 and I didn't use virtual env. But after a whole day of trying, i only got this error repeatly: remote: -----> App not compatible with buildpack: https://codon-buildpacks.s3.amazonaws.com/buildpacks/heroku/python.tgz remote: More info:https://devcenter.heroku.com/articles/buildpacks#detection-failure remote: remote: ! Push failed remote: Verifying deploy... remote: remote: ! Push rejected to py-mosaic-image. remote: To https://git.heroku.com/py-mosaic-image.git ! [remote rejected] master -> master (pre-receive hook declined) here's my dictionary: -- .git/ -- my-project/ ---- some-app-dir/ ---- some-app-dir/ ---- my-project/ ---- __init__.py ---- .env ---- db.sqlite3 ---- manage.py ---- Pipfile ---- Pipfile.lock ---- Procfile ---- requirements.txt ---- runtime.txt and here's some code( many are generated by heroku-django-template ) .env WEB_CONCURRENCY=2 Pipfile (ignore some \r) [[source]] url = "https://pypi.python.org/simple" verify_ssl = true name = "pypi" [requires] python_version = "2.7" [packages] dj-database-url = "==0.4.2" django = "==2.0" gunicorn = "==19.7.1" "psycopg2" = "==2.7.3.2" whitenoise = "==3.3.1" [dev-packages] Procfile web: gunicorn py-mosaic-image.wsgi --log-file - requirements.txt attrs==17.4.0 autobahn==17.10.1 Automat==0.6.0 backports.functools-lru-cache==1.4 constantly==15.1.0 cycler==0.10.0 Django==1.8.18 django-socket-server==0.0.4 django-socketio==0.3.9 gevent==1.2.2 gevent-socketio==0.2.1 gevent-websocket==0.10.1 greenlet==0.4.12 gunicorn==19.7.1 hyperlink==17.3.1 incremental==17.5.0 matplotlib==2.1.0 numpy==1.13.3 olefile==0.44 Pillow==4.3.0 PyAudio==0.2.11 pyparsing==2.2.0 python-dateutil==2.6.1 pytz==2017.3 scipy==1.0.0 six==1.11.0 … -
Django form error:local variable 'context' referenced before assignment
I'm collecting data from form, processing data(right now I'm not) and displaying the result on the same HTML page from where the user submits the form. Here is my views.py file: def index(request): template = 'predictor/index.html' if request.method =='POST': form = EvalForm(request.POST) if form.is_valid(): text ='thank you for submitting form' else: text='something wrong.' context: { 'text':text, } return render(request,template,context) else: form = EvalForm() return render(request,template) Here is my index.html file <form method="POST" action="{% url 'predictor' %}"> {% csrf_token %} //all input fields including submit button here </form> <div class="result"> {{ text }} </div> All other things like urls are configured properly. What I'm doing wrong here? -
uWSGI -> Logstash Connectivity Troubleshooting
I run a Django application(NGINX+uWSGI) in a Docker container and the following configurations are used in uwsgi.ini to connect to the logstash(It has both TCP and UDP port opened). logger = file:/var/log/uwsgi_server.log logger = socket:192.168.0.167:5591 But the logstash never receives any log messages from UWSGI based on the above configuration. The logs are being populated in the configured log file. Moreover, I can telnet to the configured host/port inside the container and I can see the test log messages in the logstash which I gave in the terminal. Is there any way to troubleshoot it further? -
Dynamic querying for tagulous (django)
I'm using tagulous and have 2 sets of tags on my model e.g. class MyModel(models.Model): primary_tags = TagField(to=ActionToolTreeTag, blank=True, null=True, related_name='primary') secondary_tags = TagField(to=ActionToolTreeTag, blank=True, null=True, related_name='secondary') class ActionToolTreeTag(TagTreeModel): class TagMeta: protected = True This works fine. However, on my admin frontend I have a querybuilder (Jquery QueryBuilder) and want to query the tags. It creates queries in json. I need to convert these queries to use the django ORM to pull out the model instances that fit the query. I've tried adapting a recursive script I found that looks like this: def build_query(self, json_query): if 'condition' in json_query.keys(): if json_query['condition'] in ['AND', 'OR']: if json_query['condition'] == 'AND': qop = 0 else: qop = 1 resultq = None for rule in json_query['rules']: q = self.build_query(rule) if q != None: if resultq == None: resultq = q else: if qop == 0: resultq = resultq & q elif qop == 1: resultq = resultq | q else: if json_query['operator'] == 'equal': cmd = 'exact' elif json_query['operator'] == 'contains': cmd='in' else: cmd = '' field_name = json_query['field'] kwname = str("%s%s%s" % (field_name, '__', cmd)) if json_query['operator'] == 'contains': kwdict = {kwname : [json_query['value'],]} else: kwdict = {kwname : json_query['value']} resultq = Q(**kwdict) … -
Displaying the objects from my class on the base template in Django
Sorry if my english is confusing I created a class Button on my app menu models.py (App 'menu') from django.db import models class Button(models.Model): button_name = models.CharField(max_length=30, verbose_name='xxx') button_dirurl = models.CharField(max_length=40, verbose_name='xxx') button_corequise = models.BooleanField(default=False, verbose_name='xxx') def __str__(self): return self.button_name What I would like to do is to display all the objects into base.html, located into the template at the root. I tried to do a tag, but I would like to add some html elements and as far as it goes I won't be able to do much menu_tags.py (App 'menu') from django import template from menu.models import Button register = template.Library() @register.simple_tag def show_menu(): a = Button.objects.all() return a I'm sorry if this was already asked but I don't know how to google this as my english is quite bad. Thanks ! -
Display URLS as links(Higlight, blue color, clickable etc) in Django Text Area Field
I have a site where users can post stuff (mainly links with comments.) Now when I render the text area filed, the links are being displayed as plain text. They are not clickable, blue links. I want to render identified urls as links which are clickable. Don't suggest a language or syntax in which the user has to prepend something to make it a link. Instead I want an automatic way for links to be clickable. Like how SO and SE and other forums do it. -
Using Sql Server with Django 2.0
I would like to use Django 2.0 with legacy MS SQL Server database. Latest information regarding usage Django with MS SQL Server i could find is Using Sql Server with Django in production/These days and it is about Django 1.11 Most supported seems django-pyodbc-azure but it's not supporting Django 2.0 yet: django-pyodbc-azure issue #124 Is there any alternative? -
Django Test: TypeError: __init__() got an unexpected keyword argument
I get the error from the ProductTestCase: ...setUp department = DepartmentForm(department_name_text=self.department_name) ... ...in __init__ super(DepartmentForm, self).__init__(*args, **kwargs) TypeError: __init__() got an unexpected keyword argument 'department_name_text' It would be great to know how to fix this issue and why it only occurs when on Foreign keys. I have added in Department test as well, it works fine. Thank you for your time. Department Test class DepartmentTestCase(ModelTestCase): def setUp(self): super(DepartmentTestCase, self).setUp() self.department_form = self.get_department_form(department_name_text=self.department_name) def test_valid_input(self): self.assertTrue(self.department_form.is_valid()) Product Test class ProductTestCase(ModelTestCase): @classmethod def setUpTestData(cls): super(ProductTestCase, cls).setUpTestData() def setUp(self): super(ProductTestCase, self).setUp() self.product_data = {'barcode_text': self.barcode } department = DepartmentForm(department_name_text=self.department_name) department_inst = None if department.is_valid(): department_inst = department.save(commit=False) department_inst.pk = None department_inst.save() maker = MakerForm(maker_name_text=self.maker_name) maker_inst = None if maker.is_valid(): maker_inst = maker.save(commit=False) maker_inst.pk = None maker_inst.save() self.product_data.update({'name_text': department_inst, 'from_maker': maker_inst}) def test_valid_input(self): product_form = ProductForm(**self.product_data) self.assertTrue(product_form.is_valid()) Department Form class DepartmentForm(ModelForm): field_names = {'department_name_text': 'Department Name'} class Meta: model = Department fields = ['department_name_text'] def __init__(self, *args, **kwargs): super(DepartmentForm, self).__init__(*args, **kwargs) for field, name in self.field_names.items(): self.fields[field].label = name -
Django: Problems regrouping a regroup
I'm trying to get a list of countries that are stored in my Post model. Models: Articles App: class Post(models.Model): title = models.CharField(max_length=100, unique=True) ... country_slug = models.ManyToManyField(Country_Data, related_name='nation_slug') Nation App: class Country_Data(models.Model): name = models.CharField(max_length=250) country_slug = models.CharField(max_length=250) View: get_context_data: self.sport = get_object_or_404(Sport, sport_slug=self.kwargs['sport_slug']) context['country'] = Post.objects.filter(post_category=self.sport) Template: {% for nation in country %} <ul> {% regroup nation.country_slug.all by name as country_list %} {% for country in country_list %} <li>{{ country.grouper }} <ul> {% for item in country.list %} <li>{{ item.name }}</li> {% endfor %} </ul> </li> {% endfor %} </ul> {% endfor %} The problem I'm having is looping through the list of countries and only pulling out one result. Currently, because of how it needs to be set up, it is pulling out one country per news article, which is obviously not useful for this because I'll end up with hundreds of duplicates. I cant work out how to get it to loop through the Post model, pull out all the "country_slug" fields, then regroup that into a list of unique countries. I've read through the documentation and a few other questions multiple times, I'm just failing to understand exactly what I'm doing wrong. -
Securing API's with Multi Factor Authentication
I want to secure my API with Multi-factor-Authentication on top of Auth Token/JWT. I have been searching but couldn't find any package that can work with drf. I am thinking to write my own django app. Any comments on what should be the architecture ? One solution that comes to my mind is to introduce the token base architecture.If a user is accessing the mfa secured api then the request instance should be saved alongside a token and a sms should be sent to his mobile (In case of mobile as mfa) and response should be a that token. Then another request should be made to a mfa endpoint with token and mfa-code. Once verified, We would take his previous request object and complete the request. -
How can I ensure that python files/scripts executed by the web server have been signed and valid so that alteration to script will not run?
Can I create loader or verification that the python files/scripts executed by the web server have been signed and valid so that alteration to script will not run if signature doesn't match? Is this possible with Django or any other python framework and server? -
How to test new Django 1.10+ MIDDLEWARE classes
I'm upgrading existing middleware to a new style 1.10+ Django middleware. Previously it was one similar to this: class ThreadLocalMiddleware(MiddlewareMixin): """ Simple middleware that adds the request object in thread local storage.""" def process_request(self, request): _thread_locals.request = request def process_response(self, request, response): if hasattr(_thread_locals, 'request'): del _thread_locals.request return response def process_exception(self, request, exception): if hasattr(_thread_locals, 'request'): del _thread_locals.request after rewrite to the new style: class ThreadLocalMiddleware: def __init__(self, get_response=None): self.get_response = get_response def __call__(self, request): _thread_locals.request = request response = self.get_response(request) if hasattr(_thread_locals, 'request'): del _thread_locals.request return response def process_exception(self, request, exception): if hasattr(_thread_locals, 'request'): del _thread_locals.request My question is how to test that the middleware sets the request in the _thread_locals? Previously it was as easy as calling the process_request method in tests. Now I have only the call which will erase the variable at the end. -
Is it possible to pass extra command line arguments in django integration testing?
I want to pass extra argument in my integration testing of django app. I'm trying below command line argument for same. python ./manage.py test my_api.test.end_to_end_test "IPaddress of AWS instance" but I'm getting error. Traceback (most recent call last): File "./manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/usr/local/lib/python2.7/dist-packages/django/core/management/__init__.py", line 363, in execute_from_command_line utility.execute() File "/usr/local/lib/python2.7/dist-packages/django/core/management/__init__.py", line 355, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/usr/local/lib/python2.7/dist-packages/django/core/management/commands/test.py", line 29, in run_from_argv super(Command, self).run_from_argv(argv) File "/usr/local/lib/python2.7/dist-packages/django/core/management/base.py", line 283, in run_from_argv self.execute(*args, **cmd_options) File "/usr/local/lib/python2.7/dist-packages/django/core/management/base.py", line 330, in execute output = self.handle(*args, **options) File "/usr/local/lib/python2.7/dist-packages/django/core/management/commands/test.py", line 62, in handle failures = test_runner.run_tests(test_labels) File "/usr/local/lib/python2.7/dist-packages/django/test/runner.py", line 600, in run_tests suite = self.build_suite(test_labels, extra_tests) File "/usr/local/lib/python2.7/dist-packages/django/test/runner.py", line 484, in build_suite tests = self.test_loader.loadTestsFromName(label) File "/usr/lib/python2.7/unittest/loader.py", line 91, in loadTestsFromName module = __import__('.'.join(parts_copy)) ImportError: No module named 35 -
Django: python venv: Can i edit files in the lib/python3.6/site-packages
I am using Django 2.0. and package fcm-django==0.2.13 After upgrading to Django 2.0 I have found an error in lib/python3.6/site-packages/fcm_django/api/rest_framework.py it says 'bool' object is not callable at the below line if user is not None and user.is_authenticated(): I have found the solution at https://github.com/xtrinch/fcm-django/issues/43 and also is_authenticated() raises TypeError TypeError: 'bool' object is not callable I have to replace is_authenticated() with is_authenticated (without the brackets) in the lib/python3.6/site-packages/fcm_django/api/rest_framework.py file. The latest package fcm-django==0.2.13 is not yet updated with this error. SO i have edited the file /home/test/venv/lib/python3.6/site-packages/fcm_django/api/rest_framework.py Then i save the file. But when i run the url. It shows the same error in the file rest_framework.py if user is not None and user.is_authenticated(): but i have changed is_authenticated() to is_aunthenticated Why django/venv is not reflecting the changes? -
What is causing my consumer to be sent 2 arguments--one, in addition to the "message"?
I'm implementing the multichat example and unable to figure out what's causing this error. Here's the full traceback: 2018-01-05 07:35:48,017 - ERROR - worker - Error processing message with consumer chat.consumers.chat_join: Traceback (most recent call last): File "/Users/sng/.virtualenvs/blog-api/lib/python2.7/site-packages/channels/worker.py", line 119, in run consumer(message, **kwargs) File "/Users/sng/.virtualenvs/blog-api/lib/python2.7/site-packages/channels/sessions.py", line 78, in inner return func(*args, **kwargs) File "/Users/sng/.virtualenvs/blog-api/lib/python2.7/site-packages/channels/auth.py", line 42, in inner return func(message, *args, **kwargs) File "/Users/sng/Dev/django/blog-api/src/chat/utils.py", line 14, in inner return func(message, args, **kwargs) TypeError: chat_join() takes exactly 1 argument (2 given) I believe I've copied the code nearly as is, so I don't know how it went wrong. Here's the consumer: @channel_session_user @catch_client_error def chat_join(message): room = get_room_or_error(message["room"], message.user) if NOTIFY_USERS_ON_ENTER_OR_LEAVE_ROOMS: room.send_message(None, message.user, MSG_TYPE_ENTER) room.websocket_group.add(message.reply_channel) message.channel_session['rooms'] = list(set(message.channel_session['rooms']).union([room.id])) message.reply_channel.send({ "text": json.dumps({ "join": str(room.id), "title": room.title, }), }) Routing: custom_routing = [ route("chat.receive", chat_join, command="^join$"), route("chat.receive", chat_leave, command="^leave$"), route("chat.receive", chat_send, command="^send$"), ] In regular Django, I think the parallel would be the URLconf sending one too many args to the view. I'm not sure where message is being sent from, and so unsure if anything else is being sent alongside it. The traceback hints at it being caused in relation to sessions. Not quite sure where, or how to debug in … -
Automatically Append host, port no and media folder path in url while retrieve in Django rest framework
I'm using Django rest framework APIView method to retrieve image field (Image saved in local and name saved in DB). Is there any way to append Host, Port and media Folder automatically. Now i'm appending manually. But if i'm using Viewset it appended automatically. Both method i'm using for different scenario. Can anyone suggest some way to solve the issues. -
Include stuff from another app in base template?
Sorry for the confusing title I'm not a native english speaker. I'm trying to add a condition to my base.html but I don't know where to import the stuff from my other app. I would like to import my class Button in my folder "models" in my app "menu" to do this (If it's not wrong) : {% for Button in menu.Button %} Thanks for the help ! -
How to view the Django website deployed on AWS EC2? Apologies for this silly query.
After deploying my django website on AWS EC2 Linux instance, its running at the local server http://127.0.0.1:8000/ . At which URL can I now see my website live? I have the server IP and port number but doesn't seem to work.