Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Getting started with web developmemt
I am from embedded system development field, so please forgive me if question sound naive.Recently, I got thrilled about web development and learned python. Now thinking to start learning Django for backend web development. I searched the net but couldn't found collective information about the steps involved in developing the websites. Django will do the backend but how much? Will it cover the whole backend development or I need some or deep knowledge about other language/framework? What other factors will be involved or i need to cover beside django? Can anyone please mention the steps from starting with django till the deployment of website? Backend plus frontend? -
Django 403 Javascript Post Fetch
I've been trying to POST an audio file from browser to Django using JS. The object is on a FormData. function makeLink(){ let blob = new Blob(chunks, {type: media.type }) let fd = new FormData; fd.append("audioRecording", blob); fetch("/home/django/django_project/static/audio", {method:"POST", body:fd}) .then(response => response.ok) .then(res => console.log(res)) .catch(err => console.error(err)); } I have added decorators for exempting csfr. Like this: @ensure_csrf_cookie @csrf_exempt def audio(request): return render(request, 'index.html') Why is this still returning 403? -
Remaining only digits - Create method
I have a field which is called fax. It return a fax number under different form. For instance, it could be 1-800 222-2222. I would like to create a property compress_fax get a product without anyone other information than digits. Hence, that property will change 1-800 222-2222 to 18002222222. How could I do such thing -
Django QuerySet filter ValueError not caught?
I am trying to filter a Django QuerySet. I know that sometimes the filter terms will be invalid. In this case, I want to catch the error. Here is a silly contrived example: try: MyModel.objects.filter(pk='invalid_pk') except ValueError: print "you messed up" print "you didn't mess up" Now this should raise a ValueError (because 'invalid_pk' is not a valid pk - it ought to be a positive integer, obviously). But I never reach the except block. Any suggestions? -
Phyton(Django) vs Phalcon (PHP) for Bigdata web application development
i'm trying to develop a BigData application and i'm wondering what platform is best to use. i am an ardent laravel PHP developer and i have been programming laravel for over 4 years now. i've followed opinions online and realized that laravel is slow and though good for lightbased web applications, i cant utilize it in what i'm attempting to do but i am wondering if phyton would be faster for such an application that is going to be fluid and would scale over time. since my target is a vast amount of data i would be needing a framework that is very efficient in terms of speed and data processing. my options are Phalcon - a php framework built as a C extension, and Django - built on phyton, please which would be best solution for this. i need your opinions. thanks. -
Django: select data from 2 models
Good day! I have 2 models and I am trying to get sql equivalent of : select * from both models where order=xx. Appreciate little assistance :) class Orders(models.Model): order_id = models.AutoField(primary_key=True) created = models.DateTimeField(auto_now_add=True) class ResourcePool(models.Model): email = models.EmailField() item_a = models.CharField() item_b = models.CharField() item_c = models.CharField() order_id = models.ForeignKey(Orders) Tried the following, but it does not inlude fields from 'Orders' model ResourcePool.objects.filter(order_id__pk=26).values() ResourcePool.objects.filter(order_id__pk=26).select_related().values() -
Django app ERR_EMPTY_RESPONSE when adding custom middleware to settings.py
I've created a LoggedInUserMiddleware in my project/app/middleware.py file and added it as the last entry in the MIDDLEWARE portion of my project/master/settings.py file. Before adding it to settings.py the app responds just fine. After adding it to settings.py i get an ERR_EMPTY_RESPONSE from any url of my app. My LoggedInUserMiddleware currently looks like this just to try to get it to not crash things. class LoggedInUserMiddleware(object): def process_request(self, request): return None As I understand it, that middleware should execute with every single new html request, but do absolutely nothing. -
Getting IP addresses from known MAC addresses from server side
I have a server that has list of MAC addresses of devices (think IOT devices). Is it possible to get their IP addresses? Devices with these MAC addresses are in same network like the client (through simple web interface) sending requests to server. I am aware that this question maybe a little vague, but I will edit it with any new information I get. I am using python (Django framework) for server. -
Sql sort query to sort parents and childrens of the same model
I have a Comment model which has relationship to itself meaning each comment has a comment_parent_id. I want to sort comments so first parent comment comes first then all of its children, then next comment, after that next comment children, etc. Is it a way to do it in a single sql query? I'm using Django so both Django ORM or raw queries works for me. -
In Django 1.8, what does "USERNAME_FIELD" mean by authentication system?
I have been learning Django for a week, In order to implement authentication system, I have created models.py file as tutorials. from django.db import models from django.contrib.auth.models import AbstractBaseUser class User(AbstractBaseUser): username = models.CharField('username', max_length = 10, unique = True, db_index = True) email = models.EmailField('email address', unique = True) joined = models.DateTimeField(auto_now_add = True) is_active = models.BoolenField(default = True) is_admin = models.BoolenField(default = False) USERNAME_FIELD = 'username' def __unicode__(self): return self.username I understand what username, email, joined, is_active, is_admin means, but I can't understand why I use USERNAME_FIELD. Is username created by models.CharField equal to the 'username' in USERNAME_FIELD? Why do I have to create USERNAME_FIELD? What does def __unicode__(self): function mean? -
Querying against multiple values with Django Querysets
I have a Foo and a Bar model. Each model has a GeoDjango point attribute. I would like to have returned a query set that contains all Bars within a 2 Kilometer radius of any Foo. There are roughly 5000 Foos and 900 Bars so any exhaustive solution will take a long time, such as my current solution: query = Q() radius = 2 for foo in Foo.objects.iterator(): if foo.point: point = foo.point query = query | Q(point__distance_lt=(point, radius)) bars = Bar.objects.filter(query) Is there a faster way to do this? Or have I made any mistakes that make it incalculable? -
git and django migrations: ignore the migrations files
Should I keep django migrations files in a git repository? In a developers team, how they manages their database changes. For example, Tom has made changes in their models, and ran makemigrations and migrate, his database now has changed, as well his migrations files, keeping his migration story. Meantime, Bob has made changes too. He has his migration files that are about another models, He ran makemigrations and migrate commands, and his db changed. Tom and Bob are working in the same app, so, They share the same migrations files. And the same db too. So, what will happen when Bob push their code to git repo, and later Tom pull or fetch it from git repo? The migrations files will be mixed and their stories will be broken. Also, what about with the db itself, if it is a sqlite file, should I keep it in git repo? -
Django-MSSQL projects - Looking for some sample projects
Am currently working on Django MSSQL project where i need to update and display records for the employee timesheet. Since am new to Django frame work am looking for some example projects. I couldnt able to find any satisfying sample/reference projects online. Can any one put up some links where i can find one. Note: Type of project am handling is similar to CRM/Timesheet. -
Dynamic tables with Django tables2
I'm using the django_tables2 package to display tables on my page. I have two sets of data which I want to display dynamically. <Table_1_A> <Table_1_B> <Table_2_A> <Table_2_B> <Table_n_A> <Table_n_B> In my views.py I have: primary_keys = {1, 2, ... n} # these are not simple or ordered integers tables_A = {} tables_B = {} for primary_key in primary_keys: tables_A['primary_key'] = TableA(table_A_queryset.filter(pk=primary_key)) RequestConfig(request).configure(tables_A[primary_key]) tables_B['primary_key'] = TableB(table_B_queryset.filter(pk=primary_key)) RequestConfig(request).configure(tables_B[primary_key]) return render(request, 'index.html', {'primary_keys': primary_keys, 'tables_A ': tables_A , 'tables_B ': tables_B }) TableA and TableB are defined in my tables.py In my templatetabs folder I have tags.py: @register.assignment_tag def get_table(table, primary_key): return table.get(primary_key) Finally in my index.html: {% load render_table from django_tables2 %} {% load tags %} {% block content %} {% for primary_key in primary_keys %} <div class="data_tables"> {% get_table tables_A primary_key as table_A %} {% render_table table_A %} <br> <br> {% get_table tables_B primary_key as table_B%} {% render_table table_B%} </div> {% endfor %} {% endblock content %} I'm running django 1.11 in pycharm and when I'm running in pycharm this works just fine. When I run this on a debian server I get en error. If anything is passed into primary_key, tables_A, and tables_B I get a 500 Internal Server Error. … -
Link send_mail with the button
I am trying to send a fax, and the way to do that is to send a mail with the function send_mail @staff_member_required @require_http_methods(['POST']) def fax_contract(request, pk=None): if request.is_ajax() and pk: print("Sending contract for request {}".format(pk)) try: contract = Contract.objects.get(pk=pk) except Contract.DoesNotExist: return HttpResponseNotFound(_('Contract not found')) now = datetime.datetime.now() last_faxed = contract.request.last_faxed_at if last_faxed and (now - last_faxed) < settings.LOANWOLF_FAX_GRACE_TIME: return JsonResponse({ 'error': True, 'reload': False, 'message': _('Please wait at least %(minutes)d minutes to resend the contracts') % { 'minutes': settings.LOANWOLF_FAX_GRACE_TIME.seconds // 60}, }) else: contract.request.last_faxed_at = datetime.datetime.now() contract.request.save() subject, msg = ('', '') try: result = send_mail(subject, msg, settings.LOANWOLF_FAX_EMAIL_FROM, settings.LOANWOLF_FAX_EMAIL_TO.format(contract.request.customerprofile.fax), fail_silently=False) return send_mail, JsonResponse({ 'success': True, 'reload': True, 'result': result }) except Exception as e: return JsonResponse({'error': True, 'message': str(e)}) Here is the html code where I where the previous method : <div class="alert top white-text {{ object.state|request_state_color }}"> <i class="material-icons">info</i> <a href="{% url "contracts:fax" pk=object.contract.pk %}" class="btn pull-right {{ object.state|request_state_color }} darken-2 btn-process-request" data-turbolinks="false">{%trans "Fax contract" %}</a> {% if object.contract.pk %} <a href="{% url "contracts:as-pdf" pk=object.contract.pk %}" class="btn pull-right {{ object.state|request_state_color }} darken-2 workflow-bar-btn-spacer" data-turbolinks="false">{%trans "View contract" %}</a> {% endif %} <strong>{% trans "Once the signature is added to the request documents and approved, the deposit will be … -
Django 1.7 - Prefetch_related with matching field
I have the following model: class A(models.Model): field1 = models.ForeignKey(B) field2 = models.DateField() class B(models.Model): field3 = models.CharField(max_length = 25) Class C(models.Model) field4 = models.ForeignKey(B) field5 = models.datefield() I've used Prefetch_related as follows: C.objects.select_related('field4').prefetch_related(Prefetch('field4__a_set', to_attr='attr')) This returns a list through object.attr of all the related A objects for model C. However, I don't need all of them. I only need the ones where the dates match (ie: field2 == field 5). Is there a way to do this using the queryset part of Prefetch? Something like this? (obviously doesn't work.. but I believe there should be a fairly simple way to do this). C.objects.select_related('field4').prefetch_related(Prefetch('field4__a_set', queryset = C.objects.filter(field5__in = A.objects.filter(field2 = field5)), to_attr='attr')) -
Getting TypeError: __init__() missing 1 required positional argument: 'on_delete' when trying to add parent table after child table with entries
I have to classes in my sqlite database,a parent table named Categorie and the child table called Article.I created first the child table class and addes entries.So fisrt i had this: class Article(models.Model): titre=models.CharField(max_length=100) auteur=models.CharField(max_length=42) contenu=models.TextField(null=True) date=models.DateTimeField(auto_now_add=True,auto_now=False,verbose_name="Date de parution") def __str__(self): return self.titre And after i have added parent table,and now my models.py looks like this: from django.db import models # Create your models here. class Categorie(models.Model): nom = models.CharField(max_length=30) def __str__(self): return self.nom class Article(models.Model): titre=models.CharField(max_length=100) auteur=models.CharField(max_length=42) contenu=models.TextField(null=True) date=models.DateTimeField(auto_now_add=True,auto_now=False,verbose_name="Date de parution") categorie = models.ForeignKey('Categorie') def __str__(self): return self.titre So when i run python manage.py makemigrations <my_app_name>,i get this error: Traceback (most recent call last): File "manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "C:\Users\lislis\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django-2.0-py3.5.egg\django\core\management\__init__.py", line 354, in execute_from_command_line utility.execute() File "C:\Users\lislis\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django-2.0-py3.5.egg\django\core\management\__init__.py", line 330, in execute django.setup() File "C:\Users\lislis\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django-2.0-py3.5.egg\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\lislis\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django-2.0-py3.5.egg\django\apps\registry.py", line 112, in populate app_config.import_models() File "C:\Users\lislis\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django-2.0-py3.5.egg\django\apps\config.py", line 198, in import_models self.models_module = import_module(models_module_name) File "C:\Users\lislis\AppData\Local\Programs\Python\Python35-32\lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 986, in _gcd_import File "<frozen importlib._bootstrap>", line 969, in _find_and_load File "<frozen importlib._bootstrap>", line 958, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 673, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 665, in exec_module File "<frozen importlib._bootstrap>", line 222, in … -
WEKA is literally stuck halfway through classification once a new package in installed from package manager
I'm using WEKA 3.8 version and I have installed few packages from the package manager. Now when I try any classification algorithm, it takes too long and literally gets stuck with no output at all. Once I uninstall all the new packages from the package manager, WEKA works just fine. I have tried installing different versions of WEKA but the problem persists for all the versions that have a package manager associated with it. It would be of great help if anyone could suggest solutions to this problem because I really need to use some of the external packages. -
Django DB Router Sending Table to default DB instead of Correct One
I am creating a site that will be connected to 4 databases. I got the first three going no problem. I created a separate app for each db then created a router for each one. The problem with the last db is that the router is not triggering. It keeps sending the traffic to the default db. The default db is app2, and the db I want to use is 'Login'. Here is my router class LoginRouter(object): def db_for_read(self, model): if model._meta.app_label == 'Login': return 'Login' return 'default' Here is my Settings declaration: DATABASE_ROUTERS = ['reports.dbrout.CucRouter', 'reports.dbrout.CpsgRouter', 'reports.dbrout.LoginRouter', ] Like I said this worked fro the first three. What am I missing here that is not catching for the last one!!??? -
TypeError: __init__() got an unexpected keyword argument 'current_app'
I've deployed an app using Django 1.11 (Python/2.7.5) + Apache/2.4.6 + mod_wsgi/3.4 in a server running CentOS 7. The page is working fine but when after login I get the following error: TypeError at / __init__() got an unexpected keyword argument 'current_app' Request Method: GET Request URL: http://server.url/ Django Version: 1.11.1 Exception Type: TypeError Exception Value: __init__() got an unexpected keyword argument 'current_app' Exception Location: /usr/lib/python2.7/site-packages/django/shortcuts/__init__.py in render, line 49 Python Executable: /usr/bin/python Python Version: 2.7.5 Python Path: ['/var/www/html/webINR', '/usr/lib64/python27.zip', '/usr/lib64/python2.7', '/usr/lib64/python2.7/plat-linux2', '/usr/lib64/python2.7/lib-tk', '/usr/lib64/python2.7/lib-old', '/usr/lib64/python2.7/lib-dynload', '/usr/lib64/python2.7/site-packages', '/usr/lib/python2.7/site-packages'] Server time: Wed, 17 May 2017 12:31:10 +0000 The exception is in the render line: @login_required def index(request): return render(request, 'base.html') I don't think the error is caused by Apache and/or mod_wsgi (as the page is online). Any help? -
Setting a default value in choicfield in Django
I have a model field like this -- class Country(models.Model): country = CountryField() From which i have created a form like this -- class CountryForm(forms.Form): def __init__(self, *args, **kwargs): super(CountryForm, self).__init__(*args, **kwargs) self.fields['country'].widget.attrs.update( {'class': 'form-control'}) class Meta: model = xyz fields = ['country'] I have used django-country to create the country field. How can i set a default value/a country selected at forms ? Example: django-country have countries like this --- ('BD', 'Bangladesh'), ('An','Angola') etc. If i want to Angola be selected than i need to set a default value of An. -
How to generate html via dragndrop in django?
I need to implement wix.com functionality in my django app e.g genarate html page with drag'n'drop and save it to textfield of my django model. I've found django-cms package but it requires me to create new project and a lot of redudant actions. Is there solutions to implement frontend html editor? -
Display thumbnail in Django admin inline
i'm new to Django and trying to change how inline images are presented in the admin panel. Can I add a Preview tag above each 'Currently' to and show thumbnail? -
Unable to access html page
Hello i dont know what the problem.. why when i click on button about us i am not able to be in the new page, but the url in the website change. The page reads only the extended block but the new one no. this is the template (only the one related to the buttons) <div class="btn-group cust-dropdown pull-right"> <button type="button" class="btn btn-default dropdown-toggle cust-dropdown" data-toggle="dropdown"role="button"> <i class="glyphicon glyphicon-menu-hamburger"></i> </button> <ul class="dropdown-menu" role="menu"> <li><a href="{% url 'about' %}">About</a></li> <li><a href="">Documentation</a></li> <li><a href="">Pricing</a></li> <li><a href="">Contact us</a></li> <li><a href="">Register</a></li> </ul> </div> This is the view: def base(request): return render(request, 'base.html', {'active_page':'base'}) def about(request): return render(request, 'about.html', {'active_page':'about'}) And the about html: {% extends 'base.html' %} {% block title %}About{% endblock %} {% block content %} <div class='row'> <div class="col-lg-6"> <h3>Summary</h3> <p> Our organization is related to </p> </div> </div> {% endblock %} The image link is here, only the extendable form appear when i click on about -
Django, custom 404/500 for when i return status_code 404 or 500
I wrote the custom 404/500 pages for my Django applications, and they work ok, except when I explicitly return response with status code 500 or 404 from my views. In the latter case I get whatever content I return in the response. I understand that I can render my 404 and 500 templates in those responses, but is there a way to automatically use those 404/500 pages? To illustrate my question: When i request sth. like "http://my.host/pattern_not_matching_anything", i get my 404.html page -> OK, but: When i request sth. like: "http://my.host/valid_pattern/invalid_parameter", that is, my view gets called, I look for the parameter in the DB and don't find it, and return HttpResponse("not found", status_code=404), I get an html page that only contains "not found".