Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to start google app engine on sympy-gamma
hello everyone, i am using windows-10 and i am completed all the process given by sympy-gamma document https://github.com/sympy/sympy_gamma/ . but at the end when i am configuration file for App Engine (needed to run the development web server): $ python deploy.py --generate-only --generate-test 1000 this given me output like. and run development web server and run this code will give me error: $ ../google_appengine/dev_appserver.py . error :- Error like this -
Django + JQuery - Append bars to table rows
I have table rows that look like this: {% for item in items %} <tr id="rows"></tr> {% endfor %} and bars that look like this: {% for item in items %} <div class='bar' id="bars"></div> {% endfor %} now I want to attach each bar to it's row, the first bar to the first row and so on... For a start, I tried using fragments but I haven't been successful yet... iBars = document.getElementById('bars'); var fragment = document.createDocumentFragment(); fragment.appendChild(iBars); rows = document.querySelectorAll('#rows').forEach(function (element, index) { rows.appendChild(fragment); }); Thank you for any help -
HOW TO ADD ONE MORE COLUMN IN django.contrib.auth.models from User in django rest framework
Actually i tried to authenticate my django project using JWT django.contrib.auth.models from User model and need to add one more column in user model but i cannot able to add one column don't no why? -
How to configure domain-based database filters?
Odoo has an option --dbfilter which selects database depending on domain, so the users can run different Odoo databases on different sub-domains. Let's say we have two subdomains: test1.example.com and test2.example.com. With simple configuration, Odoo can connect to test1 or test2 database. It is possible to handle it easily in Django? -
How to check this start_date>check_date in django ORM filter?
How to check this start_date>check_date in django ORM filter? check_date = request.GET.get('start_date') qs = AuditPlanning.objects.values('audit_opinion').annotate( count=Count('audit_opinion'), dcount=Count('audit_id', distinct=True)).filter(start_date__gte='check_date').order_by("count") here how can I check thestart_date with check_date. This method is not workingfilter(start_date__gte='check_date') filter(start_date__gte=check_date) also not working -
Running multiple celery instances in Production in same VM different virtual-envs
There have been similar questions. I have been running multiple production applications with Django Celery RabbitMQ, and so far so good. However now there's a customer on whose virtual machine we need to run three separate Django applications, and each of them has a Celery app. While running Celery as a stand-alone I had followed these docs. And they work like a charm. I am talking of /etc/init.d/celeryd option. The problem is the init.d scripts point to a script /etc/default and there is only one option to add a directory and other settings to point the right Django app. https://docs.celeryproject.org/en/latest/userguide/daemonizing.html#example-configuration However I am yet to see any docs, and what configs I will need to change if in the same VM, and for the same Rabbit-MQ Server we will need to make changes. In short, how do I run multiple Django Apps with celery and Rabbit MQ in a single machine. Apps are using different python VMs -
How to delay not exist task by celery?
I have two environments 1. webserver 2. celery worker webserver add jobs to celery message queue. but those env are separated, so can not import task function. how to call not exist task explicitly? ex) [X] task.delay() [O] add_jobs("task", *args) -
model forms were not generated automatically using django model forms
I'm creating Django forms using model forms because u I wanted the forms to be created automatically, but when I created this code the forms do not appear in the index.html page models.py from django.db import models class BaseCase(models.Model): base_case_name = models.CharField(primary_key=True, max_length=255) version = models.TextField(blank=True, null=True) default = models.TextField(blank=True, null=True) # This field type is a guess. class Meta: managed = False db_table = 'base_case' forms.py from django import forms from SFP.models import * class BaseCaseForm(forms.ModelForm): class Meta : model = BaseCase fields='__all__' views.py from django.shortcuts import render,redirect from .models import * from .forms import * def addbc(self, request): bcform=BaseCaseForm(request.POST) bcform.save() basecasename = bcform.cleaned_data['post'] version = bcform.cleaned_data['post'] default = bcform.cleaned_data['post'] bcform = BaseCaseForm() return redirect('index.html') args = {'bcform':bcform, 'basecasename': basecasename, 'version': version, 'default' :default} return render(request, 'index.html', args) index.html <!DOCTYPE html> <html> <head> <title>S&FP</title> </head> <body> <h1>Forms</h1> {% csrf_token %} {{ bcform }} <input type="submit" value="add"> </body> </html> I was expecting the form fields to be generated automatically but they don't appear! -
run sympy-gamma on localhost on windows 10
I am new to sympy and python. i have download sympy code from github and run on local-host. code can be run on localhost server. it can be display error. can any one help me? how to run that code on localhost. -
Why tasks do not start?
I write this celery worker -A proj -c 2 -l info And get following log: -------------- celery@proj v4.3.0 (rhubarb) --- * *** * -- Linux-4.15.0-66-generic-x86_64-with-Ubuntu-18.04-bionic 2019-11-07 10:19:11 - ** ---------- [config] - ** ---------- .> app: proj:0x7f1ed0b36b70 - ** ---------- .> transport: redis://localhost:6379/0 - ** ---------- .> results: redis://localhost:6379/0 - *** --- * --- .> concurrency: 2 (prefork) -- ******* ---- .> task events: OFF (enable -E to monitor tasks in this worker) --- ***** ----- -------------- [queues] .> celery exchange=celery(direct) key=celery [tasks] . app.tasks.one . app.tasks.two [2019-11-07 10:19:11,968: INFO/MainProcess] Connected to redis://localhost:6379/0 [2019-11-07 10:19:11,978: INFO/MainProcess] mingle: searching for neighbors [2019-11-07 10:19:12,983: INFO/MainProcess] mingle: all alone [2019-11-07 10:19:12,990: INFO/MainProcess] celery@proj ready. nginx, redis and gunicorn are runned. Django 2.2.6, celery 4.3.0 -
Customuser model doesn't return username
I have a customuser model with class customuser(AbstractUser): # additional fields def __str__(self): return self.username I have another model, that becomes the foreign key for this model class bfs_support_ticket_model(models.Model): ticket_created_by = models.ForeignKey(customuser, on_delete = models.CASCADE) Why doesn't Django renders username for the form, but render or returns username everywhere correctly class ticket_edit_form(ticket_create_form): # ticket_created_by = forms.CharField(widget=forms.TextInput(attrs={'class' : 'form-control', 'readonly' : True})) # does not work in this way def __init__(self, *args, **kwargs): super(ticket_edit_form,self).__init__(*args, **kwargs) # self.fields['ticket_created_by'].disabled = True self.fields['ticket_created_by'].widget = forms.TextInput(attrs={'class' : 'form-control', 'readonly' : True}) # doesnot work in this way too class Meta: model=bfs_support_ticket_model exclude=['ticket_last_updated_by'] When the form is rendered it just prints the customuser.id instead of customuser.username But when no form initialization is made, it return the customuser.username correctly i.e. when class ticket_edit_form(ticket_create_form): def __init__(self, *args, **kwargs): super(ticket_edit_form,self).__init__(*args, **kwargs) self.fields['ticket_created_by'].disabled = True # only this line present it renders customuser.username class Meta: model=bfs_support_ticket_model exclude=['ticket_last_updated_by'] Please help me, where I am going wrong -
pgAdmin4 is not launching fails after some loading?
I just installed postgresql in my windows 10 but it is not opening.It says Starting pgAdmin4 server.. for some time but disappears after sometime without any error or notification. -
How would i replicate this SQL query in Django Rest Framework using generics.ListAPIView and serializers.ModelSerializer
Cant actually find anything like what i am trying to do with wanting to use case statements and left joins using DRF Django Rest Framework, yes this could be done on the front end of the project i am working on but id rather not have to let the front end potentially sending 100s of requests when loading a product list for example. Nothing i can really add to this but i have tried many different ways of doing the below SELECT p.itemno, CASE WHEN cp.price IS NULL THEN p.HighSell ELSE cp.price END AS price FROM api_product AS p LEFT JOIN api_customerprices AS cp ON p.itemno = cp.itemno AND cp.customerno = 'Examplecust' WHERE p.FreeStock > 0 or restockDate > '1900-01-01' -
How do I remove 404 error from Django app?
I am trying to create a web app using Django framework. I followed the tutorial and did everything as per the tutorial. DJANGO_PROJECT: from django.contrib import admin from django.urls import include from django.conf.urls import url urlpatterns = [ url(r'^dellserver/', include('dellserver.urls')), url(r'^admin/', admin.site.urls), ] Settings.py: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'dellserver' ] dellserver\urls.py: from . import views from django.conf.urls import url urlpatterns = [ url(r'^dellserver/$', views.index, name="index") ] views.py: from . import views from django.conf.urls import url urlpatterns = [ url(r'^dellserver/$', views.index, name="index") ] Can anybody tell me what I am doing wrong? Why I a getting the ** Page not found (404) ** -
How to update exisiting date field in django using existing days field?
I want to update existing date field in django using existing days field in the same table. For example class Sample(models.Model): notify_status = models.BooleanField(default=0) next_date = models.DateField(blank=True, null=True) days = models.IntegerField(blank=True, null=True) Now I want to update days to next_date where next_date is less than todays date. I have tried this: import datetime from django.db.models import F Sample.objects.filter(next_date__lt=today).update(next_date=F('next_date')+datetime.timedelta(days=F('days'))) But its not working. -
DRF, Permissions and Tests: Receiving a 403 running tests, 200 OK in browser
I'm continuing my journey of testing my Django Rest Framework application as I add new views and more functionality. I must admit, at this stage, I'm finding testing harder than actually coding and building my app. I feel that there are far fewer resources on testing DRF available than there are resources talking about building a REST framework with DRF. C'est la vie, though, I soldier on. My issue that I'm currently facing is that I'm receiving a 403 error when testing one of my DRF ViewSets. I can confirm that the view, and its permissions work fine when using the browser or a regular python script to access the endpoint. Let's start with the model that is used in my ViewSet class QuizTracking(models.Model): case_attempt = models.ForeignKey(CaseAttempt, on_delete=models.CASCADE) user = models.ForeignKey(CustomUser, on_delete=models.CASCADE) answer = models.ForeignKey(Answer, on_delete=models.CASCADE) timestamp = models.DateTimeField(auto_now_add=True) Of note here is that there is a FK to a user. This is used when determining permissions. Here is my test function. I have not included code for the entire class for the sake of brevity. def test_question_retrieve(self): """ Check that quiz tracking/ID returns a 200 OK and the content is correct """ jim = User(username='jimmy', password='monkey123', email='jimmy@jim.com') jim.save() quiz_tracking … -
Django 2: how to run code once on app initialization?
Using Django 2.2, how can I run code once after the code has been loaded but before any request is handled? (Similar to code executed in Rails initializers). The use case is the following: I'd like to create a pool of connections to a database and assign it to a global variable in a module but preferably not during module import. (Initially following: https://stackoverflow.com/a/1117692/3837660, I was doing it at module import. But this is not optimal. Partly because I am facing a double import issue which I haven't solved yet and partly because I'd like to avoid creating a pool of connections at module import time.) It should be done exactly once (no matter if that module happens to be imported twice) but at the application start (not on the first request). -
Need help implementing django user defined table
I am developing a work management tool with Django. The tool is a general domain tool (any industry can use it), so there is no fixed table called "tasks" or "projects". I have a table called "tables" and another table called "table_details". In table, id will have the user-defined tables/entities and in table_details, i will have the structure of those tables. We need a 3rd table for the entities data. I am not getting how to achieve this.. I tried a lot to do it. I didn't find any tutorial for this to user Need to be able to dynamically add User-Defined fields of any data type. Can anyone help me with how i can solve this problem with Django? Thanks -
Django file upload returns None
I' trying to upload the image file using Django. I'm able to get the other form data but not the image file. request.FILES is blank. Below is my code. models.py class Module(models.Model): title = models.CharField(max_length = 50) slug = models.CharField(max_length = 50) description = models.TextField(max_length = 500) Forms.py class ModuleAddForm(forms.ModelForm): title = forms.CharField(max_length = 50, widget = forms.TextInput(attrs = {'class': 'form-control', 'placeholder': 'Title'} )) description = forms.CharField(max_length = 50, widget = forms.Textarea(attrs = {'class': 'form-control', 'placeholder': 'Description'} )) image = forms.FileField(widget=forms.ClearableFileInput(attrs={'multiple': True}), required=False) class Meta: model = Module fields = ['title', 'description', 'image'] Views.py form = ModuleAddForm(request.POST, request.FILES or None) if form.is_valid(): title = form.cleaned_data['title'] description = form.cleaned_data['description'] image = request.FILES['image] When I print request.FILES it returned blank and also when I tried to get it using Key it returned MultiValueDict error. But when I print request.POST, image was there. But it was of no use because an image wasn't uploaded. I'm using another model to store the image files of this model (Module) because it can contain multiple images. I've implemented the same logic in my other model and function. It's working there properly but not working here. Please help me with this. I'm using Django 2.2 -
How can I render a template and link to a particular section of the page?
In my question_detail_solution.html I have got this div: <div id='answer'></div> When I render the template in views.py I want something like an html anchor link to this div. What is the solution? This doesn't work: return render(request, 'tasks/question_detail_solution.html#answer', context) -
Is there a way to change language in django-mdeditor
I'm using django-mdeditor and it works fine just as i expect the only problem is the language. I believe its Chinese. How can I change it to English? -
Is Django framework a good fit for my use case?
I just came to learn about Django. I am going through the tutorials to learn some of its features but I wanted to get some basic idea of whether it can satisfy my use case. Problem Statement - We need to process a large number of files (say 2000) on a farm of linux machines to convert them from format A to format B. To do that, the user will take the following actions. Go to a website (landing page), and select a product. A form show up. Fill out the form and submit the files. At the backend (Linux), we will do some sanity checks on the files first. If the checks pass, the files will be "submitted" for processing, and we want to show a dynamic dashboard/status page of all the files. If the sanity checks fail, we want to send an email to the user that their submission failed. In order for the file processing to work, we need to maintain some configuration information in a DB (say MySQL or SQLite). We want the user to be able to add/modify/delete this information through the web interface using some sort of form or lightweight DB editor. We also … -
Save binary file through multipart curl
I want to save a file into binary field and some other details through DRF post request. Below is my code: class TestUpload(models.Model): id = models.AutoField(primary_key=True, editable=False) code = models.CharField(max_length=64) name = models.CharField(max_length=128) description = models.CharField(max_length=1024) data = models.BinaryField() class WidgetRoutingConfigViewSet(APIView): parser_classes = (MultiPartParser, FormParser,) def post(self, request, format=None): serializer = TestUploadSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response({'received data': request.data}) class TestUploadSerializer(serializers.ModelSerializer): class Meta: model = wm.TestUpload fields = [ 'code', 'name', 'description', 'data', ] Below is my postman curl code: curl -X POST \ http://localhost:80/testupload/ \ -H 'cache-control: no-cache' \ -H 'content-type: multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW' \ -H 'postman-token: 447d7078-faa5-37e9-30ae-5ade00e626e6' \ -F code=code \ -F name=name \ -F 'description=Description' \ -F data=@test.js With the above code the row in the database successfully added to the database but the data column is empty so the file is not inserted. What am i missing ? -
form Choice Field not updating immediately when the QuerySet is loaded form view
I have a ModelChoiceField in forms and I want to fill it based on customized QuerySet form View. The QuerySet will be added to ModelChoiceField if I refreshed the page how can I passes it immediately without refreshing? I tired to add the QuerySet in the forms.py class but I couldn't because I need the request.user and I can't get it form here. in forms.py I have this departments = forms.ModelChoiceField(queryset=Department.objects.none(), required=True, label=_('department')) and in View.py I did this department_ids.append(self.request.user.profile.department.key) for department in departments_list: if department.get_level_number > current_user_department.get_level_number: if department.is_inheritance(current_user_department): department_ids.append(department.key) department_ids = map(str, department_ids) department_queryset = departments_list.filter(key__in=department_ids) context['form'].base_fields['departments'].queryset = department_queryset return context I want the ModelChoiceField filled immediately without refreshing the page how can I do that? -
Change Function + ajax cant send value parameter from select box to django views (to make a dependent dropdown)
So i have 2 select box , first select box has a list of schema that the database has (i use oracle in DBEAVER) so the directory is like Oracle - databasename |Schema |A |B |C |D |E |Tables |POLLS_TableAll |DJANGO_ADMINUSER |etc |Views |Sequence |Types |etc |F |G polls_tableall has 2 attribute , table_id and table_name that we insert the data manually depends on list of schema and we put the table id increment tableid table_name 1 A 2 B 3 C 4 D 5 E 6 F 7 G 8 H so what i want is to make a dependent select box (dropdown list) the first dropdown has a list of table_name(which i already finish it) when i choose for example 'E' the second dropdown will show the POLLS_TableAll , Django_Adminuser , etc models.py import datetime from django.db import models from django.utils import timezone from django import forms class TableAll(models.Model): table_name = models.CharField(max_length=250) views.py from django.http import Http404 from django.shortcuts import get_object_or_404, render, redirect from django.template import loader from django.http import HttpResponse, HttpResponseRedirect from django.urls import reverse from django.views import generic from django.utils import timezone from django.contrib.auth import authenticate, login from django.contrib.auth.forms import UserCreationForm, AuthenticationForm from django.contrib import messages …