Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to include an excel spreadsheet during Heroku build
I'm building a Python application using Django, and deploying using Heroku. Because we have a large number of constants (that we occasionally change), we load them from an Excel spreadsheet (or csv file, both would work). When testing code locally, the Excel file is placed in the same folder as the Python code and loads correctly. However, when we deploy the very same project, Heroku does not seem to 'include' the Excel file. Our program crashes whenever we run a Python script that tries to load the Excel spreadsheet. Any idea how to tell Heroku to include the Excel file during deployment, so it runs as it would when testing code? -
Using Select2 autocomplete with Django project does not work while fetching the data
In my project, I have a Search field. I used Select2 autocomplete with it. I needed to fetch the product_list from my Product model. So I created a rest API that returns the product in json formats. Here is my rest API code: serializer.py: class ProductSerializer(serializers.ModelSerializer): class Meta: model = ProductList fields = ('product_id', 'product_name', 'product_image', 'product_available', 'product_description') views.py: class JSONResponse(HttpResponse): def __init__(self, data, **kwargs): content = JSONRenderer().render(data) kwargs['content_type'] = 'application/json' super(JSONResponse, self).__init__(content, **kwargs) def list(request): if request.method == 'GET': products = ProductList.objects.filter(product_name__icontains=request.GET.get('q')) serializer = ProductSerializer(products, many=True) serializer_data = serializer.data customData = {'results': serializer_data} return JSONResponse(customData) Now in my html, in the javascript portion I used this code mentioned in this Select2 doc. The code I used, looks like this: base.html: <script type="text/javascript"> $(document).ready(function() { $('.js-data-example-ajax').select2({ ajax: { url: "/api.alif-marine.com/search/products", dataType: 'json', delay: 250, type: 'GET', data: function (params) { return{ q: params.term, // search term page: params.page }; }, processResults: function (data, params) { params.page = params.page || 1; return { results: data.results, }; }, cache: true }, placeholder: 'Search for a product', escapeMarkup: function (markup) { return markup; }, // let our custom formatter work minimumInputLength: 1, templateResult: formatRepo, templateSelection: formatRepoSelection }); function formatRepo (repo) { if (repo.loading) … -
How do I use allow_tags in django 2.0 admin?
Support for the allow_tags attribute on ModelAdmin methods is removed. -
Celery worker concurrency
I have make as scrapper to scrap around 150 Link Each link has around 5k sub link to get info from them i am using celery to run the scrapper in background and store data on Django ORM , i use beautifulSoap for scrap URL When i running the celery using this command celery worker -A ... --concurrency=50 everything working fine but the workers from 1 to 50 sleep how i can make the celery working till the scrapper finish his task -
Can't load homepage.html in templates folder in Django project
Below is the error message: Template-loader postmortem Django tried loading these templates, in this order: Using engine django: django.template.loaders.filesystem.Loader: /var/www/templates/homepage.html (Source does not exist) django.template.loaders.app_directories.Loader: /usr/local/lib/python3.4/dist-packages/django/contrib/admin/templates/homepage.html (Source does not exist) django.template.loaders.app_directories.Loader: /usr/local/lib/python3.4/dist-packages/django/contrib/auth/templates/homepage.html (Source does not exist) django.template.loaders.app_directories.Loader: /home/site1222/littlethings/templates/homepage.html (Source does not exist) django.template.loaders.app_directories.Loader: /home/site1222/resume/templates/homepage.html (Source does not exist) And here is my project layout, sorry about the image quality: homepage.html is located in site1222/templates/homepage.html. I don't know where went wrong. -
Django queryset count() method raise "TypeError: unorderable types: NoneType() > int()"
My environment is Python3.5, Django1.8.3 and cx_Oracle5.3(They are checked by pip3 freeze). Django query set raises a Type Error exception when count() method is called. When it comes to Python2 + cx_oracle or Python3 + sqlite3 works fine without any exception but Python3 + cx_oracle. Thue, I tried to update cx_Oracle version to 6.1(latest version) because I thought I could be some compatibility problem between cx_Oracle and Python3. However, It generates a different error. I detail with the below code block, please refer it. P.S: I Need to keep Django version to 1.8.3 for compatibility with my Apps. models.py from django.db import models class Device(models.Model): deviceClass = models.CharField(max_length=10) class Meta: db_table = 'TST_G2S_DEVICE' cx_Oracle5.3 $ python3 manage.py shell Python 3.5.2 (default, Nov 23 2017, 16:37:01) Type "copyright", "credits" or "license" for more information. IPython 2.4.1 -- An enhanced Interactive Python. ? -> Introduction and overview of IPython's features. %quickref -> Quick reference. help -> Python's own help system. object? -> Details about 'object', use 'object??' for extra details. In [1]: from polls.models import Device; In [2]: dev = Device.objects.all() In [3]: dev Out[3]: [] In [4]: type(dev) Out[4]: django.db.models.query.QuerySet In [5]: dev.count() --------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-5-72a7bdf9f7f7> … -
Referencing SQL model in mongoengine model field
I'm using mongoengine in my workout calendar Django project to store workouts with varying fields, depending on which lifts a user has done, how many of them, etc. I have defined a Workout object that represents one workout done by one person at a certain date. class Workout(Document): id = IntField(unique=True, null=False) date = DateTimeField() lifts = EmbeddedDocumentListField(LiftSerie) cardio = EmbeddedDocumentListField(CardioSerie) Some of you might notice that there is no field representing the person who did the workout. That is where my question comes in. In my Django project, I have defined a custom User model that I've used instead of the normal django.contrib.auth.models.User object: class User(AbstractUser): REQUIRED_FIELDS = [] USERNAME_FIELD = 'email' email = models.EmailField( unique=True, }, ) This model is a normal Django model, and is represented in an SQL database, SQLite in my case. I would like this model to act as the user field in my Workout mongoengine model. Something like this: class Workout(Document): id = IntField(unique=True, null=False) date = DateTimeField() lifts = EmbeddedDocumentListField(LiftSerie) cardio = EmbeddedDocumentListField(CardioSerie) person = ReferenceField(User) #New row Is this possible to achieve in some way? Or do I need to introduce redundancy to my web app by simply adding an email … -
Django: how to correctly pass an URL in include template tag?
In two different templates, I have two blocks almost identical, only the url is different: template1.html <div class="col-sm-4"> <a href="{% url 'bo:article-list' %}" class="btn btn-block btn-secondary btn-sm" role="button"> <i class="fa fa-chevron-left"></i> Annuler </a> </div> template2.html <div class="col-sm-4"> <a href="{{ article.get_absolute_url }}" class="btn btn-block btn-secondary btn-sm" role="button"> <i class="fa fa-chevron-left"></i> Annuler </a> </div> I'd like to make this dry, creating a template, and making an include then. For example: _cancel.html <div class="col-sm-4"> <a href="{{ cancel_url }}" class="btn btn-block btn-secondary btn-sm" role="button"> <i class="fa fa-chevron-left"></i> Annuler </a> For template2.html, it will work with: {% include 'includes/_cancel.html' with cancel_url=article.get_absolute_url %} But what about template1.html ? This obviously does NOT work : {% include 'includes/_cancel.html' with cancel_url={% url 'bo:article-list' %} I guess there is a trick. Thanks for your help :) -
OneToOneField is nor related
this me again. I have some trouble with my code. I made a form from ModelForm which have a model with 8 attributes, but i want to user fill only one of them,and one from the system. The one that user fill is okay, but the one filled with system is not working. models.py class SeminarProposal(md.Model): # diisi oleh mahasiswa fileProposal = models.FileField() # This is the one is filled with system proposal = models.OneToOneField(Proposal, on_delete=models.CASCADE, related_name="propSid", unique=True, blank=True, null=True) masabimbingan = models.BooleanField(default=True) # disi oleh admin tanggal = models.DateField(default=timezone.now, blank=True,null=True) tempat = models.CharField(max_length=30, blank=True, null=True) # diisi oleh dosen pembimbing dospemsetuju = models.BooleanField(default=False, blank=True) # diisi oleh kaprodi penguji1 = models.ForeignKey(Dosen, on_delete=models.CASCADE, related_name="penguji1", blank=True, null=True) penguji2 = models.ForeignKey(Dosen, on_delete=models.CASCADE, related_name="penguji2", blank=True, null=True) def __str__(self): return "Sidang untuk " + self.proposal.judul view.py def daftarSeminar(request): if request.method == 'POST': form = FormSeminar(request.POST, request.FILES) print(request.user) if form.is_valid(): form.save(commit=False) form.cleaned_data['proposal'] print(request.user) prop = Proposal.objects.get(akun=request.user) form.proposal = prop print(form.proposal) #to confirm that this is not None form.save() return redirect('proposal:bimbingan') else: return render(request, 'sidprop.html' , {'oke': 'oke'}) return redirect('proposal:index') form.py class FormSeminar(forms.ModelForm): class Meta: model = SeminarProposal fields = ['fileProposal','proposal'] Thanks in advance. Terimakasih. -
django_apscheduler remove_all_jobs on django startup
I have used django_apscheduler to schedule jobs. And it's working fine. When I start server new job is added and periodically it's doing what I need to do. However if I exit django and start it again then django will fail with error. apscheduler.jobstores.base.ConflictingIdError: u'Job identifier (myapp_db.jobs.test_job) conflicts with an existing job' Basically old job exists in database and new job can not be created. How can I remove all jobs during django startup. I notice there is remove_all_job() function in apscheduler but I do not know from where to execute it? I'm starting job.py from url.py with import myapp.jobs Thanks. -
invalid view function or pattern name in Django project
I keep getting an error which says "Reverse for favourite not found". It has something to do with either my favourite function in the views.py or presumably the way I have called it in the detail.html file. music/views.py code from django.shortcuts import render, get_object_or_404 from .models import Album, Song # Create your views here. #each URL is connected to a view or an Http Response def index(request): all_albums = Album.objects.all() return render(request,'music/index.html',{'all_albums':all_albums}) def detail(request,album_id): album = get_object_or_404(Album,pk=album_id) return render(request,'music/detail.html', {'album':album}) def favorite(request,album_id): album = get_object_or_404(Album,pk=album_id) try: selected_song=album.song_set.get(pk=request.POST['song']) except(KeyError,Song.DoesNotExist): return render(request,'music/detail/html',{ 'album':album, 'error_message':"You did not select a valid song", }) else: selected_song.is_favorite=True selected_song.save() music/templates/music/detail.html code <img src="{{album.album_logo}}"> <h1>{{album.album_title}}</h1> <h3>{{album.artist}}</h3> {% if error_message %} <p>{{error_message}}</p> {% endif %} <form action="{%url 'music:favorite' album.id %}" method="post"> {%csrf_token%} {%for song in album.song_set.all%} <input type="radio" id="song{{forloop.counter}}" name="song" value="{{song.id}}"> <label for="song{{forloop.counter}}"> {{song.song_title}} {%if song.is_favorite%} <img src="http://www.iconninja.com/files/51/927/609/favourite-favorite-star-bookmark-icon.png"/> {%endif%} </label><br> {%endfor%} <input type="submit" value="Favorite"> </form> Error message: (on page load) The error message seems to suggest that the favourite function is not valid, but I cannot see what I have done wrong. NoReverseMatch at /music/1/ Reverse for 'favorite' not found. 'favorite' is not a valid view function or pattern name. Request Method: GET Request URL: http://127.0.0.1:8000/music/1/ Django Version: 2.0 … -
how to switch to path instead of url in urlpatterns [django]
django noobie. ive been going through tutorials but in urlpatterns they use url instead of path which is now introduced in django 2.0 i want to make /appname/anything-gibberish take the user back to the view im giving in /appname/ urlpatterns = [ path('', views.index, name='index'), path('contact/', views.contact, name='contact'), ] i want 127.0.0.1:8000/contact/asaskhask to go to views.contact is there any way to do this without using url and regular expression? -
How to create a survey with some options in django
I want to create survey. I have below models: class Survey(models.Model): question = models.CharField(max_length=100) description = models.CharField(max_length=500, blank=True, null=True) end_date = models.DateTimeField() class SurveyOptions(models.Model): survey = models.ForeignKey(Survey, related_name='s_id', on_delete=models.CASCADE) text = models.CharField(max_length=50) the survey options might be 2 or 3 or 10 or etc. How can I create that? I don't know how to create a form for it. I googled it, but I didn't find any useful links. I need an example of it. thanks. -
Override setting for unittest in django
django version: 1.11, python version: 3.6.3 When writing unit tests, avoiding interaction with external services (for example the filesystem or network) is considered best practice because you can’t rely on external services’ availability, nor do they present a consistent, predictable state when running your tests. I have a model which uses a custom storage location for image: from django.conf import settings from django.db import models from django.core.files.storage import FileSystemStorage class Example(models.Model): media = models.ImageField( storage=FileSystemStorage(location=settings.PROTECTED_ROOT) ) protected root is defined in settings.py: PROTECTED_ROOT = os.path.join(BASE_DIR, "cdn", "protected") then in the tests.py: import tempfile from example_app.models import Example from django.test import TestCase, override_settings from django.conf import settings temp_directory = tempfile.mkdtemp() @override_settings(PROTECTED_ROOT=temp_directory) class LoginTestCase(TestCase): @classmethod def setUpTestData(cls): cls.example = Example.objects.create( media = 'mock_file_or_image' ) To avoid the file system for as much as possible i would like to use temporary directory, however, files are still added to PROTECTED_ROOT, why? What can i do about it? Or is my thought process completely off and should i go for a different approach altogether? -
Preventing security exceptions in production
I am developing a Django App and I was writing a method in a class model when I realised that there was a possibility in which I would accidentally call the method with a key out of the dictionary that it uses to check the Tier level: def has_tier(self, tier_code="01A"): # it defaults to tier 1 current_tier = self.__verification_tier() # Type: int tiers = {'00X': 0, '01A': 1, '02A': 2, '02B': 3} required = tiers[tier_code] return bool(current_tier >= required) I was going to write a try-except clause since I thought: what if in production the method is accidentally called with a tier level out of the dictionary and it raises a KeyError? But then I also thought: that won't possibly happen since I am the one writing the validations and manually injecting the string into the method, it is not user input that might "mis-processed". Also if I don't catch the exception, I might assure in development stage that the application won't rise any error once all of its functionalities are tested. That way I am able to correct all the errors. I also thought that I could implement a logging module that writes into a file/database all the exceptions … -
Static file in django without Using {% static "abc.jpg" %}
I had static files in django. Project Structure Sample I have project structure like above i want to use js and img from asset folder. How can i do this ? How i can avoid using {% static "abc.jpg" %} ? -
Custom primary key in Django model
Here is my model: class InvitationCode(models.Model): code = models.CharField(max_length=6, primary_key=True) group = models.OneToOneField(Group, on_delete=models.PROTECT) According to doc, primary_key=True implies null=False and unique=True. However this is not what I see: >>> from app.models import InvitationCode >>> c = InvitationCode(group_id=1) >>> c.save() >>> c.pk '' >>> c1 = InvitationCode(group_id=1) >>> c1.save() >>> InvitationCode.objects.all() <QuerySet [<InvitationCode: InvitationCode object ()>]> Why Django allowed me to have primary key as empty string? Why uniqueness constrain didn't work? -
Search with sorting mongodb
My data in mongodb: [{ "name": "Foo", "points": [{ "order": 1, "point_name": "A" }, { "order": 2, "point_name": "B" }, { "order": 3, "point_name": "C" }] }, { "name": "Bar", "points": [{ "order": 1, "point_name": "B" }, { "order": 2, "point_name": "C" }, { "order": 3, "point_name": "A" }] }, { "name": "Fizz", "points": [{ "order": 1, "point_name": "C" }, { "order": 2, "point_name": "B" }, { "order": 3, "point_name": "A" }] } ] I'm doing a search for B -> C the result should be Foo, Bar How the query will look through Django ORM ? Perhaps this can be done easily by rebuilding data or by using hashing functions. Thank you! -
Can django admin.py be replace with a directory?
I know I meant to give what I've tried but I just want to know if the functionality is available first. I'm build a project which is basically only using the django admin functionality (ie I'm not building custom views or if I am I'm building them within the admin functionality). It is making admin.pyrather large and I just wondered if it is possible to do something similar to models and models.py can be replaced by a models directory with init.py defining where the models are found. If the answer is yes, could you point me to some documentation? -
Copy Django App to a New Project but Model Data is Lost
I made a development django project on my pc, and I added a bunch of data for one of the apps "things" by logging in the ADMIN panel. When I copy and paste this app folder into a new project on Ubuntu, add this app in setting, then I find all the data in the model is gone. I used "makemigrations, migrate". Still nothing. What should I do to have those data in this new project? -
Django views.register returning none instead of a HTTPresponse
I'm trying to make a custom user registration form Here is my views.py code from django.shortcuts import render, redirect from django.views.generic import TemplateView from .forms import RegistrationForm # Create your views here. def register(request): if request.POST: form = RegistrationForm(request.POST) if form.is_valid(): form.save() return redirect("profile/") else: form = RegistrationForm() context = {'form': form} return render(request, 'accounts/registration.html', context) Here is my forms.py code from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm class RegistrationForm(UserCreationForm): email = forms.EmailField(required=True) class Meta: model = User fields = [ 'username', 'first_name', 'last_name', 'email', 'password1', 'password2', ] def save(self, commit=True): user = super(RegistrationForm, self).save(commit=False) user.first_name = self.cleaned_data['first_name'] user.last_name = self.cleaned_data['last_name'] user.email = self.cleaned_data['email'] if commit: user.save() return user When I run this code it's working but when I try to register a user it is returning ValueError at /accounts/registration/ The view accounts.views.register didn't return an HttpResponse object. It returned None instead. Here accounts is the name of my Django app -
Django+fastcgi+nginx logging
I was given django project from another developer. It based on windows server(Django+fastcgi+nginx). In settings.py present option DEBUG=True but the anyone of the errorlog-files does not contain debugging information nginx.conf worker_processes auto; error_log C:/PATH_TO_PROJECT/nginx/logs/error.log; error_log C:/PATH_TO_PROJECT/nginx/logs/error.log notice; error_log C:/PATH_TO_PROJECT/nginx/logs/error.log info; error_log C:/PATH_TO_PROJECT/nginx/logs/error.log error; events { worker_connections 1024; } http { include mime.types; default_type application/octet-stream; sendfile on; keepalive_timeout 65; server { listen 8080; server_name localhost; client_max_body_size 32m; error_log C:/PATH_TO_PROJECT/nginx/logs/db-rlocalhost.error_log; error_log C:/PATH_TO_PROJECT/nginx/logs/db-rlocalhost.error_log notice; error_log C:/PATH_TO_PROJECT/nginx/logs/db-rlocalhost.error_log info; error_log C:/PATH_TO_PROJECT/nginx/logs/db-rlocalhost.error_log error; location / { fastcgi_pass 127.0.0.1:8888; fastcgi_pass_header Authorization; fastcgi_hide_header X-Accel-Redirect; fastcgi_hide_header X-Sendfile; fastcgi_pass_header Authorization; fastcgi_intercept_errors off; fastcgi_param CONTENT_LENGTH $content_length; fastcgi_param CONTENT_TYPE $content_type; fastcgi_param PATH_INFO $fastcgi_script_name; fastcgi_param QUERY_STRING $query_string; fastcgi_param REMOTE_ADDR $remote_addr; fastcgi_param REQUEST_METHOD $request_method; fastcgi_param REQUEST_URI $request_uri; fastcgi_param SERVER_NAME $server_name; fastcgi_param SERVER_PORT $server_port; fastcgi_param SERVER_PROTOCOL $server_protocol; } location /media/ { alias H:/AUCTION/; } location /static/ { alias C:/PATH_TO_PROJECT/static/; } location /static_ac_invoice/ { alias C:/PATH_TO_PROJECT/tender/ac_invoice/static/; } error_page 500 502 503 504 /50x.html; location = /50x.html { root html; } } } Running server: c:\PATH_TO_PROJECT\Scripts\python.exe c:\PATH_TO_PROJECT\tender\manage.py runfcgi method=threaded host=127.0.0.1 port=8888 C:\PATH_TO_PROJECT\nginx\nginx.exe How can I get debug info without reconfigure project for running in non fastcgi mode? -
How to make the Django template include work
I have three pages main,one and two. i requirement is when i visit the page main i need to see the page one and two. HTML: main.html {% extends 'base.html' %} {% load staticfiles %} {% load my_tag %} {% block title %} <title>Main TAB</title> {% endblock %} {% block body %} <div> {% include ‘test/one/’ %} </div> <div class="container"> {{name}} </div> <script type="text/javascript" src="{% static "js/testquery.js"%}"> </script> {% endblock %} one.html <div class="container"> {{name}} </div> two.html <div class="container"> {{name}} </div> view.py def main_page(request): try: main_data = {'name':"main"} return render(request, 'task/main.html', {'name': main_data}) except Exception as e: raise def one_page(request): try: main_data = "one" return render(request, 'task/one.html', {'name': main_data}) except Exception as e: raise def two_page(request): try: main_data = "Two" return render(request, 'task/two.html', {'name': main_data}) except Exception as e: raise url.py urlpatterns = [ url(r'^$', taskpage,name="task_master"), path('Task/<int:taskid>', show_task,name='show_task'), path('Task/<int:taskid>/update', updatetaskpage,name='updatetask_page'), path('Test/Main/', main_page,name='main'), path('Test/one/', one_page,name='one'), path('Test/two/', two_page,name='two'), ] I am getting the following error : TemplateSyntaxError at /taskmaster/Test/Main/ Could not parse the remainder: '‘test/one.html’' from '‘test/one.html’' Request Method: GET Request URL: http://localhost:8000/taskmaster/Test/Main/ Django Version: 2.0 Exception Type: TemplateSyntaxError Exception Value: Could not parse the remainder: '‘test/one.html’' from '‘test/one.html’' Exception Location: C:\Program Files (x86)\Python36-32\lib\site-packages\django\template\base.py in init, line 668 Python Executable: C:\Program Files … -
rpc api using django
I am trying to build an RPC API for machine learning. Is there any way to build RPC API using Django framework. Earlier I have made a restful API using Django rest framework. please suggest me if there is any other way to build the RPC API. -
error deploying django 2.0 to heroku
I have created my first Django 2.0 project and trying to deploy it into Heroku. I have have setup all and all push and pull goes well. But when I access my application endpoint with https://jotitdown.herokuapp.com It is not loading and heroku logs gives this error 2017-12-23T07:04:45.333450+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=jotitdown.herokuapp.com request_id=cd2a9bb6-fae8-4317-af39-b271c1d74af5 fwd="45.115.107.34" dyno= connect= service= status=503 bytes= protocol=https I have set this in settings.py, here ` DEBUG = True ALLOWED_HOSTS = ['*', 'jotitdown.herokuapp.com', '*.herokuapp.com'] and Profile web: gunicorn notepad.wsgi --log-file -