Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Creating a RESTful API for a desktop application
I've got an open source desktop application (with a Python programming interface.) I'd like to run it on a cloud VM and create a web API, REST or GraphQL, to allow programmatic access. Preferably, would build something with Django, right? I have not been able to find any good tutorials on doing something like this, and am not sure where to start. CouchDB seem -
How to override bootstrap cdn in Django?
I'm new to Django, and even more so to CSS. In the base.html of my site I included a bootstrap cdn as follows: <meta charset="UTF-8"> <link rel="shortcut icon" href="{% static 'favicon.ico' %}"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script> <link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"> However, I want to make some modifictions to the css and I cannot because the cdn is an external file. It wouldn't work when I simply copy the content to a local css file because of proocol issues. According to this previous thread I've tried to add another line so it would override the cdn, as follows: <link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"> <link rel="stylesheet" type="text/css" href="{{ STATIC_URL }}/bootstrap/css/style.css"> but it doesn't work. I tried also to write this line in a local html file (i.e. not in base.html) but no success. My questions are: How do I override the cdn file? That is, also where is it best to place the other css file (I have static directories both in project and app levels for some reason), and if it matters how it is named? What makes a simple and safe test to see if it worked? Most of all, I'm looking for a … -
Django TemplateDoesNotExist error
After i uploaded my django project from my local machine to a remote server this error appears TemplateDoesNotExist at / registration/login.html Request Method: GET Request URL: http://ip:8000/ Django Version: 1.8.6 Exception Type: TemplateDoesNotExist Exception Value: registration/login.html Exception Location: /home/market/local/lib/python2.7/site-packages/django/template/loader.py in get_template, line 46 Python Executable: /home/market/bin/python Python Version: 2.7.12 Python Path: ['/home/market/src', '/home/market/lib/python2.7', '/home/market/lib/python2.7/plat-x86_64-linux-gnu', '/home/market/lib/python2.7/lib-tk', '/home/market/lib/python2.7/lib-old', '/home/market/lib/python2.7/lib-dynload', '/usr/lib/python2.7', '/usr/lib/python2.7/plat-x86_64-linux-gnu', '/usr/lib/python2.7/lib-tk', '/home/market/local/lib/python2.7/site-packages', '/home/market/lib/python2.7/site-packages'] Server time: Sun, 2 Jul 2017 08:35:49 +0000 and this error appears in django server console (1_8.W001) The standalone TEMPLATE_* settings were deprecated in Django 1.8 and the TEMPLATES dictionary takes precedence. You must put the values of the following settings into your default TEMPLATES dict: TEMPLATE_DEBUG. -
How to read a django html template
Is there a way to read a django html template within a project like how BeautifulSoup reads a website. (with functionality like finding and getting data) obj = open("path to template", 'r') read_obj = obj.read() obj.close() -
Django: Cannot access _meta of model class in same model file
I have Plant model and a method get_plant_measurement_field_details returning Plant fields starting with 'measurement' so that i can use its name and verbose name for creating another model named PlantModelMeasurementRange class Plant(models.Model): measurement_outlet_length = models.FloatField( verbose_name=_('Outlet length in cm'), blank=True, null=True ) measurement_outlet_width = models.FloatField( verbose_name=_('Outlet width in cm'), blank=True, null=True ) def get_plant_measurement_field_details(): fields = Plant._meta.get_fields() measurement_field_details = [] for field in fields: if field.name.startswith('measurement'): measurement_field_details.append( { 'name': field.name, 'verbose_name': field.verbose_name } ) return measurement_field_details class PlantModelMeasurementRange(models.Model): model = models.OneToOneField(PlantModel, on_delete=models.CASCADE, related_name='range') for field in get_plant_measurement_field_details()[0]: models.FloatField( verbose_name='Maximum Value of %s' % field.get('verbose_name').lower() ).contribute_to_class( PlantModelMeasurementRange, '%s_max' % field.get('name').lower() ) But on runserver it thorows following exception: django.core.exceptions.AppRegistryNotReady: Models aren't loaded yet. Is there any better way to solve this problem. Thanks -
django on Google Cloud
Hi I am using Django in the google cloud using bitnami django/debian image. I am not able to observe any changes if I make changes to my django files like in view etc. Even if I have the server turned off I am seeing some page on the actual cloud server ! Please see that the server is stopped CONTROL-C but still I am seeing a page on the server. Server running fine at: http://104.155.166.2/ -
Django app uses only default database to retrieve data. How to set the retrieve function to mysql databse
There are two database for my Django project. I had created function to enter data to the database (mysql), but the data used to always save in the default database. I have solved the problem now using .save(using='db2'). The current problem is that I have used instance to get the id of the user and when I want to see the user detail using the function below, the user id of the default database conflicts with the user id of the mysql database so the default databases detail is shown. How can I use only db2 like the one I used for saving data. The function for showing the userdetail is shown below. DATABASES = { 'default':{ 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3')}, 'db2': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'subscribers', 'USER': 'root', 'PASSWORD': '######', 'HOST': 'localhost', 'PORT': '3306', }} The function I created in my Django app that show the detail of user whenever requested. @login_required def userDetail(request, id=None): instance = get_object_or_404(Subscribers, id=id) context = { "Name": instance.name, "instance": instance, } return render(request, 'userDetail.html', context) -
Setting pycharm run django unittest
I can not run Django Python pytest under PyCharm After I got the answer from the above URL. I am now trying to fully utilize my IDE functions as much as I can. Here is another project in my company that using Django UnitTest. This is the command line I used. $ python manage.py test --settings=eneos.config.settings.local Actually --settings=eneos.config.settings.local is not required, because I put that config in the wsgi.py already. But explicit is better than implicit when I ask the question. Unfortunately. It is not simple like pytest. I must miss some points in here. First several lines in the window. /Users/el/.pyenv/versions/eneos-pos-web/bin/python "/Users/el/Library/Application Support/JetBrains/Toolbox/apps/PyCharm-P/ch-0/171.4694.38/PyCharm.app/Contents/helpers/pycharm/_jb_unittest_runner.py" --path . Testing started at 2:17 PM ... Launching unittests with arguments python -m unittest discover -s . -t /Users/el/Code/eneos-pos-web in /Users/el/Code/eneos-pos-web Error Traceback (most recent call last): -
How to use outer loopcounter to access an array in the inner loop
In the code below the inner forloop is not working <tbody> {% for rec in medrec %} <tr> <td>{{ forloop.counter }}</td> <td>{{ rec.date }}</td> <td>{{ rec.disease }}</td> <td>{{ rec.treatment }}</td> <td> {% for n in medicine.forloop.parentforloop.counter0 %} {{ n.medicine }} {% endfor %} </td> </tr> {% endfor %} </tbody> The code above generates a table. Each rec has a array of medicines. Like for the rec.forloop.counter where forloop.counter == 1 there will objects in the medicine array index [0]. How do i print it? def profile(request,rid): patient = Patient.objects.get(pk=rid) medic = MedicalRec.objects.filter(patient=patient) i=0 a=[] for n in medic: a.append(medicine.objects.filter(Rec= n)) print(a) if patient: return render(request,'patient.html',{ 'medrec' : medic, 'pat' : patient, 'medicine' : a }) else: return 'patient not found' -
Is there a way to get html tag attributes within a django view
So basically i'm trying to get a img tag src inside a django view. Template <form method="POST" action=""> {% csrf_token %} {{ form }} <img src="https://img.jpg"></img> <input type="submit"></input> </form> View if form.is_valid(): instance = form.save(commit=False) image_src = request.POST.get({The img src}) instance.image_url = image_src instance.save() return redirect() so the end result would be to get "https://img.jpg" in the view -
I can not run Django Python pytest under PyCharm
$ pytest portal/ =============================================== test session starts =============================================== platform darwin -- Python 3.6.0, pytest-3.0.6, py-1.4.32, pluggy-0.4.0 Django settings: config.settings.local (from ini file) rootdir: /Users/el/Code/siam-sbrand/portal, inifile: pytest.ini plugins: django-3.1.2 collected 87 items portal/apps/commons/tests.py ...... portal/apps/price_list_excel_files/tests.py ssssssssssss portal/apps/price_lists/tests.py s.... portal/apps/reports/tests.py .........................ssss.................. portal/apps/sbrand_jobs/tests.py ................ portal/apps/service_items/tests.py s ===================================== 69 passed, 18 skipped in 32.08 seconds ====================================== pytest.ini: [pytest] DJANGO_SETTINGS_MODULE=config.settings.local norecursedirs = node_modules venv *.txt python_files = tests.py Test*.py test_*.py I have install pytest-django under pyenv already. Then I want to study key feature in PyCharm, but unfortunately when I try reaching the JetBrain forum. It is limited to the company owner only. I can not post my question because I just an employee. And this is when I click play pytest button /Users/el/.pyenv/versions/siam-sbrand/bin/python pytest portal /Users/el/.pyenv/versions/siam-sbrand/bin/python: can't open file 'pytest': [Errno 2] No such file or directory Process finished with exit code 2 -
Como implementar uma fila prioritária em Python
preciso implementar uma fila prioritária, essa fila além da prioridade, precisa levar em consideração alguns outros requisitos, como por exemplo, alternar entre serviços e profissionais, além claro de respeitar a ordem de chegada do cliente para aquele serviço e/ou profissional. Já andei pesquisando sobre alguma lib ou algum algorítimo e o mais próximo que encontrei foi o heapq do Python mas não consegui adaptar e montar minha solução. Estou precisando muito de um help, aceito sugestões de implementações, indicações de libs que resolvam este problema enfim. Já tentei várias soluções e nenhuma mostrou o resultado desejado. Fico no aguardo. PS: Fiz várias pesquisas aqui no SO e não encontrei nenhuma pergunta igual, caso seja repetida favor indicar link da questão. -
Django Rest Framework AttributeError: 'Response' object has no attribute 'encoding'
I am trying to do simple tests on my newly created viewsets, by using the APIClient class instead of APIRequestFactory, however, the view fails with the following error: AttributeError: 'Response' object has no attribute 'encoding' It works fine if I use APIRequestFactory though, but I need APIClient since I am using TokenAuthentication. This is the context in which I am using the client: api_client = APIClient() reversed_url = reverse('showcase:ajax:publisher-dashboard', kwargs={'pk': 1}) client_token = cm.Client.objects.get(first_name='Cliente 1', last_name='Prueba Showcase').user.auth_token.key api_client.credentials(HTTP_AUTHORIZATION='Token ' + client_token) request = api_client.get(reversed_url, format='json') response = views.PubViewSet.as_view({'get': 'dashboard'})(request, pk=1) The results are the same without providing credentials and disabling TokenAuth in settings.py. These are the contents of the Response object when using APIRequestFactory: <Response status_code=200, "text/html; charset=utf-8"> _charset = {NoneType} None _closable_objects = {list} <class 'list'>: [] _container = {list} <class 'list'>: [b''] _content_type_for_repr = {str} ', "text/html; charset=utf-8"' _handler_class = {NoneType} None _headers = {dict} {'content-type': ('Content-Type', 'text/html; charset=utf-8')} _is_rendered = {bool} False _post_render_callbacks = {list} <class 'list'>: [] _reason_phrase = {NoneType} None _request = {NoneType} None charset = {str} 'utf-8' closed = {bool} False content = {str} 'Traceback (most recent call last):\n File "/home/ariel/.local/pycharm-2017.1.1/helpers/pydev/_pydevd_bundle/pydevd_resolver.py", line 197, in _getPyDictionary\n attr = getattr(var, n)\n File "/home/ariel/.virtualenvs/recrow-app/lib/python3.6/site-packag content_type = {NoneType} … -
Form Processing: using cleaned_data
I am trying to make a BMI calculator for my program using Django Web Frameworks: This my views.py def bmi(h,w): return(w*10000.00/(h*h) def bmi_view(request): form=Bmi_forms() if request.method=='POST': form=Bmi_forms(request.POST) if form.is_valid: weight=form.cleaned_data['weight'] height=form.cleaned_data['height'] Bmi_value =bmi(height,weight) form.save() context={'form':form,'Bmi_value': Bmi_value} return render(request,'Bmidisplay.html',context) This gives a invalid Syntax Error ,I don't know what to do Some of my doubts are: 1. How can I modify my views to calculate BMI( I feel there is conflict in saving the forms data and calculation) 2. How to display the calculated Displayed Bmi value in a Template ie HTML file and give conditions like a)If BMI <18.5 ==Overweight b)If BMI between 18.5 and 25 =Normal Weight c)If BMI above 25 =Overweight Thats all,I am quite new to Python Django please Help me as I am quite new to this Language.It would be highly appreciate if you write the suitable code here -
why is my django render function not returning correct output
I have a render function which has the below arguments. This gives me the correct output on the directed page. return render(request, 'about_experiment.html', {'researcher': researcher}) But when i include another argument, it does not do the work for it as the study output is not coming return render(request, 'about_experiment.html', {'researcher': researcher}, {'study': study}) where am i going wrong -
Django - ckeditor wordcount plugin issue
I installed ckeditor and wordcount plugin in my django-app. This is a part of ma settings.py: CKEDITOR_CONFIGS = { 'default': { 'toolbar': 'Custom', 'width': '100%', 'extraPlugins': 'wordcount,notification', 'toolbar_Custom': [ ['Bold', 'Italic', 'Underline'], ['NumberedList', 'BulletedList', '-', 'Outdent', 'Indent', '-', 'JustifyLeft', 'JustifyCenter', 'JustifyRight', 'JustifyBlock'], ['Link', 'Unlink'], ['RemoveFormat', 'Source'], ] } } My plugin is in root/static/ckeditot/ckeditor/plugins directory. I see Paragraphs, Words labels in my text area but I edited my config.js to: showParagraphs: false, It looks like config.js is not valid. All my modifications in this file doesn't work. I tried to delete this file, modify another files in my wordcount directory but there is no effect... I search my venv and found ckeditor config.js. I modified it but no effect appeared. Any idea what should I do? -
django autocomple light, linked data with choices
I am using django autocompletelight. I know how to use linked data. But in documentaton, it only refers to modelselect, what about if we have static choices and we want to filter those choices depending on another? django-autocomplete-light -
Django: 'ForwardManyToOneDescriptor' object has no attribute
I have a simple view containing a queryset to filter out different users, and a 'member' variable to be used in the queryset. member = UserProfileModel.parent.random_attribute team = UserModel.objects.filter(member=another_random_attribute) However, upon refreshing the view, I receive the error: 'ForwardManyToOneDescriptor' object has no attribute 'random_attribute' Even though random_attribute is an attribute of the model 'parent' - Any ideas where this is going wrong? -
DJANGO - Redirect to different page with form data
Hi i want to redirect to a destination page with the from data. For example when user fills a form the data inputted in the form, i want that to be outputted on the destination page my codes are as follows:- source page(experiment.html), I am unsure what the action should be for the form so please help me with it <form action="{% url 'lazer.views.about_experiment' exp.link_name %}" method="POST"> {% csrf_token %} <label>Researcher Name(s):<input type="text" name="researcher"> <lable>Study Summary<textarea rows="10" cols="50" placeholder="here you go" maxlength="500" class="form-control" name="study"></textarea> <br> <input type = "submit" value="Submit" class="btn btn-primary" /> </form> destination page (about_experiment.html) <h3>Holding page for {{ exp.name }}.</h3> <h2> {{ form }} </h2> views.py from .forms import AboutHelp from django.shortcuts import render from django.http import HttpResponseRedirect def get_name(request): if request.method == 'POST': form = AboutHelp(request.POST) if form.is_valid(): researcher = form.cleaned_data['researcher'] study = form.cleaned_data['study'] else: form = AboutHelp() return render(request, 'about_experiment.html', {'form': form})` forms.py from django import forms class AboutHelp(forms.Form): researcher = forms.CharField(max_length=100) study = forms.CharField(max_length=500) urls.py url(r'^about/(?P<ex_link_name>\w+)', lazer.views.about_experiment, name='lazer.views.about_experiment'), -
Updating DataTable with Django model objects
I'm trying to update a dataTables data table in Django with an Ajax request to the Django database. The code I have to update the table in the HTML template is: $(document).ready(function(){ var table = $('#example').DataTable({ "ajax": '/main/newrequests/' }); setInterval(function(){ table.ajax.reload(); }, 20000) }); And the view for newrequests is: def newrequests(request): requests = Request.objects.all() data = serializers.serialize('json', requests) return HttpResponse(data, content_type='application/json') When the table tries to update, there is an HTML 500 error and a DataTabels Ajax error. I think the issue is that the Ajax query isn't returning the right type of data - this is what the output looks like: [{"model": "main.request", "pk": 1, "fields": {"room": "225", "request": "Where is the pool?", "done": false, "cannot": false, "time": 0, "loaded": false}}, {"model": "main.request", "pk": 2, "fields": {"room": "325", "request": "I'd like a pizza", "done": false, "cannot": false, "time": 0, "loaded": false}}], etc I need to be loading the data from "fields" into the data table, which has corresponding headers of "Room", "Request", etc. How should I try to pass the data differently through Ajax in the newrequests view, or is there a way I can use mData from dataTables to access those values? Thank you! -
Import Excel to Django Model - Django-Excel says "done" but no data added?
I've tried every existing tool I can find, openpyxl, pyexcel, django-excel, etc. I need to enable users to upload an excel file, and have those sheets translate to new records in a database. I've followed the documentation and downloaded the example files from django-excel doc, and it appears to work when I runserver locally. The upload completes and says "done", but when I look at the table it's supposed to upload to, there are zero records. I was able to get openpyxl to import a sheet into memory stored as a dict, but I confess I don't understand how to get that dict into the model class either. Here's what I'm working with: models.py: from django.db import models from django.utils import timezone from django.conf import settings class RawTransactions(models.Model): full_name = models.CharField(max_length=40) client_name = models.CharField(max_length=40) raw_type = models.CharField(max_length=40) app_type = models.CharField(max_length=40) week = models.DateField(null=True) views.py from django.shortcuts import render from django.http import HttpResponseBadRequest, HttpResponse from _compact import JsonResponse from django import forms import django_excel as excel from upexcel.models import RawTransactions class UploadFileForm(forms.Form): file = forms.FileField() def import_data(request): if request.method == "POST": form = UploadFileForm(request.POST, request.FILES) if form.is_valid(): request.FILES['file'].save_book_to_database( models=['RawTransactions'], mapdicts=[ ['full_name', 'client_name', 'raw_type', 'app_type']] ) return HttpResponse("OK", status=200) else: return HttpResponseBadRequest() … -
Setting up Nginx as a reverse proxy for Apache vs just Apache Event MPM
In the Django docs for setting up mod_wsgi, the tutorial notes: Django doesn’t serve files itself; it leaves that job to whichever Web server you choose. We recommend using a separate Web server – i.e., one that’s not also running Django – for serving media. Here are some good choices: Nginx A stripped-down version of Apache I understand this might be due to wasted resources when Apache spawns new processes to serve each static file, which Nginx avoids. However, Apache's (newish?) Event MPM seems to act similar to an Nginx instance handing off requests to an Apache worker mpm. Therefore I'd like to ask: instead of setting up Nginx to be a reverse proxy for Apache, would using an Apache Event MPM be sufficient for serving static files in Apache? -
Django model with XMLField
I'm new to python/django I'm using django 1.11, python 3.5.2 and Oracle 11g r2 I want to create a django model for the TABLE1 in oracle database my TABLE1 has 4 fields: ID (TYPE: NUMBER) NAME (TYPE: VARCHAR2) LASTNAME (TYPE: VARCHAR2) INFO (TYPE: XMLTYPE) This is the format of the xml field: <?xml version = '1.0' encoding = 'UTF-8'?><extrainfo> <info> <movie>Titanic</movie> <sport>Tennis</sport> </info> <info> <movie>Troy</movie> <sport>Soccer</sport> </info> </extrainfo> I'm creating a django model for table1, but I don't know how to read the xml field in db using django. This is my model class Table1(models.Model): id = models.IntegerField(primary_key=True) name = models.TextField(blank=True) lastname = models.TextField(blank=True) info = (I dont know what to write here to read the xmltype in db) class Meta: managed = False db_table = 'TABLE1' What Should I do? What is the best way to do it? I need to get the xmltype information. Please help me, I'm stuck. Thanks. -
How to add truncatechars filter in Django form&
I need to add truncatechars filter to Django template (in ul), but ul rendering in form. Here is my form: class TranslatorForm(forms.ModelForm): first_name = forms.CharField( required=True, ) last_name = forms.CharField( required=True, ) specializations = forms.MultipleChoiceField( required=True, choices=Specialisation.objects.all().values_list("id", "title"), widget=forms.CheckboxSelectMultiple(), label=_("specializations"), ) Template: <div class="line _dj_multicheckbox"> <label for="pe_{{ form.specializations.name }}">{{ form.specializations.label }}</label> {{ form.specializations }} {% include 'profiles/snippets/errors_snipet.html' with field=form.specializations %} <div class="clear"></div> </div> Some specializations have too much symbols, so I need truncatechars here. Is there a way to do this in from? Like Widget or something? -
How to acess a global variable and change its value from another module
I have a global variable that is Increasing, and I wanna reset the counter from another module. Whenever post_save signal runs, Counter variable increases and I see the number in the terminal. But I will call a code from another module and I want to set counter to 0, So when I call post_save signal again it starts from 0. As I did it seems there are 2 variables. counter = 0 @receiver(post_save, sender=Numbers) def num_post(sender, **kwargs): global counter counter += 1 print(counter) dict = {} for object in Numbers.objects.all(): dict[object.pk] = object.number print(dict) Group('group1').send({ 'text': json.dumps(dict) }) from .models import counter def ws_disconnect(message): global counter counter = 0 print(counter) Group('eae').discard(message.reply_channel) Group('opa').discard(message.reply_channel)