Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
List first entry from reverse foreign key
I have the following Models class Book(models.Model): title = description = class Chapter(models.Model): book = models.ForeignKey(Book,on_delete=models.CASCADE) How to list all first chapters by date added from all books? like I want to have a queryset or a list of Chapter, to display in templates. -
Django - String customizing color for template
Hey is it possible to customize a text in my view which I output on my template with certain words being in a different colour? For example I have a word which I output to my template: def test(request): text = 'test text but this section is red' return render(request, 'test.html', {'text':test} How can I get a different colour for 'this section is red' but the rest is normal to show in my template? -
Django - Use the slug from the view in the template
How do I use a (class-based) view's slug in the template? I want to use it again in other urls. -
django change id of autocomplete-light select
I have an autocomplete selectbox defining by django-autocomplete-light . I have written this codes : <script> $(document).ready(function() { $('#select2-id_raste-container').change(function() { var selectedValue = $(this).val(); window.alert(selectedValue); if($(this).val() === 'abc') { $('#d_car').closest('span').hide(); } else if (selectedValue === 'bcd') { $('#select2-id_car-container').closest('span').show(); } }); }); </script> so i need to have the selectbox id , these codes works for other types of form (like Textinput, select , ...) but i dont know how can i define autocomplete.Select2 ? class StocksForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(StocksForm, self).__init__(*args, **kwargs) for field_name, field in self.fields.items(): field.widget.attrs['class'] = 'form-control' field.widget.attrs['style']= 'width:60%' self.fields['raste'].widget = forms.TextInput???(attrs={ 'id': 'rasteId'}) class Meta(): model=Stocks fields=('user','car','stname','mark','description','pic','price') widgets = { 'car': autocomplete.Select2(url='BallbearingSite:car_autocomplete'), } -
Creating an object with django rest api referencing a foreign key
Sorry if this has been asked, but I've dug through documentation and even a few other StackOverflow questions and none seem to solve my problem. I'm a bit new to Django, so sorry if this is answered somewhere else. (Django REST - Create object with foreign key using serializers) Just doing company_id as was suggested here did not work. Still not getting there. Also tried the custom create function in the view as was suggested and no luck with that either. I have a Company class with 2 values (id 1 and 2) and a Project class that contains a foreign key company_id back to Company. A Project must have exactly 1 Company. Right now, I'm unable to do a POST to create a Project. I've tried referencing company_id specifically and even tried referencing nested serializers in the serializer. Nothing seems to work. I'd probably prefer to send the company_id in POSTs and get back the referenced object when I GET. At this point though, I'd just be happy to get a POST to work. Note: The default company_id value is 1 so the first one I create will actually work. It's just that all subsequent POSTs end up giving … -
django select2 chained dropdown
I am new to Django and trying to get familiar with it. I have two dropdown menu's which are chained. I want to select a country, and from there I want to choose the city from that country. I have the following models in models.py from django.db import models # Create your models here. class Country(models.Model): name = models.CharField(max_length=255) def __str__(self): return self.name class City(models.Model): name = models.CharField(max_length=255) country = models.ForeignKey('Country', related_name="cities", on_delete=models.CASCADE) def __str__(self): return self.name My views.py has the following code: from django.shortcuts import render from django import forms from django_select2.forms import ModelSelect2Widget from .models import Country, City # Create your views here. class AddressForm(forms.Form): country = forms.ModelChoiceField( queryset=Country.objects.all(), label=u"Country", widget=ModelSelect2Widget( model=Country, search_fields=['name__icontains'], ) ) city = forms.ModelChoiceField( queryset=City.objects.all(), label=u"City", widget=ModelSelect2Widget( model=City, search_fields=['name__icontains'], dependent_fields={'country': 'country'}, max_results=500, ) ) def start(request): form = AddressForm() return render(request, 'startpagina.html', {'form': form}) My HTML has the following code: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Chained</title> {{ form.media.css }} <script src="https://code.jquery.com/jquery-2.2.4.min.js" integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44=" crossorigin="anonymous"></script> </head> <body> <table> {{ form }} </table> <br> {{ form.media.js }} </body> </html> I populated my country and city models with the following values: Country: name: Nederland Country: name: belgie City: name: Amsterdam, country: Nederland City: name: Rotterdam, country: … -
How to can i open a network path in file explorer to view files using javascript?
I asked this before, and I am told that this is impossible. It this true? All I want is to open a network folder when I click a button. To open 'File Explorer' to that network path on the PC. Or on the browser. I prefixed file:/// to the path so that it may open in a browser. //jQuery for button 1. $(document).on("click",".Button1",function (){ var log1 = "file:/"+this.value; // this.value has path like this: ///PCname/Foldername/subfolder window.location.href = log1 }); Am I asking the impossible? I can't copy my files to document root. I have 10s of thousands of files. This is why I want to open a folder on my Windows PC to that path. My path to files changes depending on what the user has selected, and my files are 50MB or less. Is there a way I could open a network folder in the browser like this (not local drive, network path), OR a way to open a folder on the PC to that network path when I click a button? My backend is Django+Python. -
How to deny access to root but allow subdirectory access in nginx / django / python?
My current nginx config looks like this: server { listen 443 ssl http2 default_server; listen [::]:443 ssl http2 default_server; server_name _; root /usr/share/nginx/html; ssl_certificate "PEM"; ssl_certificate_key "PEM"; # It is *strongly* recommended to generate unique DH parameters # Generate them with: openssl dhparam -out /etc/pki/nginx/dhparams.pem 2048 #ssl_dhparam "/etc/pki/nginx/dhparams.pem"; ssl_session_cache shared:SSL:1m; ssl_session_timeout 10m; ssl_protocols TLSv1 TLSv1.1 TLSv1.2; ssl_ciphers HIGH:SEED:!aNULL:!eNULL:!EXPORT:!DES:!RC4:!MD5:!PSK:!RSAPSK:!aDH:!aECDH:!EDH-DSS-DES-CBC3-SHA:!KRB5-DES-CBC3-SHA:!SRP; ssl_prefer_server_ciphers on; # Load configuration files for the default server block. include /etc/nginx/default.d/*.conf; proxy_set_header Host $http_host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; location / { proxy_pass http://127.0.0.1:80; } error_page 404 /404.html; location = /40x.html { } error_page 500 502 503 504 /50x.html; location = /50x.html { } } # configuration of the server server { # the port your site will be served on listen 80; # the domain name it will serve for server_name SERVER; charset utf-8; # max upload size client_max_body_size 75M; # adjust to taste # Finally, send all non-media requests to the Django server. location / { uwsgi_pass django; include /etc/nginx/uwsgi_params; # the uwsgi_params file you installed } } ] I want to disallow access to root and allow access to subdirectory /dir1/. However, doing something like this doesn't work, because I get a duplicate location "/" issue … -
Why the built-in set_language view of Django doesn't set a custom language?
After adding a New Language to my site. I am trying to change the site language, but it doesn't work. from django.conf import locale LANGUAGES = ( ('en', _('English')), ('fr', _('French')), ('zz', _('Zulu Pic')), ) EXTRA_LANG_INFO = { 'ht': { 'bidi': False, # right-to-left 'code': 'zz', 'name': 'Zulu Pic', 'name_local': u'Zulu Pic', #unicode codepoints here }, } locale.LANG_INFO = dict(locale.LANG_INFO,**EXTRA_LANG_INFO) LANGUAGE_CODE = 'en' I set the URL in my root project: path('i18n/setlange', include('django.conf.urls.i18n')), And in my HTML: <form action="{% url 'set_language' %}" method="post" class=""> <input name="next" type="hidden" value="{{ request.path }}"> {% csrf_token %} <select name="language" class="form-control form-control-sm"> {% get_current_language as LANGUAGE_CODE %} {% get_available_languages as LANGUAGES %} {% get_language_info_list for LANGUAGES as languages %} {% for language in languages %} <option value="{{ language.code }}"{% if language.code == LANGUAGE_CODE %} selected="selected"{% endif %}> {{ language.name_local|title }} ({{ language.code|upper }}) </option> {% endfor %} </select> </form> Submit the form with js $("select[name=language]").change(function(){ $(this).closest("form").submit(); }); Every time I select zz as language, it is not selected. The site shows the default: 'EN'. 'FR' works correctly. -
How to debug django collecstatic
Every-time I run collecstatic on my django project, for some reason it doesn't upload changed files to s3. Is there a way to debug this? I'm using django-storages==1.6.6 even I tried to upgrade to the new version but still not success. I tried this one with no success: Django-storages not detecting changed static files -
Proper way of choosing the right corresponding class in python
I'm using Django and have a few models. They correlate to each other without any foreign keys, but I want to be able to select them in a centralized place, here are the models (without the inheritance and fields so tests are easy): class ItemTypeOne: pass class ItemOneExtra: pass # ----------------------------- class ItemTypeTwo: pass class ItemTwoExtra: pass # ... and so on What I thought of using so far its a dict to map them, like so: correlated_extra_model = {ItemTypeOne: ItemOneExtra, ItemTypeTwo: ItemTwoExtra}[ItemTypeOne] This works, but I'm not sure if its acceptable -
Trying to offload long running task from django to a separate thread
I have a Django 2 app with an action in the admin that takes one to many images and uses the face_recognition project to find faces and store the face information in the database. I would like to offload this action to a different thread. However, in my attempt at starting a new thread, the Django app does not return until all the threads are done. I thought that if I put the long running task in a separate thread, then the Django app would return and the user could do other things with it as the long running process ran in the background. DocumentAdmin action code: def find_faces_4(self, request, queryset): from biometric_identification.threaded_tasks import map_thread_pool_face_finder images_to_scan = [] for obj in queryset: # If the object is a Photo with one to many people, send to face recognition metadata = DocumentMetaData.objects.filter(document_id = obj.document_id)[0].metadata if "Photo Type" in metadata and metadata["Photo Type"] != 'No People': images_to_scan.append(obj) map_thread_pool_face_finder(images_to_scan) The code to find the images: def map_thread_pool_face_finder(document_list): t0 = timeit.default_timer() pool = ThreadPool() pool.map(fftask2, document_list) pool.close() pool.join() t1 = timeit.default_timer() logger.debug("Function map_thread_pool_face_finder {} seconds".format(t1 - t0)) def fftask2(obj): find_faces_task(obj.document_id, obj.storage_file_name.name, settings.MEDIA_ROOT) The find_faces_task does the actual image scanning for faces. I expected the … -
Modeling restaurant menu with django
I am creating a website with a collection of menus from restaurants in my town. As you know every restaurant has a menu comprised of sections(Appetizers, Entrees, etc) with different items under each section(I.e under Appetizers: Mozzarella Sticks, Nachos, etc.) I have the following models.py: from django.db import models class Restaurant(models.Model): name = models.CharField(max_length=50) address = models.CharField(max_length=80) def __str__(self): return self.name class MenuSection(models.Model): restaurant = models.ForeignKey( Restaurant, on_delete=models.CASCADE, primary_key=True, ) food_type = models.CharField(max_length=50) def __str__(self): return self.food_type class MenuItem(models.Model): restaurant = models.ForeignKey( Restaurant, on_delete=models.CASCADE, primary_key=True, ) MenuSection = models.ForeignKey( MenuSection, on_delete=models.CASCADE, primary_key=True, ) food_item = models.CharField(max_length=50) def __str__(self): return self.food_item Obviously, food sections and food items are going overlap between restaurants. I thought this would not be an issue but in my db I have two Restaurant objects, one already has a MenuSection named "Appetizers", I tried to give the second Restaurant a MenuSection named "Appetizers" and it will not let me do so, saying: "Menu item with this MenuSection already exists." How can I fix this? Thanks in advance for any help. -
Performance of Delete/Create vs Delete/Update
Trying to figure out best practice here. I am writing some end points that will essentially combine a group of objects if their dates become contiguous. Say there are three objects I want to group. obj1 = {id: 1, start: 1/1/18, end: 1/2/18} obj2 = {id: 2, start: 1/2/18, end: 1/3/18} obj3 = {id: 3, start: 1/4/18, end: 1/5/18} Are there any performance benefits or best practices to either of the following - Create one new object which is essentially the 3 previous objects grouped together by date. Then delete the three other objects. obj4 = {id: 4, start: 1/1/18, end: 1/5/18} obj1.delete() obj2.delete() obj3.delete() or Update one objects fields to represent the new dates. Then delete the other two objects. obj1.end = 1/5/18 obj1.save() obj2.delete() obj3.delete() Just pseudo code here, but this is in a django app. Thanks -
Forked django-oscar app with custom model unable to migrate
I am using django-oscar and forked some of the apps to use a custom model. Specifically with the catalogue model. By default there are products, product types and product categories. I am trying to extent the model to have a collections table, and to have each product be associated with a collection. I want to make the relationship so that when a collection is deleted all associated products are deleted, but so that deleting a product does not delete a collection. Aside from adding a new collection table, I extent the product table to have a multiplier field (which will contain an integer used to multiply the wholesale price...if there is a better way to do this please inform) and a foreign key to the collections table. Based on my understanding everything looks good. This is my models.py from the forked catalogue app: from django.db import models class Collection(models.Model): name = models.CharField(max_length=50) prod_category = models.CharField(max_length=50) description = models.TextField() manufacturer = models.TextField() num_products = models.IntegerField() image_url = models.URLField() from oscar.apps.catalogue.abstract_models import AbstractProduct class Product(AbstractProduct): collection = models.ForeignKey(Collection, on_delete=models.CASCADE) multiplier = models.DecimalField(max_digits=2, decimal_places=1) from oscar.apps.catalogue.models import * When I do makemigrations via manage.py, after asking for default values (something I will deal … -
Django dependent/ chained drop down form
I am trying to add a chained drop down form to a project I'm creating. I've tried numerous solution's including django smart select and using jQuery but I can't seem to get it to work.I want a drop down form where if one option is selected in one drop down menu more options will be displayed based on the the other drop downs. For example if I select the state as Texas the next drop down will show cities in Texas like Dallas. I'm using django 2.1.2 and most of the mentioned solutions are running on an older version of django. I attatched an image to clarify. Thanks example image -
How to implement tokenauthentication before views?
I have been learning how to use djangorestframework token authentication using different blog posts and youtube videos. As for reference, I was following the blog here: https://chrisbartos.com/articles/how-to-implement-token-authentication-with-django-rest-framework/ I could not understand how are we going to check the token before accessing any page. I mean, I am developing an app, that exposes the todos a user creates through the rest framework. I have added a login that saves a user and returns the token created for that person. Now,I want to check that token to find the todos api that the person created and view it in my browser in a seperate url. As an example: Once I login through localhost:8000/api/v1/login, I should get the todos created by me at api/v1/todos in json rest api format. And if I go to api/v1/todos/1/, it should give me the details of the todo, as I have created in the serializers. It would be great if someone could help. -
Using variable names rather than ints in a Django url path
I have a model called Label: class Label(models.Model): """The label a song was released on.""" name = models.CharField(max_length=100) def __str__(self): """String for representing the model object.""" return self.name And I am defining the url path(s) for each individual model instance of label: # Page for a single label. path('labels/<int:label_id>/', views.label, name='label'), Is it possible to use the label.name attribute rather than an int:label_id in the URL path? How can this be done? This is the corresponding code in views.py: def label(request, label_id): """Show a single label and associated songs.""" label = Label.objects.get(id=label_id) context = {'label': label} return render(request, 'great_songs_app/label.html', context) -
How to add a LogEntry for a Django data-migration?
Thinking of adding a Django admin log-entry in a data-migration, to ensure that the admin logs will reflect the fact that a data-migration has taken place. Assuming this could be done -- please correct me if I'm wrong -- using the approach described here and here , I have two questions: Does this make sense, or should these things be kept separate? What user should I use for the LogEntry (should I create a dedicated user)? The docs are not very forthcoming on the subject of LogEntry usage. -
Internal Server Error in Python Django using TastyPie
That's the error I've got Internal Server Error: /drawevent/ Traceback (most recent call last): File "C:\Program Files\Python37\lib\site-packages\tastypie\resources.py", line 211, in getattr return self.fields[name] KeyError: 'get' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Program Files\Python37\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "C:\Program Files\Python37\lib\site-packages\django\utils\deprecation.py", line 93, in call response = self.process_response(request, response) File "C:\Program Files\Python37\lib\site-packages\django\middleware\clickjacking.py", line 26, in process_response if response.get('X-Frame-Options') is not None: File "C:\Program Files\Python37\lib\site-packages\tastypie\resources.py", line 213, in getattr raise AttributeError(name) AttributeError: get [14/Dec/2018 12:01:21] "GET /drawevent/ HTTP/1.1" 500 64469 -
Nginx: Proxy_pass error to Django Project
Problem I have a Django project with Gunicorn that I am trying to deploy with Nginx, but it is erring on line 19 where I try to set the proxy_pass to my domain. proxy_pass <my_public_domain>.com; The error nginx: [emerg] invalid URL prefix in /etc/nginx/sites-enabled/default:19 My code My Gunicorn command is: /usr/local/bin/gunicorn config.wsgi --bind 0.0.0.0:5000 --chdir=/app And then the Nginx config is the following. I have replaced by actual domain with <my_public_domain> upstream django { server 127.0.0.1:8001; } server { set $my_host $host; if ($host ~ "\d+\.\d+\.\d+\.\d+") { set $my_host "<my_public_domain>.com"; } listen 80; server_name <my_public_domain>.com; charset utf-8; error_log /dev/stdout info; access_log /dev/stdout; location / { proxy_pass <my_public_domain>.com; proxy_set_header Host $my_host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; } if ($http_x_forwarded_proto != 'https') { return 301 https://$my_host$request_uri; } } -
Django Soft deletion and generic relationship manager
I'm using Django 2.0 in a project and I'm implementing a soft delete function so I can recover deleted objects. I've used this this implementation of soft deletion in my Django project, and it works fine. But some models have GenericRelation with objects that may be soft deleted. Is there a way to implement a GenericRelationManager like the BaseModelManager, that will ignore soft deleted objects? For example, suppose I have the following code (borrowed from this site): from django.contrib.contenttypes.fields import GenericForeignKey from django.contrib.contenttypes.models import ContentType class Activity(BaseModel): FAVORITE = 'F' LIKE = 'L' UP_VOTE = 'U' DOWN_VOTE = 'D' ACTIVITY_TYPES = ( (FAVORITE, 'Favorite'), (LIKE, 'Like'), (UP_VOTE, 'Up Vote'), (DOWN_VOTE, 'Down Vote'), ) user = models.ForeignKey(User) activity_type = models.CharField(max_length=1, choices=ACTIVITY_TYPES) date = models.DateTimeField(auto_now_add=True) # Below the mandatory fields for generic relation content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.PositiveIntegerField() content_object = GenericForeignKey() And from django.db import models from django.contrib.contenttypes.fields import GenericRelation from activities.models import Activity class Post(models.Model): ... likes = GenericRelation(Activity) class Question(models.Model): ... activities = GenericRelation(Activity) class Answer(models.Model): ... votes = GenericRelation(Activity) class Comment(models.Model): ... likes = GenericRelation(Activity) If I soft delete an activity, I would still be able to find the soft deleted activity through these GenericRelations. Can I … -
Django Context TypeError: context must be a dict rather than Context
template = loader.get_template('organizer/tag_list.html') context = Context( { 'tag_list': Tag.objects.all() } ) template.render(context) Running these things on terminal produces following error: Traceback (most recent call last): File "", line 1, in File "/home/noitanec/noitanec/django/django/lib/python3.6/site-packages/django/template/backends/django.py", line 59, in render context = make_context(context, request, autoescape=self.backend.engine.autoescape) File "/home/noitanec/noitanec/django/django/lib/python3.6/site-packages/django/template/context.py", line 270, in make_context raise TypeError('context must be a dict rather than %s.' % context.class.name) TypeError: context must be a dict rather than Context. What's wrong here ? -
How to specify Accept headers from rest_framework.test.Client?
I'm trying to set up an API endpoint to reply with HTML or JSON depending on the incoming request's Accept headers. I've got it working, testing through curl: > curl --no-proxy localhost -H "Accept: application/json" -X GET http://localhost:8000/feedback/ {"message":"feedback Hello, world!"} > curl --no-proxy localhost -H "Accept: text/html" -X GET http://localhost:8000/feedback/ <html><body> <h1>Root</h1> <h2>feedback Hello, world!</h2> </body></html> I can't figure out how to use the APITestCase().self.client to specify what content should be accepted, though. My view looks like class Root(APIView): renderer_classes = (TemplateHTMLRenderer,JSONRenderer) template_name="feedback/root.html" def get(self,request,format=None): data={"message": "feedback Hello, world!"} return Response(data) and my test code looks like class RootTests(APITestCase): def test_can_get_json(self): response = self.client.get('/feedback/',format='json',Accept='application/json') self.assertEqual(response.status_code, 200) self.assertEqual(response.accepted_media_type,'application/json') js=response.json() self.assertIn('message', js) self.assertEqual(js['message'],'feedback Hello, world!') which dies on the test for response.accepted_media_type. What's the right way to do this? All I can find says that the format argument should be sufficient. -
libraria to generate graph
I am making an application in django for hypothesis testing, there is a jquery library that allows you to make a graph to represent the case