Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Why can't I see user-added information with Django?
I'm using Django 2.2 and PostgreSQL. I want to display the product information that the user has added to the detail page. I see the information in the 'StoreOtherInfo' model, but I don't see the information in the 'Product' model. How can I do that? store/models.py class StoreOtherInfo(models.Model): user = models.OneToOneField(User,on_delete=models.CASCADE,blank=True, null=True) phone = models.CharField(max_length=11) fax = models.CharField(max_length=11) province = models.CharField(max_length=11) district = models.CharField(max_length=11) neighborhood = models.CharField(max_length=11) def __str__(self): return self.user.username products/models.py class Product(models.Model): seller = models.ForeignKey(User, on_delete = models.CASCADE) product_name = models.CharField(max_length = 50) description = RichTextField() added_date = models.DateTimeField(auto_now_add=True) def __str__(self): return self.seller store/views.py from store.models import StoreOtherInfo from products.models import Product def neighbor_detail(request,username): neighbor_detail = get_object_or_404(User,username = username) neighbor_list = StoreOtherInfo.objects.all() product_list = Product.objects.all() return render(request, 'store/neighbor_detail.html', {'neighbor_detail':neighbor_detail, 'neighbor_list':neighbor_list, 'product_list':product_list}) templates/neighbor_detail.html <strong><p>{{neighbor_detail.first_name}} {{neighbor_detail.last_name}}</p></strong> <p>{{neighbor_detail.username}}</p> <p>{{neighbor_detail.email}}</p> <p>{{neighbor_detail.storeotherinfo.phone}}</p> <p>{{neighbor_detail.storeotherinfo.fax}}</p> <p>{{neighbor_detail.storeotherinfo.province}}</p> <p>{{neighbor_detail.storeotherinfo.district}}</p> <p>{{neighbor_detail.storeotherinfo.neighborhood}}</p> <p>{{neighbor_detail.product.product_name}}</p> <p>{{neighbor_detail.product.description}}</p> <p>{{neighbor_detail.product.added_date}}</p> -
Asynchronous asyncio Django command runs sequentially
I have written a simple command to loop through all of Result objects and check its www field (representing URL of the published scientific result eg. https://doi.org/10.1109/5.771073) There is 1M results in our db and I want to check the www field, if link is corrupted, I will guess it by appending actual doi to https://doi.org/ and save it (in the www field) This is my first time working with asyncio but I think barebones of my code are right and I can't find out, why code gets ran synchronously. Main command: # -*- coding: utf-8 -*- from __future__ import unicode_literals import asyncio import time from django.core.management.base import BaseCommand from isvav.models import Result def run_statistics(array_of_results, num_of_results): num_of_correct_urls = 0 sum_check_time = 0 max_check_time = 0 for res in array_of_results: if res[0]: num_of_correct_urls += 1 if res[1] > max_check_time: max_check_time = res[1] sum_check_time += res[1] return f"""ran statistics on {num_of_results} isvav.results \n ---------------------------------------------------------------------------- correct/corrupted link ratio: {num_of_correct_urls} / {num_of_results - num_of_correct_urls}\n Mean time to check URL: {sum_check_time / num_of_results}\n """ class Command(BaseCommand): help = 'checks url in www field of isvav.result, if the link is unresponsive, tries to generate new hyperlink ' \ '(using DOI) and saves it in www_processed field' … -
uWSGI runs Django project from command line but not from Emperor uwsgi.service file
I am running a virtualenv with Python3.6 on Ubuntu 16.04 for my Django project using uwsgi and NGINX. I have uWSGI installed globally and also in the virtualenv. I can run my project from the command line using uWSGI within the env with /home/user/Env/myproject/bin/uwsgi --http :8080 --home /home/user/Env/myproject --chdir /home/user/myproject/src/myproject -w myproject.wsgi and go to my domain and it loads fine. However I am obviously running uWSGI in "Emperor mode" and when I set the service file up (along with NGINX) the domain displays internal server error. The uWSGI logs trace to --- no python application found --- I was having this problem when running uwsgi --http :8080 --home /home/user/Env/myproject --chdir /home/user/myproject/src/myproject -w myproject.wsgi because it was using the global install uwsgi instead of the virtualenv one. I changed my StartExec to the virtualenv uwsgi path but no luck. I can't figure out what I'm doing wrong, path error? Syntax error? my /etc/systemd/system/uwsgi.service file [Unit] Description=uWSGI Emperor service [Service] ExecStartPre=/bin/bash -c 'mkdir -p /run/uwsgi; chown user:www-data /run/uwsgi' ExecStart=/home/user/Env/myproject/bin/uwsgi --emperor /etc/uwsgi/sites Restart=always KillSignal=SIGQUIT Type=notify NotifyAccess=all [Install] WantedBy=multi-user.target -
Showing JSON data from DB to django template using Bootstrap tabs
Sorry I'm a programming newb.... But I am trying to use Bootstrap's tabs navigation to view JSON data from a DB. I'm transforming the JSON data to a 2d array and storing my data as the following dictionary: tables = {u'table1': [[u'CS6140', u'Machine Learning', u'Sara Arunagiri'], [u'CS5100', u'Foundations of Artificial Intelligence ', u'Chris Amato'], [u'CS6220', u'Data Mining', u'Pablo Esteves']], u'table2': [[u'Paris, France', u'06/01/2019 - 06/15/2019', u'James Fraser'], [u'Edinborough, Scotland', u'10/14/2019 - 10/20/2019', u'Claire Beauchamp'], [u'Rome, Italy', u'12/14/2019-12/24/2019', u'Timothy Dalton']], u'table3': [[32423, u'iced coffee', 3.67], [34241, u'bagel', 2.99], [3109247, u'sanwich', 5.99]]} Thus each table dict entry corresponds to one table.So I'm trying to loop through the dictionary and 2d array to create different tables. I'm currently trying to loop through the dictionary as follows but I am getting the 2d arrays replicated 3 times for each of the tables when instead I want each table in my dictionary to only be shown once for each tab. {% for table in tables %} <div class="tab-content"> <div id="{{ table }}" class="tab-pane active"> {% for table in tables.values %} <table class="table"> <tbody> {% for row in table %} <tr> {% for item in row %} <td>{{ item }}</td> {% endfor %} </tr> {% endfor … -
isinstance() arg 2 must be a type or tuple of types error in Django
I keep getting this error when using Django Rest Framework: isinstance() arg 2 must be a type or tuple of types Here is my model: class mymodel(models.Model): firstfield = models.ArrayModelField(models.FloatField()) secondfield = models.ArrayModelField(models.FloatField()) def save(self, *args, using=None, **kwargs): super(mymodel, self).save(*args, using='mydb', **kwargs) Here is what my data looks like: id: 'some id here' firstfield: ['somefloat', 'somefloat'], ['another float', 'another float'] ... secondfield: ['somefloat', 'somefloat'], ['another float', 'another float'] ... I think the problem is with my MongoDB data. Basically, firstfield and 'secondfield' are both lists, containing other lists, each one with two float numbers. Every advice to fix this is appreciated -
ModuleNotFoundError: No module named 'config'
I am new to python and django. Every time I try any django command, I am getting this error. Following are the steps that I tried: [namespace] user@tux:~/Workspace/udemy$ python3 -m venv restapi-basics [namespace] user@tux:~/Workspace/udemy$ cd restapi-basics/ [namespace] user@tux:~/Workspace/udemy/restapi-basics$ source bin/activate (restapi-basics) [namespace] user@tux:~/Workspace/udemy/restapi-basics$ which python /home/user/Workspace/udemy/restapi-basics/bin/python (restapi-basics) [namespace] user@tux:~/Workspace/udemy/restapi-basics$ python --version Python 3.6.8 (restapi-basics) [namespace] user@tux:~/Workspace/udemy/restapi-basics$ which pip /home/user/Workspace/udemy/restapi-basics/bin/pip (restapi-basics) [namespace] user@tux:~/Workspace/udemy/restapi-basics$ pip --version pip 9.0.1 from /home/user/Workspace/udemy/restapi-basics/lib/python3.6/site-packages (python 3.6) (restapi-basics) [namespace] user@tux:~/Workspace/udemy/restapi-basics$ pip install django djangorestframework djangorestframework-jwt Collecting django Downloading https://files.pythonhosted.org/packages/d6/57/66997ca6ef17d2d0f0ebcd860bc6778095ffee04077ca8985928175da358/Django-2.2.4-py3-none-any.whl (7.5MB) 100% |████████████████████████████████| 7.5MB 193kB/s Collecting djangorestframework Downloading https://files.pythonhosted.org/packages/af/2a/055e65e1aa25cc2726d68d78b859a7b5955c673bc5e4646b205c21e05b25/djangorestframework-3.10.2-py3-none-any.whl (908kB) 100% |████████████████████████████████| 911kB 748kB/s Collecting djangorestframework-jwt Downloading https://files.pythonhosted.org/packages/2b/cf/b3932ad3261d6332284152a00c3e3a275a653692d318acc6b2e9cf6a1ce3/djangorestframework_jwt-1.11.0-py2.py3-none-any.whl Collecting pytz (from django) Downloading https://files.pythonhosted.org/packages/87/76/46d697698a143e05f77bec5a526bf4e56a0be61d63425b68f4ba553b51f2/pytz-2019.2-py2.py3-none-any.whl (508kB) 100% |████████████████████████████████| 512kB 928kB/s Collecting sqlparse (from django) Downloading https://files.pythonhosted.org/packages/ef/53/900f7d2a54557c6a37886585a91336520e5539e3ae2423ff1102daf4f3a7/sqlparse-0.3.0-py2.py3-none-any.whl Collecting PyJWT=1.5.2 (from djangorestframework-jwt) Downloading https://files.pythonhosted.org/packages/87/8b/6a9f14b5f781697e51259d81657e6048fd31a113229cf346880bb7545565/PyJWT-1.7.1-py2.py3-none-any.whl Installing collected packages: pytz, sqlparse, django, djangorestframework, PyJWT, djangorestframework-jwt Successfully installed PyJWT-1.7.1 django-2.2.4 djangorestframework-3.10.2 djangorestframework-jwt-1.11.0 pytz-2019.2 sqlparse-0.3.0 (restapi-basics) [namespace] user@tux:~/Workspace/udemy/restapi-basics$ which django-admin /home/user/Workspace/udemy/restapi-basics/bin/django-admin (restapi-basics) [namespace] user@tux:~/Workspace/udemy/restapi-basics$ django-admin startproject cfehome (restapi-basics) [namespace] user@tux:~/Workspace/udemy/restapi-basics$ cd cfehome/ (restapi-basics) [namespace] user@tux:~/Workspace/udemy/restapi-basics/cfehome$ ls cfehome manage.py (restapi-basics) [namespace] user@tux:~/Workspace/udemy/restapi-basics/cfehome$ python manage.py runserverTraceback (most recent call last): File "/home/user/Workspace/udemy/restapi-basics/lib/python3.6/site-packages/django/core/management/base.py", line 323, in run_from_argv self.execute(*args, **cmd_options) File "/home/user/Workspace/udemy/restapi-basics/lib/python3.6/site-packages/django/core/management/commands/runserver.py", line 60, in execute super().execute(*args, **options) File "/home/user/Workspace/udemy/restapi-basics/lib/python3.6/site-packages/django/core/management/base.py", line 364, in execute output = self.handle(*args, **options) File … -
Pip install error exit status 1 while installing a pip package
I'm having a issue while installing a python package, it came out a issue that something regarding of spacy issue . How could i solve it and install successfully ? I am a rookie on python Collecting pyresparser Using cached https://files.pythonhosted.org/packages/ad/8f/5a55cfb269621d3374a6ba4aed390267f65bdf6c4fed8b1c0cbf5a118f0e/pyresparser-1.0.2-py3-none-any.whl Collecting idna>=2.8 (from pyresparser) Downloading https://files.pythonhosted.org/packages/14/2c/cd551d81dbe15200be1cf41cd03869a46fe7226e7450af7a6545bfc474c9/idna-2.8-py2.py3-none-any.whl (58kB) |████████████████████████████████| 61kB 261kB/s Collecting pyrsistent>=0.15.2 (from pyresparser) Using cached https://files.pythonhosted.org/packages/b9/66/b2638d96a2d128b168d0dba60fdc77b7800a9b4a5340cefcc5fc4eae6295/pyrsistent-0.15.4.tar.gz Collecting thinc>=7.0.4 (from pyresparser) Using cached https://files.pythonhosted.org/packages/92/39/ea2a3d5b87fd52fc865fd1ceb7b91dca1f85e227d53e7a086d260f6bcb93/thinc-7.0.8.tar.gz Collecting blis>=0.2.4 (from pyresparser) Using cached https://files.pythonhosted.org/packages/59/9e/84a83616cbe5daa94909da38b780e93bf566dc2113c3dc35d7b4cad52f63/blis-0.2.4.tar.gz Collecting tqdm>=4.32.2 (from pyresparser) Using cached https://files.pythonhosted.org/packages/9f/3d/7a6b68b631d2ab54975f3a4863f3c4e9b26445353264ef01f465dc9b0208/tqdm-4.32.2-py2.py3-none-any.whl Collecting certifi>=2019.6.16 (from pyresparser) Using cached https://files.pythonhosted.org/packages/69/1b/b853c7a9d4f6a6d00749e94eb6f3a041e342a885b87340b79c1ef73e3a78/certifi-2019.6.16-py2.py3-none-any.whl Collecting spacy>=2.1.4 (from pyresparser) Using cached https://files.pythonhosted.org/packages/f1/04/f25cdc3cb6d143ef397c23718026aff606c3e558cbd4939e9e4cb0a4b515/spacy-2.1.7.tar.gz Installing build dependencies ... error ERROR: Command errored out with exit status 1: command: 'c:\users\user\appdata\local\programs\python\python37-32\python.exe' 'c:\users\user\appdata\local\programs\python\python37-32\lib\site-packages\pip' install --ignore-installed --no-user --prefix 'C:\Users\User\AppData\Local\Temp\pip-build-env-kc70rx4b\overlay' --no-warn-script-location --no-binary :none: --only-binary :none: -i https://pypi.org/simple -- setuptools 'wheel>0.32.0.<0.33.0' Cython 'cymem>=2.0.2,<2.1.0' 'preshed>=2.0.1,<2.1.0' 'murmurhash>=0.28.0,<1.1.0' 'thinc>=7.0.8,<7.1.0' cwd: None Complete output (70 lines): Collecting setuptools Using cached https://files.pythonhosted.org/packages/ec/51/f45cea425fd5cb0b0380f5b0f048ebc1da5b417e48d304838c02d6288a1e/setuptools-41.0.1-py2.py3-none-any.whl Collecting wheel>0.32.0.<0.33.0 Using cached https://files.pythonhosted.org/packages/bb/10/44230dd6bf3563b8f227dbf344c908d412ad2ff48066476672f3a72e174e/wheel-0.33.4-py2.py3-none-any.whl Collecting Cython Using cached https://files.pythonhosted.org/packages/ba/08/4f0d09d63b713955f9c6937923f1b1432331f468912b65824b19b9d82d19/Cython-0.29.13-cp37-cp37m-win32.whl Collecting cymem<2.1.0,>=2.0.2 Using cached https://files.pythonhosted.org/packages/eb/cb/4ff546a491f764f67284572d25c57927e3f17103adf979bc99d90128f3eb/cymem-2.0.2-cp37-cp37m-win32.whl Collecting preshed<2.1.0,>=2.0.1 Using cached https://files.pythonhosted.org/packages/00/52/ef641ebb40e287b95e9742e7f3120dca0350d92b3d0ef050e5133acf8931/preshed-2.0.1-cp37-cp37m-win32.whl Collecting murmurhash<1.1.0,>=0.28.0 Using cached https://files.pythonhosted.org/packages/22/e9/411be1845f1ac07ae3bc40a4b19ba401819baed4fa63b4f5ef28b2300eb4/murmurhash-1.0.2.tar.gz Collecting thinc<7.1.0,>=7.0.8 Using cached https://files.pythonhosted.org/packages/92/39/ea2a3d5b87fd52fc865fd1ceb7b91dca1f85e227d53e7a086d260f6bcb93/thinc-7.0.8.tar.gz Collecting blis<0.3.0,>=0.2.1 (from thinc<7.1.0,>=7.0.8) Using cached https://files.pythonhosted.org/packages/59/9e/84a83616cbe5daa94909da38b780e93bf566dc2113c3dc35d7b4cad52f63/blis-0.2.4.tar.gz Collecting wasabi<1.1.0,>=0.0.9 (from thinc<7.1.0,>=7.0.8) Using cached https://files.pythonhosted.org/packages/f4/c1/d76ccdd12c716be79162d934fe7de4ac8a318b9302864716dde940641a79/wasabi-0.2.2-py3-none-any.whl Collecting srsly<1.1.0,>=0.0.6 (from thinc<7.1.0,>=7.0.8) Using cached https://files.pythonhosted.org/packages/84/59/6f276ab6d74888eed0e999d617101ed7357fc1ee073e9aac92d53260bd23/srsly-0.0.7.tar.gz Collecting numpy>=1.7.0 (from thinc<7.1.0,>=7.0.8) Using cached https://files.pythonhosted.org/packages/f9/3f/d75fc983cc420b2acb5fae446b950e2dc9e5395a79fa76859d2528352d2c/numpy-1.17.0-cp37-cp37m-win32.whl Collecting plac<1.0.0,>=0.9.6 … -
Mixing Django models and SQLAlchemy in model fields: can it be done?
I have several models, with ids defined like this: id = models.UUIDField(primary_key=True, default=uuid.uuid4, blank=True, editable=False) I want to be able to use the SQLAlchemy server_default option, I tried this way: id = Column( UUID(as_uuid=True), primary_key=True, server_default=sqlalchemy.text("uuid_generate_v4()"), blank=True, editable=False, ) but this returned the error NameError: name 'sqlalchemy' is not defined (despite sqlalchemy being imported and installed with Pip). Is there a clean/correct way of making use of this function in a Django model? -
Is there a way to set two variables as unique together?
I'm creating an application that i have username and nickname for the same person: username = models.CharField( max_length=40, unique=True, db_index=True) nickname = models.CharField(max_length=100, unique=True) But i need to define this two variables as unique like: If an user A has: username: bird nickname: dog and an user B try to make registration like: username: dog nickname: butterfly I will not accept because dog is already taken. Or if an user try to put nickname as same as username. I'm thinking to create a registration view to make this validation manually. But is there a way to make this in the declaration? -
Adding security questions to signup page created using django
I am creating a signup page using Django, I need to add some security questions so the user can choose which one they wanna use and save the answer of that question. What am I supposed to do? -
Django values() function. What are *fields?
As documentation says: values(*fields, **expressions) The values() method takes optional positional arguments, *fields, which specify field names to which the SELECT should be limited. If you specify the fields, each dictionary will contain only the field keys/values for the fields you specify. If you don’t specify the fields, each dictionary will contain a key and value for every field in the database table. But what is *fields is not clear to me. Supposing a model named MyModel with just three fields: id, name and phone. This works: values = MyModel.objects.all().values('id', 'name', 'phone') This doesn't work: def get_values(fields): return MyModel.objects.all().values(fields) fields = ['id', 'name', 'phone'] values = get_values(fields) Because it raises: AttributeError: 'list' object has no attribute 'split' But I don't understand why. I mean, it is clear that a list, tuple or set don't have a split method but, is not a list (a tuple, actually) what I am passing in the first example? The second code snippet fails even with a tuple or a set, and this is obvious, because they don't have a split method too. So what type am I passing in first example? There's something about python/django behavior that I'm not missing. Thank you. -
Circular imports django
I have wrote this code in my models.py file. As you see the code, I have a class called File and also I have imported in models.py the same class. Now it gives me this error while migration: Cannot import name "File" from 'uploadapp.models' I understand it's the error for circular (recursive) import. But how can I solve this? from django.db import models from .models import File class File(models.Model): file = models.FileField(blank=False, null=False) def __str__(self): return self.file.name -
Updating source of video tag with ajax
I have an html page where there is a calendar, a video tag and a button. When a user clicks on a button, based on the timestamp the path of the video file from Django is sent and is received by an ajax call. When the page is opened for the first time or is refreshed and the date and time is selected and then the button is pressed the video corresponding to that date and time gets displayed on the page and can be played. However when I change the date and time, the same video file which was opened previously gets displayed on the page, however the path of the video file which is being returned from the django is according to the new date and time. Kindly help me here. HTML code <div style="margin-left: 10%"> <button type="submit" class="btn btn-secondary btn-lg" id="recorded" name="btn_submit" value="Play Recorded Videos" onclick="record()" >Play Recorded Videos</button> </div> <div id="videoDiv" class="container" style="margin-left: 10%; margin-top: 1%; align-items: center; display: none "> <video id='storedVideoId' width='100%' controls > </video> <br><br> </div> Javascript code <script type="text/javascript"> var dateNow = new Date(); dateNow.setDate(dateNow.getDate()); var timer $(function () { $('#datetimepicker1').datetimepicker({ defaultDate:dateNow }); }); function getDataFromServer() { getVideoFile() } function getSelectedDate() { … -
How to manage static files in Python, which are in separate app in Django 2+?
Here is my project directory: So I want to create home.html file where to load style.css file. How I load style.css file in home.html file: {% load static %} <link rel="stylesheet" type="text/css" href="{% static 'style.css' %}"> Which returns me: <link rel="stylesheet" type="text/css" href="/static/style.css"> Which is not the right path. Based on documentation I tried with: {% load static %} <img src="{% static "my_app/example.jpg" %}" alt="My image"> in my case: {% load static %} <link rel="stylesheet" type="text/css" href="{% static 'core/style.css' %}"> But it returns me wrong path again: <link rel="stylesheet" type="text/css" href="/static/core/style.css"> Where am I wrong ? -
Accessing parent model instance within model admin to provide custom queryset
I want to provide a custom queryset within a model admin class that inherits from TabluarInline, but I want to provide this queryset by calling a method of current instance of the model object. I have two models. One for tracks belonging to an album, and one for the Album itself. Some tracks can be hidden and I have a method in Album to return only the visible tracks. class Track(models.Model): name = models.CharField() length = models.IntegerField() album = ForeignKey(Album) hidden = BooleanField() class Album(models.Model): name = models.CharField() def get_visible_tracks_queryset(self): return self.track_set.filter(hidden=False) And I have a tracks inline admin which is included on the django admin page for an album. I want to re-use the get_visible_tracks_queryset to define the queryset for this inline admin, I don't want to repeat the logic again. I can't figure out how to do it. I could do something like the following, however I'm using a simplified example here, I actually have more complex logic and I don't want to be repeating the logic in multiple places. class TracksInlineAdmin(admin.TabularInline): fields = ("name", "length") model = Track def get_queryset(self, request): qs = super(TracksInlineAdmin, self).get_queryset(request) return qs.filter(hidden=False) Ideally I could do something like: class TracksInlineAdmin(admin.TabularInline): fields = … -
return manytomany field by nested relationship, and update by id
I have two models MusicandMusicList(manytomanyfield), and I use ViewSet to generate api. I expected that it returns Music's detail(include music_name, music_id...) when I call such as http://127.0.0.1:8000/api/musiclist/7/(GET), that required nested relationships. however I also wanna to update MusicListwith music_id, it can be implemented by use serializers.PrimaryKeyRelatedField I tried to defined two fields to Specify separately write_only and read_only,but I don't think it's a good solution. models.py class MusicList(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name='user', related_name='musiclist') name = models.CharField('list_name', max_length=50, default='') music = models.ManyToManyField(Music) def __str__(self): return self.name serializers.py class MusicSerializer(serializers.ModelSerializer): class Meta: model = Music fields = '__all__' class MusicListSerializer(serializers.ModelSerializer): # music = MusicSerializer(many=True, required=False) music = serializers.PrimaryKeyRelatedField(many=True, queryset=Music.objects.all()) class Meta: model = MusicList fields = ['user', 'name', 'music'] validators = [ UniqueTogetherValidator( queryset=MusicList.objects.all(), fields=['user', 'name'] ) ] -
Wagtail Page get_url_parts() method is not being called
I have copied some of [this]https://stackoverflow.com/a/54561756/11225921 answer/code but the get_url_parts method is not being called at all. I am wondering if it has to do with the abstract mixin, or else I am not sure. The same method header works if I put it on my (main Page/HomePage) This is the abstract class BaseSection(models.Model): """ BaseSection abstract base class. All HomePage sections should inherit from this class. """ parent_page_types = ['HomePage'] subpage_types = [] content_panels = [] class Meta: abstract = True def get_url_parts(self, request=None, *args, **kwargs): """ Customising URL patterns for a page model http://docs.wagtail.io/en/latest/topics/pages.html#customising-url-patterns-for-a-page-model Rewrite page path to corresponding anchor of this section on the containing page. """ print("METHOD CALL") url_parts = super().get_url_parts(request=request) if url_parts is None: return None else: site_id, root_url, page_path = url_parts _cust_page_path = '#section-{}'.format(page_path.replace('/', '')) return (site_id, root_url, _cust_page_path) and this here is the Page (-mixin, correct?) class IntroductionSection(BaseSection, Page): template = 'sections/text_section.html' body = RichTextField() def get_context(self, request): print(type(self)) content_panels = BaseSection.content_panels + [ FieldPanel('title'), FieldPanel('body'), ] I use wagtail modeltranslation but that should not be the reason, because the method call works for the HomePage class HomePage(Page): parent_page_types = [ 'wagtailcore.Page', ] # The following page types (here named "sections") are standard … -
MySQL REGEXP query via Django doesn't return anything but queries in MySQL work just fine, any ideas?
I'm currently developing a website that visualizes the amount of occurrences a certain ngram has given a date range, similar to google's ngram viewer, but for my native language. My thesis adviser said we should implement a regex query that returns all the ngrams that fit the given regex. However, querying via Django gives me an empty result set, and running the query in MySQL workbench gives me the data I want. I've tried using both a raw query and Model.objects.filter as shown below. def regex(request, regexPattern): #TO MAKE WORK if(request.method == 'GET'): print(regexPattern) results = Ngram.objects.filter(ngram__regex = regexPattern) for x in results: print(x) sql = "SELECT ngram FROM ngram n WHERE n.ngram REGEXP %s AND n_number = %s" val = (regexPattern, "1") with connection.cursor() as cur: cur.execute(sql, val) myresult = cur.fetchall() data = [] #data["ngrams"] = regexPattern for x in myresult: print(x) The MySQL query is SELECT ngram FROM ngram WHERE ngram REGEXP 'du\w{0,5}' AND n_number = '1' Both for loops that print x from the resultSets from Ngram.objects.filter and the raw query print nothing, but if I run this query in my database I get a lot of rows. Here is a sample ngram ------ modumo dulay dumating … -
How I can Move Site-Packages from Virtualenv to my App folder in Django
I have some packages installed in my website, but i want to move 1 package from virtual env to Django app folder (Which i Created), I copied complete folder of package from virtual env to my App folder, but no changing showing, Please let me know the process, How i can do it. -
Django dynamic page generating
I'm learning Django, and doing a project for myself. Intro about the Project : it is a travel app, where user have to select their destinations. The destinations will be added by the admin/superuser from the Admin panel. Now I can dynamically add the Contents from the Admin panel. What I want : when a user will click on a particular destination, this should open the destination page. as the content is coming from a Database (that means if i have 1 rows in the DB it will show 1 destination). Now i would like to know how can I create webpages based on the contents that are available? Image of the code snippet of the destination in the "destinations.html", what should I add so that it will create a page when I add a new destination, as well as it will create a dynamic URL to that page. for eg. I have 1 destination, and when I click it it will open the page of the destination (That I can do by creating a new view object). But suppose I add a new destination, and it will create a Page for that 2nd destination. -
ImportError: No module named 'django' uWSGI Django Nginx Ubuntu 16.04 Python3.6
I've spent a day trying to figure this out. I'm running on Digital Ocean with Django, Python3.6, Nginx, Ubuntu 16.04, and uWSGI. Have had to install Python3.6 via deadsnakesppa and have a virtualenv which I created with mkvirtualenv --python=python3.6 myproject I am following this tutorial which I have followed before but when I try to run the below code to test the application server (not in virtualenv) uwsgi --http :8080 --home /home/user/Env/myproject --chdir /home/user/myproject/src/myproject -w myproject.wsgi I get this traceback *** Starting uWSGI 2.0.18 (64bit) on [Mon Aug 5 12:23:53 2019] *** compiled with version: 5.4.0 20160609 on 05 August 2019 11:53:48 os: Linux-4.4.0-157-generic #185-Ubuntu SMP Tue Jul 23 09:17:01 UTC 2019 nodename: myproject machine: x86_64 clock source: unix detected number of CPU cores: 1 current working directory: /home/user/myproject/src/myproject detected binary path: /usr/local/bin/uwsgi !!! no internal routing support, rebuild with pcre support !!! *** WARNING: you are running uWSGI without its master process manager *** your processes number limit is 3898 your memory page size is 4096 bytes detected max file descriptor number: 1024 lock engine: pthread robust mutexes thunder lock: disabled (you can enable it with --thunder-lock) uWSGI http bound on :8080 fd 4 spawned uWSGI http 1 (pid: … -
condition in html template
Hello I am working on the web app with Python Django and I am struggling to reate condition in my html template. I got table and I want to make the text bold in the cell if the text in the cell is equals to specified text. I tried this: <table> <tr> <td>{% if order.order_buffer %}{{ order.order_buffer }}{% else %}<b>{{ order.order_buffer }}</b>{% endif %}</td> </tr> </table> In this condition it goes straight to the else block. Any ideas? -
How and where should I store the conversion code for image files in Django?
I created a simple form in Django of which it contains only a single form input field i.e image field. My aim is to allow a user to upload an image file i.e JPEG, JPG, SVG, PNG. Once uploaded, I want to write some code that'll convert the image file to PNG and then store it in my database. How should I write this code and where do I write it? You can view my current code below. I'm a beginner in Django and could use some help. settings.py STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, "static"), ] MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') website/urls.py: from django.contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), path('', include('myapp.urls')), ] urlpatterns = urlpatterns + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) urlpatterns = urlpatterns + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) models.py from django.db import models class Image(models.Model): """Image upload model""" image = models.ImageField(upload_to = 'media', default = 'media/sample.png') created_date = models.DateTimeField(auto_now = True) def __str__(self): return str(self.id) forms.py from django import forms from myapp.models import Image class ImageForm(forms.ModelForm): """Image upload form""" class Meta: model = Image exclude = ('created_date',) views.py from django.shortcuts import render from django.db import … -
How to SQL code conversion to a single Django ORM query?
I'm trying to convert the following SQL query in to a single Django query in order to minimize number of executed sql queries, however I'm not able to do that except using a for-loop. I appreciate it if anyone could provide me the intended Django query SQL Query: select FUND_ID, REPORT_DATE, PURCHASE_NAV_PER_SHARE FROM FUNDS_HISTORY WHERE REPORT_DATE = ( SELECT Max(REPORT_DATE) FROM FUNDS_HISTORY fund_history where fund_history.FUND_ID = FUNDS_HISTORY.FUND_ID ) -
how to connect database programatically at runtime in #django framework
I have in my User Profile, one field to define the Database name, that user can connect. DATABASES = { 'app_data': { 'NAME': 'app_data', 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'USER': 'postgres_user', 'PASSWORD': 's3krit' }, 'DBNAME_1': { 'NAME': 'user_data', 'ENGINE': 'django.db.backends.mysql', 'USER': 'mysql_user', 'PASSWORD': 'priv4te' } } class UserProfile(models.Model): user = models.OneToOneField(User) dbname = models.CharField(u'Database name', max_length=100, null=True, blank=True) not connecting to 2 different database only creating in single database