Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to serve subdirectory as root in nginx using django?
When a user visits www.website.com I would like to server content as if the user went to www.website.com/frontend/. However, I want to mask the /frontend/ part of the url so the user doesn't see it. Can this be done? What would my rewrite rule look like? -
How to create a user/password for a selenium test case in django
I am trying to write some selenium test cases using Django (or python's) unit testing frameworks. What I have below is for a login, but I have previously created the user: from selenium import webdriver from django.conf import settings class SeleniumClient(object): def __init__(self, driver="Chrome", url=BASE_URL): if driver == 'Chrome': self.driver = webdriver.Chrome(CHROMEDRIVER) self.url = url def _get_url_from_path(self, path): return self.url.rstrip('/') + '/' + path.lstrip('/') def login(self): url = self._get_url_from_path("/login") self.driver.get(url) email_field = self.driver.find_element_by_id('email').send_keys(TEST_USERNAME) password_field = self.driver.find_element_by_id('password').send_keys(TEST_PASSWORD) self.driver.find_element_by_id('loginButton').submit() Is there a way to "generate" the user on the test and destroy it when it's done? If so, how would I do that? -
Xlsxwriter cant find file for close() in Django Project
I am attempting to write a class to create an excel sheet using my Django Models. I have created the following class: class workBook(object): def __init__(self, title, data): path = '\\workbooks\\' + title + '.xlsx' print(os.path.normpath(path)) self.workbook = xlsxwriter.Workbook(os.path.normpath(path)) newWorkSheet(self.workbook, data) self.workbook.close() The method creates the workbook with the proper path but when I close it I get the following error: [Errno 2] No such file or directory: '\\workbooks\\Test.xlsx' I know this is because of the double "\" but I dont know how to send the correct path to the close method. I also know the rest of my class works because it does not throw this error when I simply put the file name and not a full directory. Thank you! -
Editing a topic and its sub entries at the same time
I want to edit an entry and it's child at the same time. So I have a Price model which has Entry (another model) as it's foreign key. ` class Price(models.Model): price = models.ForeignKey(Entry, on_delete = models.CASCADE) ptext = models.FloatField(blank = True, null = True) date_added = models.DateTimeField(auto_now_add = True) class Meta: verbose_name_plural = 'prices' def __str__(self): return self.ptext[:50] + "..." ` How would I pull the price from the entry model? I can only modify data inside the entry model, but not the price model. The instance part is giving a problem in particular. I don't know what to put for the PriceForm instance. def edit_entry(request, entry_id): entry = Entry.objects.get(id = entry_id) price = entry.price_set.get.all() topic = entry.topic check_topic_owner(topic.owner, request.user) if request.method != 'POST': form = EntryForm(instance = entry) form2 = PriceForm(instance = price) else: form = EntryForm(instance=entry, data = request.POST) form2 = PriceForm(instance=price, data = request.POST) if form.is_valid() and form2.is_valid(): form.save() form2.save() return HttpResponseRedirect(reverse('learning_logs:topics')) context = {'entry': entry, 'topic': topic, 'form': form, 'form2':form2} return render(request, 'learning_logs/edit_entry.html', context) -
Django - getting data from url in register view
Im trying to grab data from the url /register/?ref=123456 but having some trouble with it. User registration is tied to one of my views: class UserRegisterView(FormView): form_class = UserRegisterForm template_name = 'accounts/user_register_form.html' success_url = '/accounts/login' def form_valid(self, form): username = form.cleaned_data.get('username') email = form.cleaned_data.get('email') password = form.cleaned_data.get('password') new_user = User.objects.create(username=username, email=email) new_user.set_password(password) new_user.save() ref = self.request.GET.get('ref', 'None') print(ref) return super(UserRegisterView, self).form_valid(form) I'm trying to use "self.request.GET.get('ref', 'None')" to grab the data, but each time a user registers ref returns "None" rather than 123456 Here is the user_register_form.html: <div class='row'> <div class='col-sm-4 offset-sm-4 mt-3'> <h1 class='text-center mt-3'>Sign Up</h1> <form {% if form_id %} id='{{ form_id }}' {% endif %} class='form mt-3' method='POST' action=''> {% csrf_token %} {{ form|crispy }} <input class='btn btn-primary-new' id="submit" type="submit" value="Sign Up" /> </form> </div> </div> -
django adding a background image to admin site
I need to display a background image in the django admin site. I have looked to all questions but none of the solutions seems to work for me. I just want the background to appear in the back of the admin site. I have a base_site.html {% extends "admin/base_site.html" %} {% load static %} {% block extrastyle %} {{ block.super }} <link rel="stylesheet" type="text/css" href="{% static "css/admin-extra.css" %}" /> {%endblock%} The extra-admin.css head.bg { /* The image used */ background-image: url('{{ STATIC_URL }} background.png') ; /* Full height */ height: 100%; /* Center and scale the image nicely */ background-position: center; background-repeat: no-repeat; background-size: cover; } This extra-admin.css is loaded as I see it in the firfox inspector. However the image does not appear. something seems to appear in the background but is immediately covered by the normal admin site with white background. -
Is ASKBOT project still alive?
It seems that askbot.com hasn't been updated since 2016, docs at askbot.org/doc are properly 404, the latest release on the GitHUB has been released on 2015-04-22, and in the askbot_requirements.txt I found django>=1.8,<1.9... At the time of this writing the latest official version of django is v2.1.4, so AskBot is quite a bit behind. Despite all the negative, git log kind of reveals that it's still an active project: $ git log -100 --date=iso | grep Date: | sort -ruk2,2 Date: 2018-10-28 16:26:23 -0300 Date: 2018-10-15 21:34:30 -0300 Date: 2018-10-14 17:09:29 -0300 Date: 2018-10-13 16:14:25 -0300 Date: 2018-09-23 20:06:21 -0300 Date: 2018-09-22 19:53:15 -0300 Date: 2018-09-17 17:22:02 -0300 Date: 2018-09-06 11:41:11 -0300 Date: 2018-09-04 20:24:43 -0300 Date: 2018-09-02 11:52:41 -0300 Date: 2018-08-28 11:15:44 -0300 Date: 2018-08-26 13:32:05 -0300 Date: 2018-08-25 20:01:44 -0300 Date: 2018-08-18 19:22:05 -0300 Date: 2018-08-15 09:25:52 -0300 Date: 2018-08-12 20:18:20 -0300 Date: 2018-08-05 21:22:23 -0400 Date: 2018-07-22 17:44:37 -0400 Date: 2018-07-14 21:46:46 -0400 Date: 2018-05-28 12:06:19 -0400 Date: 2018-05-26 20:27:24 -0400 Date: 2018-05-25 10:09:06 -0400 Date: 2018-05-24 19:18:06 -0400 Date: 2018-05-20 21:17:18 -0400 Date: 2018-05-19 20:08:32 -0400 Date: 2018-05-14 11:23:25 -0400 Date: 2018-04-29 12:31:34 -0300 So it begs the question, whether it's still alive? We are considering … -
500 Internal Server Error!! - Issue in wsgi in django application migrating from python2.7 to python3.6
I am getting 500 Internal Server Error when I migrated my django app from python2.7 to python3.6. I have created a new virtualenv, and created all the apps individually. The virtualenv is defined in uwsgi.ini file home = /home/netadc/.venvs1/netadc I have installed all the packages using pip3.6. I am not sure what I am missing. Every config in uwsgi is same as python2.7 when it was working.I am using uwsgi 2.0.13. I have restarted nginx as well. Is there a separate uwsgi for python3 which I cannot locate? The socket permissions are also same as before. Please help. -
Django: render only last part of image url in template
I've a model that has an image field as attribute. I need to render the attributes of this model in my template, but specifically the image.url atribute. Right now, I can render it as: /media/images/floral.jpg However, I'd like to only render the last part: floral.jpg So I'm using this in my template: {{ cart_item.image.url }} What can I do to only render the last part of the image url? class SizeQuantity(models.Model): cart = models.ForeignKey(Cart, on_delete=models.CASCADE) product = models.ForeignKey(Product, on_delete=models.CASCADE) size = models.CharField(max_length=20, choices=TAMANIOS) quantity = models.CharField(max_length=20, choices=CANTIDADES) image = models.ImageField(upload_to='images', blank=True, null=True) uploaded_at = models.DateTimeField(auto_now_add=True) def __str__(self): return self.size view.py def cart_detail(request, total = 0, counter = 0, cart_items = None): try: cart = Cart.objects.get(cart_id = _cart_id(request)) cart_items = SizeQuantity.objects.filter(cart = cart) except ObjectDoesNotExist: pass return render(request, 'cart.html', dict(cart_items = cart_items, total = total, counter = counter)) -
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