Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Is there a better way to move between Django's views aside from pasting new url?
I'm learning to use Django to build my web application. I want to access another page through a link on the index page, but the browser keeps appending the file and app name to the request. How do I get the browser to switch through links without appending the directory name each time ? I've tried using reg exp with the old url method but it doesn't seem to work # My project # urls.py urlpatterns = [ path('admin/', admin.site.urls), path('', include('index.urls')), ] # My app # urls.py urlpatterns = [ path('index/',include([ path('', views.index,name="index"), path('theteam', views.theteam,name="theteam"), path('services',views.services,name="services"), path('quotes',views.quotes,name="quotes"), path('insurance',views.insurance,name="insurance"), path('contact',views.contact,name="contact"), path('thanks', views.thanks,name="thanks"), ])), ] # Views def index(request): return render(request, 'index/index.html') def theteam(request): return render(request, 'index/theteam.html') def services(request): return render(request, 'index/services.html') def quotes(request): form = ContactForm(request.POST or None) if request.method == 'POST': return redirect(request, '/thanks/') return render(request, 'index/quotes.html', { 'form': form }) def insurance(request): return render(request, 'index/insurance.html') def contact(request): return render(request, 'index/contact.html') def thanks(request): return render(request, '/thanks.html') #My Views HTML <div class="menu-bar "> <ul> <a href="{% url 'services' %}"> <li>Services</li></a> <a href="{% url 'theteam' %}"><li>The Team</li> </a> <a href="{% url 'quotes' %}"><li>Quotes</li> </a> <a href="{% url 'insurance' %}"> <li>Insurance</li></a> <a href="{% url 'contact' %}"><li>Contact Us</li></a> </ul> </div> So far I've … -
Which platforms to use for backend and Android frontend
I plan to write a service that should communicate both with Android app and Desktop app and send various data (login data, images, texts etc.) My questions are: 1) What to use for backend, on server side I have an experience with Django and MySql but should you recommend something else cause this is a large project and I don't mind learning new stuff 2) What to use for frontend for developing Android app that will communicate with server Here I don't have the any clue, all I ever tried to develop any app but that was very primitive was some previous versions of Delphi XEs; I heard that new Delphi Seattle has great stuff for cross compiling, is it any worth or to complete forget about Delphi? Thanks. -
Django project, I need advice about my model
I need to do opportunity for users to save body# and slug field from Post model in data base, but i have issue i have 10 fields named body1, body2 e.t.c in Post model. User self make choice wich field need to save. How better to save some body# field in data base user ? How to do it in my html code ? class PostDig(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='dig') slug = models.SlugField(max_length=150, blank=True) body = models.TextField(blank=True) date_save= models.DateTimeField(auto_now_add=True) def __str__(self): return self.name class Meta: ordering = ['-date_save'] models.py class Post(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) image = VersatileImageField( 'Image', upload_to='media_my/',null=True, blank=True ) title = models.CharField(max_length=150, db_index=True) slug = models.SlugField(max_length=150, unique=True, blank=True) tags = models.ManyToManyField('Tag', blank=True, related_name='posts') body1 = models.TextField(blank=True) body2 = models.TextField(blank=True) body3 = models.TextField(blank=True) body4 = models.TextField(blank=True) body5 = models.TextField(blank=True) body6 = models.TextField(blank=True) body7 = models.TextField(blank=True) body8 = models.TextField(blank=True) body9 = models.TextField(blank=True) body10 = models.TextField(blank=True) date_pub= models.DateTimeField(auto_now_add=True) def get_absolute_url(self): return reverse('post_detail_url', kwargs={'slug':self.slug}) def get_update_url(self): return reverse('post_update_url', kwargs={'slug': self.slug}) def get_delete_url(self): return reverse('post_delete_url', kwargs={'slug': self.slug}) def save(self, *args, **kwargs): if not self.id: self.slug= gen_slug(self.title) super().save(*args, **kwargs) def __str__(self): return self.title class Meta: ordering = ['-date_pub'] HTML code .. {% extends 'face/base_face.html'%} {% block title %} {{ post.title }} - … -
python web app, trigger async function without separate server
How should I trigger async functions during django/flask views? In node.js, I can easily bypass an async function, like so: module.exports.myView = function (request, response) { myVerySlowFunction(function (nonsense) { console.log('handle triggered nonsense', nonsense); }); response.json({ message: 'ok' }); } This is very typical to do in node, but I've never seen it done in django. I'm wanting to translate it like so: def my_view(request): apply_async(my_very_slow_function) return Response({'message': 'okay'}) I have used Celery in the past for this, but it feels like overkill to have a separate server running just so I can trigger async functions. I know I can trigger async functions like so: https://stackoverflow.com/a/1239252/4637643, but have never seen them in the context of a web application. Is this a bad idea? should I look for another solution? -
Provide lists as required arguments to function (Python)
I'm using a python wrapper to access an api and in the docstring it says that you can provide a lists as required arguments. Here is the function I'm using to call send_orders wrapper function def send_orders(self, runner_id, odds, side, stake, temp_id=None, session=None): """ Place an order(s) on a runner, multiple orders can be places by providing lists of the required arguments. :param runner_id: runner(s) on which to place bets. :type runner_id: int :param odds: odds at which we wish to place the bet. :type odds: float :param side: The type of bet to place, dependent on exchange. :type side: MatchbookAPI.bin.enums.Side :param stake: amount in account currency to place on the bet. :type stake: float :param temp_id: A helper ID generated by the client to help understand the correlation between multiple submitted offers and their responses. :type temp_id: str :param session: requests session to be used. :type session: requests.Session :returns: Orders responses, i.e. filled or at exchange or errors. :raises: MatchbookAPI.bin.exceptions.ApiError """ date_time_sent = datetime.datetime.utcnow() params = { 'offers': [], 'odds-type': self.client.odds_type, 'exchange-type': self.client.exchange_type, 'currency': self.client.currency, } if isinstance(runner_id, list): if isinstance(temp_id, list): for i, _ in enumerate(runner_id): params['offers'].append({'runner-id': runner_id[i], 'side': side[i], 'stake': stake[i], 'odds': odds[i], 'temp-id': temp_id[i]}) else: for … -
How to pass created object in createview right to updateview in django
I have a createview view in my django app: class GroupCreateView(CreateView): ..do tons of stuf def get_context_data(self, **kwargs): ..do more stuf context['group_id'] = None #added this def post(self, request, *args, **kwargs): if self.request.POST.has_key('submit'): ..DO LOTS OF STUFF.. #below I REALLY want to take the object created automagically by the django submit form etc, and pass it right to the update view return HttpResponseRedirect("") I really want to load the page with the created object but as an updateview Anyway to do this from the create view? -
Django get values with point field
I want to get x and y by this queryset: user = User.objects.values('id', 'email', 'username', 'point').first() But I get the following result: {'id': 85270, 'email': 'username_0@email.com', 'username': 'username_0', 'point': <Point object at 0x7f8e061cc2b8>} How can I get an x and y, making an queryset with values ? I want to get something like this: {'id': 85270, 'email': 'username_0@email.com', 'username': 'username_0', 'point__x': '-4.266398314110177', 'point__y': '-39.39432682357033'} -
Tags for relationship in Django
I'm working on an inventory tracking application. Barebones, just for learning. One issue I'm running into is how products can be related. Categories works fine, but a Logitech G35 Mouse could be nested under Peripherals, but Peripherals will be populated with mice, keyboards, headphones, Waacom pads, etc. To help find what we need faster I wanted to incorporate tags of some sort, but I've noticed there's something called Tags native to Django which keeps hijacking my search. Here's my Item model: class Item(models.Model): name = models.CharField(max_length=100) description = models.CharField(max_length=100) manufacturer = models.ForeignKey('Manufacturer', blank=True, null=True, on_delete=models.SET_NULL) part_number = models.CharField(max_length=50, blank=True, null=True) introduction = models.DateField(auto_now=True) category = models.ForeignKey('Category', default='Uncategorized', on_delete=models.SET_DEFAULT) quanity = models.IntegerField(default=0) is_retired = models.BooleanField(default=False) def __str__(self): return self.name def add(self): pass def remove(self): pass def retire(self): # Rex came up with this, roll credits. pass def count(self): pass So if I were to add a Logitech G35 Mouse as an item, I'd like the tag(s) to be mouse, mice, wireless and so forth. Where might I find the information needed to implement this? -
register 4 arguments on django admin - TypeError: register() takes at most 3 arguments (4 given)
here is my code.. and I know that I am not alowed to give 4 arguments to register() in django admin.py, but I want to use ProductAdmin and ProductExportImportAdmin together for Product model.. is there possible I am doing that? Is there a way? # -*- coding: utf-8 -*- from __future__ import unicode_literals from django.contrib import admin from .models import Supplier, Customer, Product, PoOrder from import_export.admin import ImportExportModelAdmin from import_export import resources class ProductResource(resources.ModelResource): class Meta: model = Product exclude = ('id', 'created_at', 'edited_at',) class ProductExportImportAdmin(ImportExportModelAdmin): resource_class = ProductResource class ProductAdmin(admin.ModelAdmin): search_fields = ['code','name'] admin.site.register(Supplier) admin.site.register(Customer) admin.site.register(Product, ProductAdmin, ProductExportImportAdmin) admin.site.register(PoOrder) -
How to pass a table data from and HTML front end to the server side in Django through JSON?
I have multiple tables in the front end. Based on the information provided in the table an oracle database needs to be updated at the back end. The server side is coded in Django and the front end is the typical HTML, Javascript, Bootstrap, Jquery etc. The data is needed to be passed as JSON request since the application sends data to the server side in a JSON format. The question is how to parse the table in the front end, encompass it in an object and send it through JSON and parse it in Python( Django )? My plan is to store the values in a javascript object and then pass it in json format. By I am unable to iterate over the values of the table itself. var exclScoreObj = new Object(); $("#exclTable tr").each(function() { $(this).find('td').each(function(){ console.log($(this).val()) }) }) -
How to make a portfolio page in django
I would like to know what to use on this page for models from django.db import models class Person(models.Model): first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) enter image description here I put a pic of what I'm going for -
Formset management_form gives wrong TOTAL_FORMS value after refreshing
I'm using Django 2.14 and my set up for this view is a form and a formset. The code looks like this: order_form = CreateOrder(instance=order, initial=initial) item_form_set = inlineformset_factory(Order, Item, form=AddItem, validate_min=True, min_num=1, extra=1) formset = ItemFormSet(instance=order, initial=items_initial) # form processing ... I used this setup to add more forms for the formset using javascript. So everything works fine if I try to add extra forms. The only issue is that I can't remove forms sometimes. This only happens after I add and remove some fields and refresh the page. The TOTAL_FORMS value is initialized as 1 even if there are two forms (1 initial + 1 extra). It seems like the browser is populating TOTAL_FORMS with the previous value (before the page is refreshed). <input type="hidden" name="item_set-TOTAL_FORMS" value="1" id="id_item_set-TOTAL_FORMS"> Based on this post from reddit it seems like one solution might be to add the autocomplete='off' tag to stop this behavior. I don't want to use an external library to solve this problem, so is there any other way to hook on to the formset management form to add these tags? Would it be any better to use javascript to modify the TOTAL_FORMS value? -
How to create a read-only custom Django model field?
Desired behavior: Excluded from save, create, update, etc. Can otherwise be accessed normally through the ORM, e.g. when loading model instances or querying. Included in DB creation SQL. Number 1 is definitely what I need the most help with, I think I've already got the rest working. Do I need to individually override all these methods? I'm hoping there's a common way I can exclude this field for any insert/update queries. For a bit more background, these are for MySQL generated fields. The fields are currently updated by various stored procs, so using something like signals wouldn't work; it has to happen outside of Python. Thanks! -
how to deploy a django-celery-rabbitmq-redis-flower app using Kubernetes
I have a Django-web app that uses celery workers to do asynchronous jobs. I have containerised the app and successfully ran it on my local machine and my local GCP account. However, when I deploy it using Kubernetes and create a webservice. I see connection errors in my logs such as [CRITICAL] WORKER TIMEOUT that I think comes from GUNICORN and ConnectionRefusedError: [Errno 111] Connection refused from flower. I don't know how to fix the problem. The followings summarise my deployment info: I have the following Dockerfile: FROM python:3.6 ENV LANG=C.UTF-8 LC_ALL=C.UTF-8 WORKDIR / COPY requirements.txt ./ RUN pip install --no-cache-dir -r requirements.txt COPY app/seg/requirements.txt ./app/seg/ RUN pip3 install --no-cache-dir -r ./app/seg/requirements.txt RUN rm requirements.txt RUN apt-get update RUN apt-get -y install ffmpeg RUN apt-get -y install nginx RUN mkdir -p config/nginx/conf.d RUN touch config/nginx/conf.d/local.conf COPY . / WORKDIR /app CMD gunicorn --preload -b :8000 api.wsgi and a docker-compose file as follows: services: app: build: . image: &app gcr.io/xxxx/app restart: "no" command: ["gunicorn", "--preload", "-b", ":8000", "api.wsgi"] env_file: &envfile - env.env volumes: - ./app:/app networks: - nginx_network depends_on: - broker - backend worker: build: . image: *app restart: "no" env_file: *envfile command: ["celery", "worker", "--app=worker.worker.app", "--concurrency=1", "--hostname=worker@%h", "--loglevel=ERROR"] volumes: - … -
Simple way to minify/scramble Django js
There is a simple way to minify and/or obfuscate JS that it's present in my django templates? I'm also using template variables and templates tag into js, so, the standard uglifyjs or similar are not fitting my original request. Anything to do? -
Django first run: SyntaxError: invalid syntax
https://docs.djangoproject.com/en/2.1/intro/tutorial01/ Hi, I just installed django and I'm running through the starter tutorials and when I enter the first command: $ python -m django --version I get an error stating: SyntaxError: invalid syntax. Why am I getting this? I am brand new to django. -
Setting django timezone on runtime
While I have a default timezone of UTC in my settings file, occasionally I need to overwrite this timezone. Without using something like pytz is it possible to set the tza at runtime. For example: from django.utils import timezone tz = 'America/New_York' now = timezone(tz).now() # in pseudocode Would there be a way to accomplish the above? -
How to pass 'using' DB to the django connection object
To query a specific database in django I can do: Item.objects.using('specific_db').all() Is there a way to do the same using a django connection? For example: >>> from django.db import connection >>> cursor=connection.using('specific_id').cursor() If not, how could I get a cursor/connection for a specific DB without manually providing all the credentials? -
installing APACHE MacOS: configure: error: C compiler cannot create executables
I am trying to install APACHE webserver on my Macbook Pro for use with DJango and everything seems to go fine with the install until: checking whether the C compiler works... no configure: error: in `/Users/darrinwebster/desktop/httpd-2.4.37': configure: error: C compiler cannot create executables whereis gcc gives: /usr/bin/gcc gcc-v gives: Configured with:--prefix=/Volumes/Blackbox/Applications/Xcode.app/Contents/Developer/usr --with-gxx-include-dir=/usr/include/c++/4.2.1 Apple LLVM version 6.1.0 (clang-602.0.53) (based on LLVM 3.6.0svn) Target: x86_64-apple-darwin15.6.0 Thread model: posix Here is the config log: This file contains any messages produced by compilers while running configure, to aid debugging if configure makes a mistake. It was created by configure, which was generated by GNU Autoconf 2.69. Invocation command line was $ ./configure --prefix=/Darin-Macbook-Pro/local/apache2 --------- Platform. --------- hostname = Darrins-MacBook-Pro.local uname -m = x86_64 uname -r = 15.6.0 uname -s = Darwin uname -v = Darwin Kernel Version 15.6.0: Thu Jun 21 20:07:40 PDT 2018; root:xnu-3248.73.11~1/RELEASE_X86_64 /usr/bin/uname -p = i386 /bin/uname -X = unknown /bin/arch = unknown /usr/bin/arch -k = unknown /usr/convex/getsysinfo = unknown /usr/bin/hostinfo = Mach kernel version: Darwin Kernel Version 15.6.0: Thu Jun 21 20:07:40 PDT 2018; root:xnu-3248.73.11~1/RELEASE_X86_64 Kernel configured for up to 4 processors. 2 processors are physically available. 4 processors are logically available. Processor type: i486 (Intel 80486) Processors active: 0 … -
Mac osx Mojave compatibility issue with mod_wsgi for use with Django and apache
I am setting up a new Mac server running Mojave 10.14.2 to run with django and which utilizes mod_wsgi for Apache. When adding the configuration to load the mod_wsgi module, Apple does not allow for third party modules with their Apache installation. I have this working on a windows PC but need to put on the Mac server. I have tried a few things as posted HERE I have also tried a custom installation of httpd through homebrew and it does not work. -
Django template slow when creating report (many variables, many models, many lists)
I'm a newbie trying to use Django to create a report about the participants of a team and I'm doing something fundamentally wrong and have spent several hours trying to figure out what's going wrong - the report is still hitting the DB about 4000+ times. An abbreviated version of what I'm doing is below. ​ Any help, pointers or other resources would be much appreciated! ​ For the Team model: class Team(BenchmarkData): year = models.ForeignKey(Period, on_delete=models.CASCADE, null=True) sponsor = models.ForeignKey(Person, on_delete=models.CASCADE) goal = models.ForeignKey(Goal, on_delete=models.CASCADE, null=True) ...other non-relational properties... def _participation_queryset(self): from .participation import Participation pp = Participation.objects.filter(team=self.id) return pp @cached_property def average_points(self): list_participation = [participation.calculated_yearly_points_per_hour for participation in self._participation_queryset()] try: return mean(list_participation) @cached_property ... For the Participation model: class Participation(models.Model): person = models.ForeignKey(Person, on_delete=models.CASCADE, null=True) team = models.ForeignKey(Team, on_delete=models.CASCADE, null=True) year = models.ForeignKey(Period, on_delete=models.CASCADE, null=True) start_date = models.DateField('Began', null=True) end_date = models.DateField('Left', blank=True, null=True) active = models.BooleanField('Active?', null=True) yearly_points = models.FloatField(default=0, null=True) yearly_hours_of_play = models.FloatField(default=0) ...other non-relational properties... @cached_property def calculated_yearly_points_per_hour(self): try: return self.yearly_points / self.yearly_hours_of_play except ZeroDivisionError: return 0 ...other cached properties... For my View, I used: class PlanReport(TemplateView): template_name = 'pension/report/index.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) self.team = get_object_or_404(Plan, id=self.kwargs['team_id']) self.sponsor = get_object_or_404(Company, id=self.kwargs['sponsor_id']) self.report … -
debug toolbar django not executing
I've been trying to use the debug Toolbar from django by applying the docs. Before adding the INTERNAL_IPS=['127.0.0.1'] on settings.py, django can be executed locally and i can run it, but the toolbar doesn't appear. Once I add the INTERNAL_IPS=['127.0.0.1'], I get the following error: Internal Server Error: / Traceback (most recent call last): File "C:\Anaconda3\envs\mydjan\lib\site-packages\django\core\handlers\exception.py", line 35, in inner response = get_response(request) File "C:\Anaconda3\envs\mydjan\lib\site-packages\django\utils\deprecation.py", line 97, in __call__ response = self.process_response(request, response) File "C:\Anaconda3\envs\mydjan\lib\site-packages\debug_toolbar\middleware.py", line 133, in process_response panel.generate_stats(request, response) File "C:\Anaconda3\envs\mydjan\lib\site-packages\debug_toolbar\panels\staticfiles.py", line 136, in generate_stats "staticfiles_finders": self.get_staticfiles_finders(), File "C:\Anaconda3\envs\mydjan\lib\site-packages\debug_toolbar\panels\staticfiles.py", line 148, in get_staticfiles_finders for path, finder_storage in finder.list([]): File "C:\Anaconda3\envs\mydjan\lib\site-packages\django\contrib\staticfiles\finders.py", line 125, in list for path in utils.get_files(storage, ignore_patterns): File "C:\Anaconda3\envs\mydjan\lib\site-packages\django\contrib\staticfiles\utils.py", line 28, in get_files directories, files = storage.listdir(location) File "C:\Anaconda3\envs\mydjan\lib\site-packages\django\core\files\storage.py", line 313, in listdir for entry in os.listdir(path): FileNotFoundError: [WinError 3] The system cannot find the path specified: 'C:\\Users\\Alvaro Lloret\\Home\\alpha_trader\\static\\' [10/Jan/2019 20:14:30] "GET / HTTP/1.1" 500 94293 Find hereby my settings.py: import os from django.contrib.messages import constants as messages # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'n2th-ublablalablablals' … -
How do I reference a user's most recently uploaded file in a view, then do something with the file, then return the data?
I'm trying to build a site specific to a product that I make. The product records data from sensors on a CSV file. What I want to do: Users can create an account, upload their CSVs, then, using chart.js, I pass x and y axis data to the template through template tags. I have the idea working well with a local CSV test file, but now I need to reference the users specific files in the view, then parse the csv and return the data as context, but I'm stuck on how to reference the specific users csv and how to handle the file in the view. models.py from django.db import models from django.contrib.auth.models import User from django.contrib.auth import get_user_model def user_directory_path(instance, filename): return 'user_{0}/{1}'.format(instance.user.id, filename) class Document(models.Model): docfile = models.FileField(null=True, blank=True, upload_to=user_directory_path) description = models.CharField(max_length=255) user = models.ForeignKey(User, on_delete=models.CASCADE) def get_upload_path(self,filename): return "media/uploads/"+str(self.user.id)+"/"+filename def __str__(self): return self.description class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) #additional portfolio_site = models.URLField(blank=True) profile_pic = models.ImageField(upload_to='profile_pics',blank=True) docfiles = models.OneToOneField(Document, on_delete=models.CASCADE) def __str__(self): return self.user.username views.py from django.shortcuts import render, redirect, render_to_response, reverse from django.http import HttpResponse from django.http import HttpResponseRedirect from django.conf import settings from django.contrib import messages from . import parsecsv import json from … -
How Django and JavaScript work together for running Python script?
I am wondering how to accomplish the below with Django: Consider a function in JavaScript: $('#button').click(function(){ var rand_val = Math.random(); // here some code sends this rand_val to a Python script in Django app // as seen below, script is run and generates result alert('This is the result ' + result); }) The script in the Django app: def my_func(rand_val): # result = (some operations with rand_val) return result The Python script will be run in Django virtual environment. With a button click, run a Python script and show the result on the page. -
Interfacing a QR code recognition to a django database
I'm coming to you with the following issue: I have a bunch of physical boxes onto which I still stick QR codes generated using a python module named qrcode. In a nutshell, what I would like to do is everytime someone wants to take the object contained in a box, he scans the qr code with his phone, then takes it and put it back when he is done, not forgetting to scan the QR code again. Pretty simple, isn't it? I already have a django table containing all my objects. Now my question is related to the design. I suspect the easiest way to achieve that is to have a POST request link in the QR code which will create a new entry in a table with the name of the object that has been picked or put back, the time (I would like to store this information). If that's the correct way to do, how would you approach it? I'm not too sure I see how to make a POST request with a QR code. Would you have any idea? Thanks. PS: Another alternative I can think of would be to a link in the QR code to …