Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How do I load image from Django uploaded image binary file and use face_recognition(dlib)
This is the same question I posted here: https://github.com/ageitgey/face_recognition/issues/324 I am using face_recognition dlib module. I have a Django app that I want the user to upload the face image or pass it through web rest based API. The problem is how do I load this image ? In the current example is load_image_file("my_picture.jpg") but i believe this will take it from the file system. How do I load an image that is uploaded binary (without saving it to the filesystem) ? What I Did I have uploaded an image (jpg/png) through a browse button from Django web app just like this https://imgur.com/a/fVKuF From the code I will obtain the face_image_obj object and then try to pass it the face_locations function. However the face_image_obj is not compatible. In the example, I believe load_image_file is from the file system, but with web based api, we are to get it from an uploaded source. face_image_obj = employeefaceimageupload_form.cleaned_data["face_image"] logging.debug("face_image_obj type: %s" % type(face_image_obj)) face_location_unknown = face_recognition.face_locations(face_image_obj) face_recognition.face_locations will cause this exception: Exception Value: | Unsupported image type, must be 8bit gray or RGB image. i check the image type using this type(face_image_obj is <class 'django.core.files.uploadedfile.InMemoryUploadedFile'> My environment: face_recognition version: face-recognition==1.0.0 face-recognition-models==0.3.0 Python version: … -
using Geodjango with oracle database
when working with GeoDjango i have a problem: when i make migrations then migrate new models the log said "no migrations to apply" and the oracle database still have no new table . my settings.py is DATABASES = { "default": { "ENGINE": "django.contrib.gis.db.backends.oracle", "NAME":, "USER":, "PASSWORD":, } } I need some help -
Django Appurl and Root url
I am not able to understand the difference between the Root URL and the App url and how to construct those. Its confusing when I need to use the Root url and App url. Example: When I need the extension of the website like www.test.com/users then I need to go for the app url? But what confusing is these extensions I can create in the Root url also. Please clarify. -
Django and ManyToMany fields
I have a database in mysql and I am setting up a django project. I have some entities with many-to-many relations, which are handled through association tables. With django, I have understood that I can use ManyToMany entity to achieve many-to-many relations BUT how do I do when the association table holds more information besides just the many-to-many relation? See the example below. CREATE TABLE `products` ( `id` int(11) unsigned NOT NULL AUTO_INCREMENT, `name` char(150) DEFAULT NULL ...) CREATE TABLE `pictures` ( `id` int(11) unsigned NOT NULL AUTO_INCREMENT, `filename` char(100) NOT NULL ... ) CREATE TABLE `products_pictures` ( `id` int(11) unsigned NOT NULL AUTO_INCREMENT, `fk_products_id` int(11) unsigned NOT NULL, `fk_pictures_id` int(11) unsigned NOT NULL, `priority` tinyint(4) unsigned DEFAULT NULL, `relation` varchar(25) DEFAULT 'same product family' ... ) -
Need a minimal Django file download example
I'm facing difficulty to download (the already uploaded) files as I am a newbie in django. Also I could not find a way to do that (the uploaded files are of different formats). May someone post a minimal but complete (Model, View, Template) example code to do so? -
Django with multiple Apps and reusing the same database tables
I am quite new to Django. Right now I am working on a prototype with ~30 database tables. I have understood that with Django you preferably want to have quite small Apps, with limited number of Models. I want to use the same Models (i.e. database tables) in several different Apps. What is the best practice to achieve this? I am using mysql. -
How to load block by ajax in backgroud?
:) I have tree structure in my template which created by Nestable2 plugin. I render tree structure with next html which you can see below. It works but render some heavy pages with a lot of data too slow. By default when user open the page tree is collapse. I show top level nodes first and then check if they have descendants. You can see it in html. The main load to database happens when I check all descendants of the node in this line: node.get_children. Question: Is it possible to load this part {% if node.get_children %} *** {% endif %} by ajax in backgroud when page is opened? I want to know your ideas, I would be grateful for examples. My aim is to speed up page loading. main.html: <ol class="dd-list"> {% for node in nodes %} {% include "tree_template.html" %} {% endfor %} </ol> tree_template.html: <li class="dd-item dd3-item" data-id="{{node.id}}"> <div class="dd-handle dd3-handle"></div> <div class="dd-content dd3-content">***</div> {% if node.get_children %} <ol class="dd-list"> {% for child in node.get_children %} {% with node=child template_name="tree_template.html" %} {% include template_name %} {% endwith %} {% endfor %} </ol> {% endif %} </li> -
How to replace data value(js) with a datatable value?
Python 3.6.3 django==1.11.3 bootstrap4 I am trying to create a bar chart with data retrieved from a datatable. how to map data(lables, data) values to datatable in a chart js file. Assuming that hard-coded data exists as a datatable, how do you write a js file? Please tell me how. html <div class="col-lg-6"> <div class="card bar-chart-example"> <div class="card-header d-flex align-items-center"> <h4>Bar Chart Example</h4> </div> <div class="card-body"> <canvas id="barChartExample"></canvas> </div> </div> </div> chart js var barChartExample = new Chart(BARCHARTEXMPLE, { type: 'bar', data: { labels: ["January", "February", "March", "April", "May", "June", "July"], datasets: [ { label: "Data Set 1", backgroundColor: [ 'rgba(51, 179, 90, 0.6)', 'rgba(51, 179, 90, 0.6)', 'rgba(51, 179, 90, 0.6)', 'rgba(51, 179, 90, 0.6)', 'rgba(51, 179, 90, 0.6)', 'rgba(51, 179, 90, 0.6)', 'rgba(51, 179, 90, 0.6)' ], borderColor: [ 'rgba(51, 179, 90, 1)', 'rgba(51, 179, 90, 1)', 'rgba(51, 179, 90, 1)', 'rgba(51, 179, 90, 1)', 'rgba(51, 179, 90, 1)', 'rgba(51, 179, 90, 1)', 'rgba(51, 179, 90, 1)' ], borderWidth: 1, data: [65, 59, 80, 81, 56, 55, 40], } ] } }); -
How to install django in windows 10
I'm using anaconda interpreter, can you please tell me how to install django by creating conda environment in different drive (other than C drive). Thank you -
Reverse for Model with Slug in URL not working
I have a parts.html page that references the model Part, the page I am having issue with is the Part List view Generic Model view. The purpose of it is to lists all of the parts on a page and show the category next to it. Each part has a foreignkey "category". I am trying to create a Slug URL from the Part list view to the Category detail page, but I receive this error when I go to the partlistview page. I can access the Category page with portal/category/category where the second category at the end is a category in the database. django.urls.exceptions.NoReverseMatch: Reverse for 'category-detail' with arguments '('',)' and keyword arguments '{}' not found. 1 pattern(s) tried: ['portal/category/(?P<slug>[-\\w]+)/$'] Views.py class PartDetailView(LoginRequiredMixin, generic.DetailView): model = Part template_name = 'portal/part.html' # Option - Specify your own template name/location class PartListView(LoginRequiredMixin, generic.ListView): model = Part #queryset = Part.objects.filter(is_active=True) #.prefetch_related('user') #hos paginate_by = 100 https://simpleisbetterthancomplex.com/tutorial/2017/03/13/how-to-create-infinite-scroll-with-django.html template_name = 'portal/parts.html' # Option - Specify your own template name/location context_object_name = 'part_list' #def get_queryset(self): #return Category.objects.all() def get_context_data(self, **kwargs): context = super(PartListView, self).get_context_data(**kwargs) context['category'] = Category.objects.all() return context class CategoryDetailView(LoginRequiredMixin, generic.DetailView): model = Category template_name = 'portal/category.html' # Option - Specify your own template name/location … -
You're using the staticfiles app without having set the STATIC_ROOT setting to a filesystem path
I have gone through every other answer and cannot seem to get anything to work for me. I am following a tutorial and trying to push my master branch to heroku and get the error You're using the staticfiles app without having set the STATIC_ROOT setting to a filesystem path. I am using Django 2.0 and python 3.6.3. The full traceback: remote: -----> $ python manage.py collectstatic --noinput remote: Traceback (most recent call last): remote: File "manage.py", line 15, in <module> remote: execute_from_command_line(sys.argv) remote: File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 371, in execute_from_command_line remote: utility.execute() remote: File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 365, in execute remote: self.fetch_command(subcommand).run_from_argv(self.argv) remote: File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/base.py", line 288, in run_from_argv remote: self.execute(*args, **cmd_options) remote: File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/base.py", line 335, in execute remote: output = self.handle(*args, **options) remote: File "/app/.heroku/python/lib/python3.6/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 189, in handle remote: collected = self.collect() remote: File "/app/.heroku/python/lib/python3.6/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 114, in collect remote: handler(path, prefixed_path, storage) remote: File "/app/.heroku/python/lib/python3.6/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 344, in copy_file remote: if not self.delete_file(path, prefixed_path, source_storage): remote: File "/app/.heroku/python/lib/python3.6/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 250, in delete_file remote: if self.storage.exists(prefixed_path): remote: File "/app/.heroku/python/lib/python3.6/site-packages/django/core/files/storage.py", line 308, in exists remote: return os.path.exists(self.path(name)) remote: File "/app/.heroku/python/lib/python3.6/site-packages/django/contrib/staticfiles/storage.py", line 43, in path remote: raise ImproperlyConfigured("You're using the staticfiles app " remote: django.core.exceptions.ImproperlyConfigured: You're using the staticfiles app … -
Append query string if user logged in
Is there a way to add a query string such as ?preview to all URLs for a particular view in Django only if a user is logged in? The purpose of this is to bypass caching on cloudflare. -
django 2.0 - including urls file from an app to the root urls file
I'm interested in have for each app their own urls.py file and then, include them in the root urls.py file using the include django function like this include('myapp.urls'). So, in root urls.py it is like this: from django.url import include, path urlpatterns = [ path('folio/', include('folio.urls')) ] and now in the folio urls.py it is like the following which didn't find solution in the django url documentation: from django.urls import path from . import views urlpatterns = [ path('', views.home, name='home') ] After some tryings all I get is page not found. What am I missing? -
How to handle an extremely big table in a search?
I'm looking for suggestions on how to go about handling the following use case scenario with python django framework, i'm also open to using javascript libraries/ajax. I'm working with pre-existing table/model called revenue_code with over 600 million rows of data. The user will need to search three fields within one search (code, description, room) and be able to select multiple search results similar to kendo controls multi select. I first started off by combining the codes in django-filters as shown below, but my application became unresponsive, after waiting 10-15 minutes i was able to view the search results but couldn't select anything. https://simpleisbetterthancomplex.com/tutorial/2016/11/28/how-to-filter-querysets-dynamically.html I've also tried to use kendo controls, select2, and chosen because i need the user to be able to select as many rev codes as they need upward to 10-20, but all gave the same unresponsive page when it attempted to load the data into the control/multi-select. Essentially what I'm looking for is something like this below, which allows the user to select multiple selections and will handle a massive amount of data without becoming unresponsive? Ideally i'd like to be able to query my search without displaying all the data. https://petercuret.com/add-ajax-to-django-without-writing-javascript/ Is Django framework meant to … -
Django: Reusable App Code
Can anyone share the reusable app one is supposed to get after completing the official Django tutorial? 2.0 would be ideal! I tried searching on Github but wasn't able to find working projects. Alternatively, can you perhaps recommend some other starter project templates written in Django? Thank you! -
Django - Create a User instance from another model that uses User as a OneToOne
I think an example will explain it better. Lets say I am making an application for various Libraries to show what books they have available. The site will have Users that are registered through the built-in user registration system and User model. These Users (think of it like library members) can visit the Libraries and browse and checkout the available books. The site will also allow Libraries to register themselves, and part of that registration is declaring a "Librarian," a person who controls what books are available in their particular Library. I want to create a Library Registration Form that takes the information of this Library and its Librarian and not only creates an instance of the Library model, but also an instance of the User model. The Librarian automatically becomes a User. This is my current models.py: class Library(models.Model): name = models.CharField(max_length=200) website = models.URLField() street = models.CharField(max_length=200) city = models.CharField(max_length=200) state_or_province = models.CharField(max_length=200) postal_code = models.CharField(max_length=200) date_registered = models.DateField(auto_now_add=True) librarian = models.OneToOneField(User, on_delete=models.CASCADE) @receiver(post_save, sender=Library) def create_user(sender, instance, created, **kwargs): if created: User.objects.create(user=instance) instance.user.save() I am currently lost as to how to build views.py and forms.py. I am not even sure that model is built correctly, since I … -
TypeError at /en/ Object of type '__proxy__' is not JSON serializable
I'm trying to implement a breadcrumb in my django project. To archieve that, I've created a mixin which is inherited by every view I have. Here is the code: class BreadcrumbMixin(object): index = False url_name = None verbose_name = None def breadcrumbUpdate(self, breadcrumb, new_value): for i in range(len(breadcrumb)): if breadcrumb[i]['url_name'] == new_value['url_name']: breadcrumb = breadcrumb[:i + 1] return breadcrumb breadcrumb.append(new_value) return breadcrumb def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) new_value = { 'url_name' : self.url_name, 'verbose_name' : self.verbose_name, 'url' : reverse_lazy(self.url_name, **kwargs) } if self.index: self.request.session['breadcrumb'] = [new_value,] else: self.request.session['breadcrumb'] = self.breadcrumbUpdate(self.request.session['breadcrumb'], new_value) return context The attributes index, url_name and verbose_name are set in each view that inherits it. For instance: class Index(BreadcrumbMixin, TemplateView): template_name = 'crud/index.html' index = True url_name = 'index' # Name argument used in urls.py verbose_name = _('Index') It basically use these informations to make a list of dicts, which is passed to the template using the session dictionary. In the template, it is being called like this: <div style="margin-left: 10px;"> {% for element in request.session.breadcrumb %} <a href="{{ element.url }}" class="breadcrumb"> {{ element.verbose_name }} </a> {% endfor %} </div> The problem is, it's giving me the error mentioned in the title. Here is the traceback: Environment: … -
How references fields that are foreignkey in another table
Documents models.py ERD-Restaurants python3.6.4, django 2.0 Hello django pals, I need some help. Only business_id is not generated automatically (user_id and dish_id are generated automatically by django API) This is the Rating class(Rating Table) in model.py class Rating(models.Model): business = models.? r1 dish = models.? r2 user = models.ForeignKey(User, on_delete=models.CASCADE, primary_key=True) rating = models.IntegerField() comment = models.TextField() How can I references r1 with Price.restaurant, r2 with Price.dish? and set these 2 fields as primary key so that the 3 fields (business, dish and user) can form a composite key. Is valid use the argument , primary_key=True in ForeignKey fields as I am using there? Because I need to set that fields as primary key too. -
How to access the a reverse relation of a reverse relation django
I am determined to try get all the other users that replied to the same comment as a given reply. I have come up with the following python, however I am concerned this will do more than one DB call. other_repliers = [other_reply.user for other_reply in my_reply.comment.replies.filter()] I'm looking for a one-db-call fix. The Psuedo-SQL logic would be something like: SELECT u.* FROM users AS u INNER JOIN replies AS r ON r.user = user.id WHERE r.comment = {my_reply.comment} AND r.user != {my_reply.user} Does anyone know a way that I can do the above SQL in a single query? -
"Invalid HTTP_HOST header" from unknown domain
I am using Nginx and Gunicorn to host a Django project. I need to secure this site, and as a test I set up Let's encrypt to an unused domain of mine. While tailing the Django access log, I noticed the following entry from time to time: Invalid HTTP_HOST header: 'aydinfatih.com'. You may need to add u'aydinfatih.com' to ALLOWED_HOSTS. This is an unknown domain to me, and while trying to access the domain (it got 400 response), I could se more of these log entries on my server. What is this? Is it related to my SSL-setup, and an indication that it's not secure? server { server_name example.com example.com; location /static/ { root /home/user/project/django-project; } location /media/ { root /home/user/project/django-project; } location / { include proxy_params; proxy_pass http://unix:/home/user/project/project.sock; } listen 443 ssl; # managed by Certbot ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem; # managed by Certbot ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem; # managed by Certbot include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot if ($scheme != "https") { return 301 https://$host$request_uri; } # managed by Certbot } server { listen 80; server_name my.server.ip.here example.com; return 301 https://example.com; } I added the following to my server block: if ($host !~* ^(example.com|www.example.com)$ ) { return … -
Django How to save just one field of form
I want to save a field from form by radio button and others from excelfile the excel file imports correct by itself but when i want to save a file from form, it doesnt work My view is : def ca_import(request): uploadform=UploadFileForm(None) if request.method == 'POST' : uploadform = UploadFileForm(request.POST, request.FILES) if uploadform.is_valid(): file = uploadform.cleaned_data['docfile'] workbook = openpyxl.load_workbook(filename=file, read_only=True) first_sheet = workbook.get_sheet_names()[0] worksheet = workbook.get_sheet_by_name(first_sheet) data = [] try: for row in worksheet.iter_rows(row_offset=1): stock = Stocks() stock.user = request.user stock.name = row[0].value stock.number = row[1].value stock.suffix = row[2].value stock.brand = row[3].value.upper() stock.comment = row[4].value stock.price = row[5].value stock.seller = uploadform.cleaned_data.get("seller") data.append(stock) print(uploadform.cleaned_data.get("seller")) #it print the correct value but not save # Bulk create data Stocks.objects.bulk_create(data) #save from form instance=uploadform.save() instance.user=request.user instance.save() messages.success(request,"Saved Successfully" ,extra_tags="saveexcel") except : messages.error(request,_('Error! '),extra_tags="excelerror") return render(request, 'BallbearingSite/excelfile.html',{'uploadform':uploadform}) -
Django formset, using a form to do two different actions
My models Agency has manytomany sell_houses and manytoamany buy_houses, (they have slightly different information in each model). a Member only belongs to one Agency. I want to be able to populate a formset on a page that shows all the Members that belong to one Agency and be able to choose on a form either to sell_house or buy_house but can not do both at the same time. forms.py class ManageHouseForm(forms.Form): buy_house = forms.ModelChoiceField( label="buy a house", queryset=None, ) sell_house = forms.ModelChoiceField( label="sell a house", queryset=None, ) def __init__(self, agency, *args, **kwargs): super(ManageHouseForm, self).__init__(*args, **kwargs) self.fields["buy_house"].queryset = agency.sell_houses self.fields["sell_house"].queryset = agency.buy_houses template.htm <form method="post"> {% csrf_token %} <table....>{{formset.management_form}} {% for form in formset.forms %} {% for member in members %} <tr> <td>{{member.name}}</td> {% for field in form.visible_fields %} <td> {{ field }} </td> {% endfor %} </tr> {% endfor %} </tbody> {% endfor %} </table> views.py def agency_member_manage(request, agency_name): template = "template.htm" agency = get_object_or_404(models.Agency, name=agency_name) members = models.Machine.objects.filter(group=machine_group) ManageHouseFormSet = formset_factory(wraps( forms.ManageHouseForm)(partial(forms.ManageHouseForm, agency=agency))) if request.method == "POST": formset = ManageHouseFormSet(data=request.POST) if formset.is_valid(): for form in formset: action_buy_house(member, form) #do something with members else: formset = ManageHouseFormset() context = {"members": members,"agency":agency,"formset": formset,} return render(request, template, context=context) My biggest problem is … -
In a Django project with different versions of settings.py, can I use a dict.update() method on a setting?
I'm working on a project with multiple settings files, similar to https://medium.com/@ayarshabeer/django-best-practice-settings-file-for-multiple-environments-6d71c6966ee2. There is a settings directory with multiple settings files: settings ├── base.py ├── development.py ├── production.py └── staging.py The base.py contains the default permissions setting for the Django REST framework: REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.IsAuthenticated', ], } In production, I would like to use the default JSON renderer instead of the browsable API. So in production.py I have something like this: from .base import * REST_FRAMEWORK.update({ 'DEFAULT_RENDERER_CLASSES': ( 'rest_framework.renderers.JSONRenderer' ) }) I find this more DRY than defining a REST_FRAMEWORK setting in every file. The question is: will this work? Can you update an imported setting dictionary in a settings.py? -
Connect to API endpoint from Django and returning data
I have a django form which at the moment checks for postcodes in areas that the app can deliver. I would like to integrate it with postcodes.io API endpoint to check that the actual postcode is valid. The endpoint is as below: api.postcodes.io/postcodes/:postcode/validate This is my form code: from django import forms class PostCodeForm (forms.Form): pcode = forms.CharField() def clean_pcode(self): permitted = {'gu15','GF34','FG34','BT25'} pcode = self.cleaned_data['pcode'].lower() if not pcode[:4] in (permitted): raise forms.ValidationError("Apologies, but does not currently deliver to you postcode.") return pcode I am stuck in terms of how to integrate with the API endpoint from Django. Any help is really appreciated. Thanks in advance. -
force Django tests to write models into database
I am setting up a very simple Django project and with a very simple test like: def test_name(self): t = Thing.objects.create(name='a') print(t.id) import time time.sleep(30) self.assertEqual('a', t.name) The tests passes of course, but the database (TEST database) doesn't get populated with my Thing model information, even though I can actually see its id as you can see my script. When I connect into the database, the Thing table is always empty (I also saw some comments about it in the documentation). Now, how can I tell Django to actually populate the data? I am using mysql, and checking the complete logs I see Django is creating a SAVEPOINT before populating data (that is not committed) and once the test passes, it goes back into that previous SAVEPOINT. I am using: Django==2.0.1 mysqlclient==1.3.12 pytest==3.3.2 pytest-django==3.1.2 I would like Django to actually populate the TEST database, with the information from my tests and at the end drop that database, that's why I am assuming Django is creating a completely new database just for tests.