Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: how to process flat queryset to nested dictionary?
I have a table with data looking like this: |Country|State|City |Street| |-------|-----|-----|------| | USA | AZ |city1| str1 | | USA | AZ |city1| str2 | | USA | AZ |city2| str1 | | USA | AZ |city2| str3 | | USA | MN |city3| str4 | | MEX | CH |city4| str5 | | MEX | CH |city4| str6 | What is a proper way to convert this into nested dictionary? I expect the result looking like this: nested_dict = { 'USA':{ 'AZ':{ 'city1':['str1','str2'], 'city2':['str1','str3'], }, 'MN':{ 'city3':['str3','str4'], }, }, 'MEX':{ 'CH':{ 'city4':['str5','str6'], }, }, } -
DRF serializer change field to read_only for some model instances
I have this model: class Task(MPTTModel, TimeStampedModel, StartFinishModel): name = models.CharField(max_length=256) parent = TreeForeignKey('self', on_delete=models.CASCADE, related_name='children') start_date = models.DateField() finish_date = models.DateField() @property def is_stage(self): if self.get_children(): return True return False And serializer: class TaskBaseSerializer(StartFinishSerializer, TimeStampedSerializer): class Meta: model = Task fields = ('id', 'name', 'parent', 'start_date', 'finish_date', 'is_stage') read_only_fields = ('is_stage') I want to make fields 'start_date' and 'finish_date' to become read_only if is_stage property is True. How can do that? -
Image processing on browser
I need to do some image processing on a browser where I upload images and with my python script it manipulate the images. At the end I just want to open a html page where I can simply use buttons there to process my python script. Please tell me how can I do it? I don't know much about web development. I don't need to host a website. I just want to do it locally so that if I give my files to anyone they can access it by just opening the html document. -
jQuery Tablesorter: sort and filter editable columns
I'm using the jQuery Tablesorter on a table with editable columns and tried to add the option to filter and sort them, but it fails to sort / filter them correctly. My table: <div class="table-responsive"> <table class="table table-bordered tablesort-proof-holder" id="proofTable"> <thead> <tr> <th>First Name</th> <th>Last Name</th> <th>Birthday</th> {% for category in categories %} {% if category.type == "BOOL" %} <th class="filter-select">{{ category }}</th> # this is a select with 3 choices {% else %} <th data-sorter="text">{{ category }}</th> # this is just text {% endif %} {% endfor %} </tr> </thead> <tbody> {% for person in people %} <tr> <td contenteditable="true" class="first_name" maxlength="50">{{ person.first_name }}</td> <td contenteditable="true" class="last_name" maxlength="50">{{ person.last_name }}</td> <td class="date_of_birth"><input type="text" value="{{ person.date_of_birth | date:"d.m.Y" }}" class="pseudo"></td> {% for item in person.item_set.all %} {% if item.category.type == 'TEXT' %} <td contenteditable="true" maxlength="50">{{ item }}</td> {% else %} <td data-category="{{ item.category.pk }}" data-category-type="{{ item.category.type }}"> <select class="pseudo"> <option value="Yes" selected>Yes</option> <option value="No">No</option> <option value="Unknown">Unknown</option> </select> </td> {% endif %} {% endfor %} </tr> {% endfor %} </tbody> </table> </div> My Tablesorter options are as followed (written in a coffee script): defaultOptions = dateFormat : "de", widgets: ['uitheme', 'filter', 'zebra'] theme: 'bootstrap' headerTemplate : '{content} {icon}', widgetOptions: { 'zebra': … -
Django display list data in json
I am using django to display pandas data frame into json format I am suing django panda I can convert my model into data frame but I don't know how to display whole frame in json format. I am using this code: def index(request): qs = DebtManagement1S.objects.all() df = qs.to_dataframe() resp_data = { 'x': list(df['sector']), 'z': df.to_json() } return JsonResponse(resp_data) And it is returning Json response In my x value I can get a result in list but when I am doing df.to_json() it is returning value in string and I can't use it as a reponse. I want to return a proper json response where I can access it. Is there any way to convert it into json format and return values like this: { sector: { "Internal Debt", "Central Loans" ... } } -
Unable to load style.css in django
I am not able to load the style.css on my web page. I've added the path for STATICFILES_DIRS like below, STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, "static"), ] STATIC_ROOT = os.path.join(os.path.dirname(BASE_DIR), "static_cdn") urls.py from django.conf import settings from django.conf.urls.static import static urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^', include('Salmon.urls')), ] if settings.DEBUG: urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) I ran the collectstatic and it collected the static files. When I do inspect element and open a link of style.css (http://127.0.0.1:8000/static/css/style.css), it gives not found message. I've added below in my index.html inside head tags, {% load staticfiles %} <link rel="stylesheet" href='{% static "css/style.css" %}'> I tried hard-coding the path to style.css but, no luck. I am missing something but can't seem to find it. Any help is really appreciated. -
check related object or not
I need to check my object related or not ORM postgresql/ I have two object ItemVariationValue and ItemVariation i need to check ItemVariationValue has relation with ItemVariation models.py class ItemVariation(models.Model): restaurant=models.ForeignKey(Restaurant,on_delete=models.CASCADE) items=models.ForeignKey(Item,on_delete=models.CASCADE) price=models.IntegerField(blank=True,null=True,default=0) item_code=models.CharField(max_length=500) keywords= models.ManyToManyField(Keyword) image=models.ImageField(upload_to='dishes/', blank=True, null=True) def __str__(self): return str(self.id) class ItemVariationValue(models.Model): items=models.ForeignKey(Item,on_delete=models.CASCADE) items_variation=models.ForeignKey(ItemVariation,on_delete=models.CASCADE) items_attribute=models.ForeignKey(ItemAttribute,on_delete=models.CASCADE) attribute_value=models.ForeignKey(AttributeValue,on_delete=models.CASCADE) def __str__(self): return str(self.id) -
How to hide Some API in django rest swagger?
I have to API end point one is product and another is price, i want to hide price API from swagger documentation.How will i achieve this? urlpatterns = [ url(r'^v1/products', include('project.products.v1.product_urls')), url(r'^v1/price', include('project.products.v1.price_urls')), ] -
Python Urllib download the video but it's not playable
I'm trying to download a video from s URL using Python's urllib package. My Python version is 3.6. Here's what I have tried: from views.py: def post(self, request, *args, **kwargs): serializer = VideoConverterSerializer(data=self.request.data) validation = serializer.is_valid() print(serializer.errors) if validation is True: url = request.POST.get('video_url') try: r = urllib.request.urlopen(url) with open('my_video.mp4', 'wb') as f: f.write(r.read()) rea_response = HttpResponse('my_video.mp4', content_type='video/mp4') rea_response['Content-Disposition'] = 'attachment; filename=my_video.mp4' return rea_response except TimeoutError: return HttpResponse(TimeoutError) else: return HttpResponse('Not a valid request') Here's an example URL I'm trying with: https://expirebox.com/files/386713962c5f8b7556bc77c4a6c2a576.mp4 The code above download the video file as my_video.mp4 but the video is not playable. The actual size of the video is ~5.9 MB but the size of download video is 11 KB only, so definitely something wrong with the downloaded video. What can be wrong here? help me, please! Thanks in advance! -
pysolr.SolrError: Solr responded with an error (HTTP 400): [Reason: undefined field django_ct]
I am trying to implement solr in django using haystack but facing an error search_indexes.py: import datetime from haystack import indexes from search.models import Note class NoteIndex(indexes.SearchIndex, indexes.Indexable): text = indexes.CharField(document=True, use_template=True) author = indexes.CharField(model_attr='user') pub_date = indexes.DateTimeField(model_attr='pub_date') def get_model(self): return Note def index_queryset(self, using=None): """Used when the entire index for model is updated.""" return self.get_model().objects.filter(pub_date__lte=datetime.datetime.now()) I did the following instructions: python manage.py build_solr_schema python manage.py rebuild_index The Error raise SolrError(error_message % (resp.status_code, solr_message)) pysolr.SolrError: Solr responded with an error (HTTP 400): [Reason: undefined field django_ct] -
How to set a value of a variable in queryset using(alias) in apiview class
I'm able to fetch the values from the table with in the database named '11' by using the below line of code. queryset = JobSeekers.objects.using("11").all() Now i would like to to pass the variable instead of static alias name. (here i'm using a global variable 'IdentificationNumber' which is getting set in AuthBackends.py) class GetCanidatesList(generics.ListAPIView): authorizedID = str(AuthBackends.IdentificationNumber) queryset = JobSeekers.objects.using(authorizedID).all() serializer_class = CandidatesSerializer name = 'candidates-list' Is that possible? Please help me. new to django Thanks in advance -
Django sessions not updating in templates
Django sessions are updating in my views but when i access them in templates, they are not. settings.py SESSION_SAVE_EVERY_REQUEST=True views.py request.session['login'] = 1 request.session.modified = True request.session.save() -
fcm_django library Issue
I am trying to integrate Google Firebase with Django App. The error what i am facing is the makemigrations file get created in site packages of fcm_django and while migrating the model is not created in DB. The Package I am using are below. Babel==2.6.0 cairocffi==0.8.1 CairoSVG==2.1.3 certifi==2018.1.18 cffi==1.11.5 chardet==3.0.4 cssselect2==0.2.1 defusedxml==0.5.0 Django==1.11 django-cors-headers==2.2.0 django-haystack==2.8.1 django-oauth-toolkit==1.0.0 django-oauth2-provider==0.2.6.1 django-phonenumber-field==2.0.1 django-rest-framework-docs==0.1.7 django-uuidfield==0.5.0 django-vinaigrette==1.1.1 djangorestframework==3.7.7 drfdocs==0.0.11 elasticsearch==6.3.0 fcm-django==0.2.19 future==0.16.0 gcloud==0.17.0 html5lib==1.0.1 httplib2==0.11.3 idna==2.6 ipaddress==1.0.22 jsonfield==2.0.2 jsonpickle==0.9.6 jws==0.1.3 oauth2client==3.0.0 oauthlib==2.0.7 pdfrw==0.4 phonenumbers==8.9.11 Pillow==5.1.0 pkg-resources==0.0.0 protobuf==3.6.1 psycopg2==2.7.4 psycopg2-binary==2.7.4 pyasn1==0.4.4 pyasn1-modules==0.2.2 pycparser==2.18 pyfcm==1.4.5 PyJWT==1.6.4 Pyphen==0.9.4 PySocks==1.6.8 python-dateutil==2.7.3 python-jwt==2.0.1 pytz==2018.3 requests==2.19.1 requests-toolbelt==0.7.0 rsa==4.0 sendotp==0.0.4 shortuuid==0.5.0 simplejson==3.16.0 six==1.11.0 tinycss2==0.6.1 twilio==6.16.3 urllib3==1.22 WeasyPrint==0.42.3 webencodings==0.5.1 Could Someone please let me know Why isn't this making the db structure? Thanks in advance -
Passing django array to example.js
I'm passing an array of files using this method How to pass an array in Django to a template and use it with JavaScript all is well if I have the script within the .html but if I want to have a separate example.js file, the only current way to get it working is to create the var in the html and then call it from example.js. In an effort to keep things tidy and in one place, I'd like to avoid doing this. Is it possible to put it into the example.js ? -
Django re-rendering part of a page after successful file upload
I have a technical question: I wrote a website with back end powered by Django, which does an asynchronous POST to the server with Ajax. The back end then checks the files and carries out a few other operations on them. Since this file transfer happens asynchronously, the web site is not re-rendered after a successful upload from the updated view on the back end. That gives me issues with providing the website user with any feedback about validity of some of the files they have uploaded (after analysis on the back end). Can someone point me in the right direction, of how situations like that are normally handled? Does Django have any functions which allow it to "respond" to the received request with some code to update the web page? Thank you. -
django-allauth; SocialApp matching query does not exist
django-allauth doesn't work. I saw this error before but django-allauth did work suddenly then. Here is setting I did on admin. Here is error log. ile "/mnt/c/Users//Desktop/Project//venv/lib/python3.6/site-packages/django/core/handlers/exception.py" in inner 34. response = get_response(request) File "/mnt/c/Users//Desktop/Project//venv/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response 126. response = self.process_exception_by_middleware(e, request) File "/mnt/c/Users//Desktop/Project//venv/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response 124. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/mnt/c/Users//Desktop/Project//venv/lib/python3.6/site-packages/allauth/socialaccount/providers/oauth2/views.py" in view 73. return self.dispatch(request, *args, **kwargs) File "/mnt/c/Users//Desktop/Project//venv/lib/python3.6/site-packages/allauth/socialaccount/providers/oauth2/views.py" in dispatch 96. app = provider.get_app(self.request) File "/mnt/c/Users//Desktop/Project//venv/lib/python3.6/site-packages/allauth/socialaccount/providers/base.py" in get_app 52. return SocialApp.objects.get_current(self.id, request) File "/mnt/c/Users//Desktop/Project//venv/lib/python3.6/site-packages/allauth/socialaccount/models.py" in get_current 34. provider=provider) File "/mnt/c/Users//Desktop/Project//venv/lib/python3.6/site-packages/django/db/models/manager.py" in manager_method 82. return getattr(self.get_queryset(), name)(*args, **kwargs) File "/mnt/c/Users//Desktop/Project//venv/lib/python3.6/site-packages/django/db/models/query.py" in get 399. self.model._meta.object_name Exception Type: DoesNotExist at /accounts/google/login/ Exception Value: SocialApp matching query does not exist. I can show local var if needed. What am I wrong with this? -
Django .save() doesn't take effect
Good morning everybody, I'm pretty new with Django, and I would like to get some help to understand why I need to rerun the Django server in order to watch the effect of .save() method. When I upload a new document, I created a code which let to see if the document is pretty new or not. For example, I set the expiration time 15 seconds after the upload part (15 seconds is just in order to make some tries, it will be 1 week in production). I have this class : class DocumentListView(CreateView): """ Render the home page """ template_name = 'documentList.html' form_class = DocumentForm def get_context_data(self, **kwargs): now = timezone.now() for document in Document.objects.all(): expiration_delay = document.creation_date + timedelta(seconds=15) if now > expiration_delay: document.new_document = False document.save() kwargs['document_list'] = Document.objects.all().order_by('publication__category__name') return super(HomeView, self).get_context_data(**kwargs) It works fine, but after 15 seconds, when I want to refresh my page, the flag is still there. It disappears only when I rerun my Django server. Do you have any idea about it? Thank you so much -
Remote connection blocked by remote server
I have a postgres database on server and I want to connect to it remotely with my local django application. I set: listen_addresses = '*' In postgres configuration file. Then do: host all all 0.0.0.0/0 md5 host all all ::/0 md5 In pg_hba.conf file And restarted postgres: sudo /etc/init.d/postgresql restart Set iptables: sudo iptables -A INPUT -p tcp -s [MY_IP_HERE] --sport 1024:65535 -d [MY_IP_HERE] --dport 5432 -m state --state NEW,ESTABLISHED -j ACCEPT sudo iptables -A OUTPUT -p tcp -s [MY_IP_HERE] --sport 5432 -d [MY_IP_HERE] --dport 1024:65535 -m state --state ESTABLISHED -j ACCEPT Netstat shows this: netstat -an | grep 5432 tcp 0 0 0.0.0.0:5432 0.0.0.0:* LISTEN tcp 0 0 127.0.0.1:5432 127.0.0.1:53796 ESTABLISHED tcp 0 4164416 127.0.0.1:5432 127.0.0.1:53540 ESTABLISHED tcp 0 0 127.0.0.1:5432 127.0.0.1:53798 ESTABLISHED tcp 0 0 127.0.0.1:53798 127.0.0.1:5432 ESTABLISHED tcp 0 3139216 127.0.0.1:5432 127.0.0.1:53488 ESTABLISHED tcp 0 0 127.0.0.1:53796 127.0.0.1:5432 ESTABLISHED tcp 0 0 127.0.0.1:5432 127.0.0.1:53530 ESTABLISHED tcp6 0 0 :::5432 :::* LISTEN tcp6 5511980 0 127.0.0.1:53488 127.0.0.1:5432 ESTABLISHED tcp6 4553483 0 127.0.0.1:53540 127.0.0.1:5432 ESTABLISHED tcp6 0 0 127.0.0.1:53530 127.0.0.1:5432 ESTABLISHED unix 2 [ ACC ] STREAM LISTENING 132643 /var/run/postgresql/.s.PGSQL.5432 But I still get an error: django.db.utils.OperationalError: could not connect to server: Connection refused Is the server running on … -
Is there any possible solution for getting more than one value inside function in django?
I am creating a blog application using Django and I am also very much new to django. This is the models I created class categories(models.Model): Title = models.CharField(max_length=40, default='GST') class Blog(models.Model): User = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE,null=True,blank=True) Date = models.DateTimeField(default=datetime.now) Blog_title = models.CharField(max_length=255) likes = models.ManyToManyField(settings.AUTH_USER_MODEL,related_name='likes',blank=True) Description = RichTextUploadingField(blank=True, null=True,config_name='special') Blog_image = models.ImageField(upload_to='blog_image', null=True, blank=True) Category = models.ForeignKey(categories,on_delete=models.CASCADE,related_name='Categories') I was wondering How to count the total no of blog present under a particular category? I want to track a specific count rate for all Categories... Done something like this in my model def categories_count(self): for a in categories.objects.all(): categories_count = Blog.objects.filter(Category__Title=a.Title).count() return categories_count But it is returning only one value...Can anyone suggest me with some suitable codes to resolve this... Thank you -
template doesn't exist using generic views
following the django tutorial I have changed to generic views and now my templates cannot be found anymore. error: TemplateDoesNotExist at /artdb/test2 it seems that it finds the right directory: Using engine django: django.template.loaders.filesystem.Loader: /Users/jonas/Dropbox/prog/web/django/winmalist/templates/artdb/test2 (Source does not exist) path to templates: /Users/jonas/Dropbox/prog/web/django/winmalist/templates/artdb: total used in directory 24 available 9223372036852770383 drwxr-xr-x@ 5 jonas staff 160 Sep 20 09:59 . drwxr-xr-x@ 4 jonas staff 128 Sep 9 15:50 .. -rw-r--r--@ 1 jonas staff 215 Sep 19 10:47 index.html -rw-r--r--@ 1 jonas staff 212 Sep 19 16:02 test1.html -rw-r--r--@ 1 jonas staff 253 Sep 20 09:59 test2.html urls.py: from django.urls import path from django.views.generic import TemplateView # from . import views app_name='artdb' urlpatterns = [ path('artdb',TemplateView.as_view(template_name='index')), path('test2',TemplateView.as_view(template_name='artdb/test2')), # path('', views.IndexView.as_view(), name='index'), # path('contract', views.contract, name='contract'), # path('<int:person_id>/test1/', views.test1, name='test1'), settings.py: ROOT_URLCONF = 'winmalist.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] -
Select correct postgresql version in travis build
I use TravisCi to build and test a Django based project. The build fails on db related errors that seems to be linked to the wrong postgres version being used. However, following Travis doc to set Postgres' version does not seem to work as expected. Here's my .travis.yml file: language: python python: - "3.6" addons: - postgresql: "9.6" before_install: - cd $TRAVIS_BUILD_DIR/src install: - npm install -g sass - make init before_script: - psql --version - psql -c 'SELECT version();' -U postgres - psql -c "CREATE USER aides WITH CREATEDB PASSWORD 'aides';" -U postgres script: - make checkstyle - make test Here's the build part that's bugging me: $ psql --version psql (PostgreSQL) 9.6.6 $ psql -c 'SELECT version();' -U postgres version -------------------------------------------------------------------------------------------------------------- PostgreSQL 9.2.24 on x86_64-unknown-linux-gnu, compiled by gcc (Ubuntu 4.8.4-2ubuntu1~14.04.3) 4.8.4, 64-bit (1 row) Unless I'm missing something obvious, it looks like the psql client connects to a server from a different pg version. How do I configure Travis to make sure Postgres server 9.6 is used? -
How can I add an Upload Image field to a Wagtail?
I want to make form from my page for blog, here's some of my code for my blog post class BlogPage(Page): date = models.DateField("Post date") intro = models.CharField(max_length=250) body = RichTextField(blank=True) and this for my image class NewsPageGalleryImage(Orderable): page = ParentalKey(BlogPage, on_delete=models.CASCADE, related_name='gallery_images') image = models.ForeignKey( 'wagtailimages.Image', on_delete=models.CASCADE, related_name='+' ) is it the best way to make front end form for this is by using modelform django and add the image form as inline form, or using form builder for that ? -
Django: 'Settings' object has no attribute
Depending on if I am in staging or production I either load settings.production or settings.staging. Now I want to check if CROSS_SUBDOMAIN_COOKIE is set, but I always receive 'Settings' object has no attribute 'CROSS_SUBDOMAIN_COOKIE'. This only happens in production, as my settings.staging is not loaded there. In .staging I wrote CROSS_SUBDOMAIN_COOKIE = True from django.conf import settings def mixpanel_id(self): if settings.CROSS_SUBDOMAIN_COOKIE: cross_subdomain_cookie = True else: cross_subdomain_cookie = False -
DRF Workflow Approach
I'm building a business application which will support multiple Loan products, for eg HomeLoan, CarLoan, PersonalLoan, EcommerceLoan. The major steps involved are 1) Onboarding (Generating Lead) 2) User Info (and Verification) - 3) Loan Info (Credibility) 4) Disbursement An example of the business flow is 1) Customer comes on-board, registers his mobile number, verifies it with OTP, 2) fills his personal information (validate it), 3) provides the loan amount 4) check loan credibility 5) Allocate funds (after XYZ validations) 6) Provide Bank Account details 7) Verify Bank Account (only after you have abc information) 8) Do eKYC 9) Disburse Now, I'm building the same using Django DRF Rest-ful APIs. However, there's a concern. In another product of ours, the flow can be different. Step 4 and step 6 can be interchanged, but step 7need to be done at the same position. Basically, I should have the flexibilty to reshuffle the activities (nodes) As of right now, the APIs written (although modular)is specific for only 1 product. How can I use DRF as a workflow approach? or use any library on top of DRF that can govern the flow. -
Convert SQL query to django orm
I want this query to convert to orm in django Select t1.field1,t1.field2,t2.field1,t2.field2 from table1 as t1 inner join table 2 as t2 on t2.field3=t1.field3 and t2.field4=t1.field4 where emp_id=5 and Case when table1.some_id>3 THEN (table1.field1,table1.field2) in (select field1,field2 from table3 where user_id=2) else 1 end. Note: field4 is a foreign key representing 4th table in both table1 and table2.