Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to embed images in JavaScript in Django
I creat web chess by Django and I use the code js from chessboardjs.com, I call .js in html in Django but, it don't call the image, what shoul I do? in my html: <!doctype html> <html> <head> <title>Chess</title> {% load staticfiles %} <link rel="stylesheet" href= "{% static "lib/chessboard-0.3.0.min.css" %}" type="text/css" /> <link rel="stylesheet" href="{% static "default.css" %}" type="text/css" /> </head> <body> <div id='gameBoard'></div> <script src="{% static "lib/chess.min.js" %}"></script> <script src="{% static "lib/chessboard-0.3.0.js" %}"></script> <script src="{% static "lib/jquery-1.11.1.js" %}"></script> <script src="{% static "default.js" %}"></script> </body> </html> my urls.py from django.conf.urls import url from django.contrib import admin from game.views import index from django.conf import settings from django.conf.urls.static import static urlpatterns = [ url(r'^$', index, name='homepage'), # The start point for index view url(r'^admin/', admin.site.urls), # etc :D ] if settings.DEBUG: urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) And I want to add channels to chess to that I can muiltiplayer. so what I'll do? Thanks very much -
Can't use the extended User model
I want to add a department field on my User model. I am using sql server as my db. I did the following in models.py class Employee(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, db_column='user') department = models.CharField(max_length=20, blank=True) class Meta: db_table = 'Employee' Then, using stored procedure I can fill all the fields of User easily, but when I want to fill the extra field department, I get the error RelatedObjectDoesNotExist at /fetched User has no employee. in views.py, where I retrieve the data from procedure: q = User(id=result_set[i][0], username=result_set[i][1], is_staff=False, first_name=result_set[i][4], last_name=result_set[i][3], email=result_set[i][8]) q.set_password(result_set[i][2]) q.employee.department = 'something' q.save() -
Compare url in django
I am trying to hide a content when a user is visiting his own profile. I tried the code below but it didn't work. What could be wrong. {% if request.path == "/account/users/{{ request.user.username }}/" %} {% else %} <img src="https://tyllplus.com/static/arrow-orange-down-vector-1.png" width="30" height="30"> {% endif %} -
Show url link only if condition meet using data in model - Django
I am using template to render basic html in django and specify link as below. <li><a href="{% url 'project:geometry' object.pk %}">Geometry</a></li> I want to hide this link based on condition using model information. Does anyone know how to do this? -
In Django Unite a Dynamic Amount of QuerySets
In my django-application I have a model with “UnitNodes”, “Persons”, and “PersonUnitRelations”. I wish to select all persons related to a list of units. I think it is most efficent if I can do things in only one DB query. So I cam up with some code similar to this: from models import Person from django.db.models import Q from models import UnitNode unitqs = UnitNode.objects.order_by('translations__title').filter(Q(translations__title__icontains="ceres")) unit = unitqs[0] qs = Person.objects.filter(personunitrelation__unit_node=unitqs[0]) for unit in unitqs: qs2 = Person.objects.filter(personunitrelation__unit_node=unit) qs = qs.union(qs2) This can create some large query and I wonder if there is some better way. -
Flow control and Failed: Database access not allowed, use the "django_db".... Error
I am running into some odd behavior with one of my celery tasks. def run_single_test(test_name_or_decorator): # get dict of test names, test paths test_dict = get_single_test_names() # check to see if test is in the dict if test_name_or_decorator not in test_dict: return 'The requested test could not be found.' for test_name, test_path in test_dict.items(): # if test name is valid run associated test if test_name == test_name_or_decorator: pytest.main(['-p', 'no:django','--json-report', test_path]) report = return_test_result_json('.report.json') report_id = str(uuid.uuid4()) test_run_data = TestResults.objects.create(name=report_id, data=report) return 'this is your test report: {}'.format(get_report(test_run_data.id)) This task will execute the pytest.main() command and run a test however when it goes to insert the .report.json into the Db with .create() I get the following error: Failed: Database access not allowed, use the "django_db" mark, or the "db" or "transactional_db" fixtures to enable it. Now if I take all the functionality within the for test_name.... block simplify things and move it into its own function everything works: def run_single_test_path(): test_path = 'test_folder/test_file.py::TestClass::specific_test_name' pytest.main(['-p', 'no:django','--json-report', test_path]) report = return_test_result_json('.report.json') report_id = str(uuid.uuid4()) test_run_data = TestResults.objects.create(name=report_id, data=report) return 'this is your test report: {}'.format(get_report(test_run_data.id)) I get the expected return: "this is your test report: {'created': datetime.datetime(2018, 9, 27, 15, 51, 59, 297991, … -
Non-existing template variables in Django
What is the best practice for either testing or making sure that all your template variables are in fact existing. Assume that we have the following template <html> <div>{{ existing_object.non_existing_attribute }}</div> </html> We have an existing object. So we can't really test the response context like in the following answer: Django Unitest Checking Value Of Template Variable There is string_if_invalid as described in the documentation. But that should only be used for debugging purposes. Any insight on how to best avoid this would be helpful! -
Best way to create one to one chat application using django
question is somehow a suggestion I saw many answers till now like using these in these answers which are well explained as well Can I use Socket.IO with Django? but I wanted to know is there a solution which I can use to create a chat between two specific users (like usually facebook or upwork etc) using Django . and what will be steps as I am new in Django. Any type of help would be highly appreciated . thanks -
Can i use django-cryptography with filter or get queries
we are trying to encrypt some fields in Django models, so that no one get data through database access (previously we used django.core.signing), but we need it in some queries where we need to query based on the value but we are getting this error *** django.core.exceptions.FieldError: Unsupported lookup'exact' for EncryptedCharField or join on the field not permitted. using Django 2.1 and django-cryptography 0.3 -
Test Python 3 Django app in Gitlab which calls out to Python 2 shell
I want to run my tests in a GitLab CI pipeline for a Python 3 Django app which occasionally calls out to run a Python 2 Django management script. How do set up both a Python 3 and Python 2 environment (both with Django and other packages) inside the one GitLab CI pipeline? Here is my current .gitlab-ci.yml which runs my tests in Python 2. test: script: - export I_AM_ON_GITLAB_CI=1 - apt-get update -qy - apt-get install -y python-dev python-pip - pip install -r requirements.txt - python manage.py test I want to upgrade this to allow running the tests in Python 3 with occasional calls (shelling out via proc = subp.Popen(cmd_array, stdout=tfil, stderr=subp.STDOUT) etc) to Python 2. Why do I need this? I need to run ALSM Python parsing that supports both python 2 and python 3 syntax, hence the need for two pythons in the one pipeline. See also my related question re hosting an app with both Python 3 and Python 2 avaiable in the one app, on Heroku. -
Django: initial value
I want to pass an initial value for the field to the unfilled form. If, on the other hand, a query (#Ref) arrives, it should prefill the values from the database. Why is not a value displayed in either case? views.py: def mieter(request,id): if request.method == 'POST': form = MieterForm(request.POST) if form.is_valid(): tmp = request.GET.get('wohnungsgruppenname') mieter = form.save() Wohnungseinheit = Wohnungseinheiten.objects.get(id=tmp) Wohnungseinheit.mieter.add(mieter) return render(request,'Immo/user/mieter.html',{'form':form}) else: if str(id).isdigit(): #Ref user = ImmoUser.objects.get(username=request.user.username) form = Mieter.objects.get(pk=id) return render(request,'Immo/user/mieter.html',{'form':form}) else: form = MieterForm(initial={'nameL':"initialValueHere",}) return render(request,'Immo/user/mieter.html',{'form':form}) models.py: class MieterForm(forms.ModelForm): nameL = forms.CharField(required=True,max_length=100) class Meta: model=Mieter fields = ("nameL",) mieter.html: <td><input class="form-control" id="{{ form.nameL.auto_id }}" name="nameL" value="{{ form.nameL.value }}" type="text"></td> -
Generate Trie in minimum time in django
I want to implement an auto complete search in ecommerce website. I found that trie will be a good choice to implement autocomplete but implementing trie poses some problems. 1.Trie uses a large amount of memory. 2.Trie takes a lot of time whenever it is generated. So I want to reduce the generating time of trie. Can cache or database help me to solve this? Is there any other data structure better than trie in the case of django? -
subclassing method showing error in the site-package in virtual environment
the init.py file shows error while running the file in importing subclassing method (env) devbase@bounce:~/env/local/lib/python2.7/site-packages/djorm_pgtrgm$ python __init__.py Traceback (most recent call last): File "__init__.py", line 4, in <module> from django.db.models.fields import Field, subclassing ImportError: cannot import name subclassing i am new to python so it would be helpful if someone can tell me about the error .............Thanks!!! from django.db import backends from django.db import connection from django.db import models from django.db.models.fields import Field, subclassing from django.db.models.query import QuerySet try: # Django 1.7 API for custom lookups from django.db.models import Lookup except NameError: from django.db.models.sql.constants import QUERY_TERMS from django.contrib.gis.db.models.sql.query import ALL_TERMS db_backends_allowed = ('postgresql', 'postgis') This is small part of code where i am importing the subclassing -
Translate javascript POST request into Axios (using Stripe)
I am working with Stripe (developing a payment system) on React.js and I am trying to translate the code below into React.js and use axios to create the endpoint that receives the POST request from the backend (Django): var handler = StripeCheckout.configure({ key: 'pk_test_zNq2YI8Spsyi81TknNujN36T', image: 'https://stripe.com/img/documentation/checkout/marketplace.png', locale: 'auto', token: function(token) { $.ajax({ type: "POST", url: 'http://localhost:8000/subscriptions/codes/pay/', data: {amount: amount, token: token}, }); } }); I am stuck on Step 4 from this link : Stripe for React, which explains the POST request but they are using Express, and I am using Django. -
Pycharm Docker Debugger Unable to Connect to DB in Docker
I am running a PyCharm 2018.2 version. I have my django code running on a docker instance and the Postgres running on another docker instance. My docker-compose.yml file is here version: "2.3" services: cv_db: container_name: cv_db image: postgres:10.3-alpine restart: always ports: - "9081:5432" environment: POSTGRES_USER: root POSTGRES_PASSWORD: **** POSTGRES_DB: cv volumes: - cv_db:/var/lib/postgresql/data expose: - "9081:5432" cv_redis: container_name: cv_redis image: redis:4.0.5-alpine restart: always ports: - "6379:6379" cv: container_name: cv image: cv restart: always depends_on: - cv_redis - cv_db ports: - "9080:9080" - "8080:8080" expose: - "9080" build: context: . args: http_proxy: https_proxy: no_proxy: TF_ANNOTATION: "no" USER: "django" DJANGO_CONFIGURATION: "production" WITH_TESTS: "no" environment: DJANGO_MODWSGI_EXTRA_ARGS: "" DJANGO_LOG_SERVER_URL: "" volumes: - cvat_data:/home/django/data - cvat_keys:/home/django/keys - cvat_logs:/home/django/logs - ./share:/home/django/share volumes: cv_db: cv_data: cv_keys: cv_logs: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', # 'HOST': 'cv_db', 'HOST': 'localhost', 'PORT': '9801', 'NAME': 'cv_dev', 'USER': 'root', 'PASSWORD': os.getenv('POSTGRES_PASSWORD', '****'), } I am using the django debugger: Edit Configuration Settings are below: Host: 0.0.0.0 Port: 9080 Run Browser: http://0.0.0.0:9080/ WHen I click on debug, I get the error saying it cant connect to Database: django.db.utils.OperationalError: could not connect to server: Connection refused Is the server running on host "localhost" (127.0.0.1) and accepting TCP/IP connections on port 9081? could not … -
iterating through an array twice within django templates
I have 2 lists of equal lengths in my views, that I have passed into templates using the zip function. For each element in the first list, a new row is created and I've used the split function to allocate the table cells. Each second list element is a collapsible row respective to a first list element. However, I'm struggling to split the second list in the same way as it is comprised of a list within a list. I want to split each second list element into the elements delimited by commas onto separate rows. Then use the split function again to put certain indexes into table cells. How should I go about this? {% for i,j in zip %} <tr> <td> <button type="button" id="chevron-{{ forloop.counter }}" class="fa fa-chevron-right rotate" data-toggle="collapse" data-target=#demo-{{ forloop.counter }} onclick="$('#chevron-{{ forloop.counter }}').toggleClass('fa-rotate-90')"> </button> </td> <td> {{ i.split.0 }} </td> <!-- sample word --> <td> {{ i.split.2 }}</td> <!-- ref word --> <td> {{ i.split.4 }}</td> <!-- cost --> <td> {{ i.split.3 }}</td> <!-- sum --> </tr> <tr> <td class="collapse" id="demo-{{ forloop.counter }}" colspan="5"> {% with j as list %} {% for item in list.split %} {% for x in item %} {{ x }} … -
How to run celery beat where each task has individual queues?
I have a Django project with multiple celery beat tasks , I have an issue when I have multiple celery beat tasks with individual queues so is there a possibility that i can run all these at a time , what is the best practice to run these? from __future__ import absolute_import, unicode_literals import os from celery import Celery from celery import Celery from celery.schedules import crontab os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'projectDemon.settings') app = Celery('projectDemon') app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks() @app.on_after_configure.connect def setup_periodic_tasks(sender, **kwargs): sender.add_periodic_task( crontab(minute=30, hour='7'), task1.s('Checking task1 !'), queue= 'task1', options={ 'queue': 'task1', 'routing_key': 'task1'} ) sender.add_periodic_task( crontab(minute=00, hour='6'), task2.s('Checking task2 !'), queue= 'task2', options={ 'queue': 'task2', 'routing_key': 'task2'} ) sender.add_periodic_task( crontab( minute='*/1', # run every minute ), task3.s('Checking task3 !'), queue= 'task3', options={ 'queue': 'task3', 'routing_key': 'task3'} ) @app.task def task1(arg): print(arg) @app.task def task2(arg): print(arg) @app.task def task3(arg): print(arg) -
AppRegistryNotReady("Apps aren't loaded yet.") django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet
I ran pip install djangoseo and then confirmed it with pip freeze Added rollyourown.seo to my INSTALLED_APPS setting Added "django.core.context_processors.request" to TEMPLATE_CONTEXT_PROCESSORS setting When I try to run python manage.py syncdb or run my application I get the following error AppRegistryNotReady("Apps aren't loaded yet.") django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. -
django restframework error while working on permission and authentication
Here is my models.py from __future__ import unicode_literals from django.db import models class Snippet(models.Model): created = models.DateTimeField(auto_now_add=True) title = models.CharField(max_length=100, blank=True, default='') code = models.TextField() linenos = models.BooleanField(default=False) owner = models.ForeignKey('auth.User', related_name='snippets', on_delete=models.CASCADE) highlighted = models.TextField() class Meta: ordering = ('created',) here is my serializers.py from .models import Snippet from django.contrib.auth.models import User class SnippetSerializer(serializers.ModelSerializer): owner = serializers.ReadOnlyField(source='owner.username') class Meta: model = Snippet fields = ('id', 'title', 'code', 'linenos') class UserSerializer(serializers.ModelSerializer): snippets = serializers.PrimaryKeyRelatedField(many=True, queryset=Snippet.objects.all()) class Meta: model = User fields = ('id', 'username', 'snippets') Here is my permissions.py from rest_framework import permissions class IsOwnerOrReadOnly(permissions.BasePermission): def has_object_permission(self, request, view, obj): if request.method in permissions.SAFE_METHODS: return True return obj.owner == request.user Here is my views.py from .models import Snippet from .serializers import SnippetSerializer, UserSerializer from rest_framework import generics from django.contrib.auth.models import User from rest_framework import permissions from .permissions import IsOwnerOrReadOnly class SnippetList(generics.ListCreateAPIView): queryset = Snippet.objects.all() serializer_class = SnippetSerializer permission_classes = (permissions.IsAuthenticatedOrReadOnly,) def perform_create(self, serializer): serializer.save(owner=self.request.user) class SnippetDetail(generics.RetrieveUpdateDestroyAPIView): queryset = Snippet.objects.all() serializer_class = SnippetSerializer permission_classes = (permissions.IsAuthenticatedOrReadOnly, IsOwnerOrReadOnly,) class UserList(generics.ListAPIView): queryset = User.objects.all() serializer_class = UserSerializer class UserDetail(generics.RetrieveAPIView): queryset = User.objects.all() serializer_class = UserSerializer Here is my urls.py from django.conf.urls import url, include from v2 import views urlpatterns = [ # url(r'^snippets/$', … -
Django filter LIKE Query in array ORM (icontains)
Views.py print(keywords_array) #['Donut', 'Pizza'] print(moods_array) #['Dating', 'Family'] items=ItemVariation.objects.filter(item__restaurant__id = i['restaurant']['id'],keyword__name__icontains=keywords_array,keyword__mood__moods__in=moods_array).select_related() I need to filter keyword__name__icontains but variable is an array ['Donut', 'Pizza'] . -
Deploy Python 3 Django app in Heroku which calls out to Python 2 shell
I want to run a Python 3 Django app in Heroku which calls out to Python 2 shell. The Python 2 environment also needs to have Django and several other packages installed. I can specify a python in the file runtime.txt but how do I get two Python environments in the one app. Why? I need to run ALSM Python parsing that supports both python 2 and python 3 syntax, hence then need for two pythons in the one app. -
Django shared template tag result
How can I define a global variable that is shared between all django apps or at least in admin views? I need to load some values in a dictionary just once at boot. Tried to define a template_tag: MyDict = { 'a':'gigi', 'b':'pippo', } def diz(): try: A = getfiltereddatafromdb('db') except: A={'err':'err'} return A MyDict=diz() @register.filter(name='test') def test(value): return MyDict[value] but the diz() always return 'err', where should i call diz() to make the data from db readable? I wan't to share in admin the result data of MyDict, if I insert diz() in the test() I get the data but each page load would take a long time to generate results. Django v. 1.11.14 -
.get + dict variable
I have a charge object with information in charge['metadata']['distinct_id']. There could be the case that it's not set, therefore I tried it that way which doesn't work charge.get(['metadata']['distinct_id'], None) Do you know how to do that the right way? -
Django: Require admin approval for patch and post
I'm trying to write my REST API in Django so that if someone makes a patch or post it will require someone with access to Django's admin panel to actually write the changes, but it'll be pending and visible to the admin till then, is this possible? Or do I have to create a model for the pending request then make the patch and post create new entities? -
django form field validation while using chained select
In my form i have a select box whose option changes according to selection of previous option.it is working fine. but when i try to use form validation it is not validated, instead shows 'Select a valid choice. is not one of the available choices' My form field, property_type = forms.ChoiceField(widget=forms.Select(attrs={'id':'prop_type', 'class':'form-control'})) and i am populating the options from the template using ajax call. I suspect that this is happening as i am not giving choices in my form, but cannot find a way to make it validate correctly.