Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Python 'call_command' mock is used in other tests as well
Using Django 1.10 and python 3.5.1. I'm trying to mock 'call_command' function to throw an exception. The problem is that seems like the moment it gets the 'side_effect' function - it keeps to it also for other tests. What am I doing wrong or how can I 'revert' the side_effect from that function? In this example, after running one of the tests, all other tests that run afterwards will throw the same exception even if it's not supposed to throw exception in that test. def test_run_migrations_raise_exception(self): with mock.patch('django.core.management.call_command', return_value=None, side_effect=Exception('e message')): self.check_migrations_called(MigrationTracker.objects.all(), data_migrations_settings_in_db) call_command('run_data_migrations') self.check_migrations_called(MigrationTracker.objects.all(), data_migrations_settings_in_db) def test_run_migrations_raise_flow_exception(self): with mock.patch('django.core.management.call_command', return_value=None, side_effect=FlowException(500, 'fe message', {'a': 1})): self.check_migrations_called(MigrationTracker.objects.all(), data_migrations_settings_in_db) call_command('run_data_migrations') self.check_migrations_called(MigrationTracker.objects.all(), data_migrations_settings_in_db) -
Django annotate min and max of filtered foreign key
class Price(models.model): value = models.DecimalField(...) stock = models.ForeignKey("Stock", related_name='prices') class Stock(models.model): current_evlauation = models.ForeignKey('Price') last_hour_evlauation = models.ForeignKey('Price') In Django 1.11.13 with mysql as database, i want to optimize the following lines of code: last_hour = datetime.datetime.now() - datetime.timedelta(hours=2) stock_list = Stock.objects.all() for stock in stock_list: stock.last_hour_evaluation = stock.prices.filter(date__gte=last_hour).earliest('date') stock.current_evaluation = stock.prices.latest('date') stock.save() stock_deltas = list(Stock.objects.annotate(delta=F('current_evaluation__value)-F('last_hour_evaluation__value')).values_list('delta', flat=True)) in something like: stock_deltas = list(Stock.objects\ .annotate(current_eval=..., last_eval=...)\ .annotate(delta=F('current_eval') -F('last_hour_eval'))\ .values_list('delta', flat=True)) Is it possible to do such thing? If not, how can i write the first chunk of code, using the least amount of querys? -
Read-only field with pre-populated data in django form
I have following snippets, # models.py class Test(models.Model): username = models.CharField(max_length=100) email = models.EmailField() # forms.py class TestForm(forms.ModelForm): username = forms.CharField() email = forms.EmailField() class Meta: model = Test fields = ('username', 'email') # views.py def test(request): email = "example@example.com" """ How to pass and show the 'email' in django form/template? """ if request.method == 'POST': form = TestForm(request.POST) if form.is_valid(): form.save() return redirect('home') else: form = TestForm() return render(request, 'test.html', {"form": form}) How can I show and re-use the value of email variable (ie,example@example.com) in Django form/template as a read-only field? -
Is it a good idea to build progressive web app with Angular and Django?
I’m currently planning the development of my own application in order to increase my knowledges in web development. I’ve been coding desktop & mobile applications for more than 5 years so I’ve wide knowledge in C++, Objective-c, Swift, and Python also for some little backend projects. Now I would like to create an application available on the web and mobiles (iOs and Android). The purpose of this one will be like Expedia. The user write what he want, the application gives him it at the best price. My mantra has always been "Go to native", but since I will be alone and need to do a prototype quickly I was thinking to do a Progressive Web App (PWA). Unfortunately I don’t have knowledge in this field and I would like to get some information about it. 1°) Is a PWA a good bet? I read that a lot of big company are doing this. 2°) Which technologies should I use? From what I understand so far, Angular for the front-end and Django for the backend will work well. But am I missing something else? 3°) Should I consider services like Wordpress or AWS? -
Loading different models as inital for different steps in a formwizard
views.py def get_form_initial(self, step): if 'pk' in self.kwargs: return {} return self.initial_dict.get(step, {}) def get_form_instance(self, step): if not self.instance_dict: if 'pk' in self.kwargs: pk = self.kwargs['pk'] resume = Resume.objects.get(id=pk) return resume return None Hi! I have a form wizard that works with different models for every step. The model in each step after the first step has a ForeignKey relationship to the first step model. How can I load the different model instances as initial in the steps after the first step? Do I continue placing the logic in get_form_instance? I am trying to use the same wizard as "edit" forms. Thanks in advance! -
Can requests.post method be used in django get fucntion?
I am parsing an url and getting the values from it and want to send it to an API via post method. As default django function is get method can i use request.post method there? def paypal_return(request): token = '' current_url = request.build_absolute_uri() query_list = parse_qs(urlparse(current_url).query) print(request.GET.get('token', '')) if 'token' in query_list: token = query_list['token'][0] print(token) else: pass config = GetConfig().config(request) API_KEY = config['API_KEY'] API_URL = config['API_URL'] parameters = {'authToken': API_KEY,, 'token': token} url = '{}{}'.format(API_URL, '/payment') r = requests.post(url=url, params=parameters) return Httpresponse(r) -
Instalation problem when doing python manage.py migrate django_cron
I need to use Cron to send automatic emails through Django. I was following the tutorial in the Cron documentation: https://django-cron.readthedocs.io/en/latest/installation.html However, after running the code python manage.py migrate django_cron I got the error: ModuleNotFoundError: No module named 'my_app.cron' I have followed everything in the installation tutorial. Does anyone know what is wrong in my code? -
ElasticSearch : Index a document in my django web application
I'm trying to use for the first time ElasticSearch in my web application and I have difficulties with my ES indexation. The process is : When I add a document with upload field, the document is indexed by ES I have a function which let to define a new document title I have to reindex this document with new title in order to appear in ES list of documents I have some issues with this last part and I would like to know if you could help me. This is my code : es4omcl.py class EdqmES(object): host = 'localhost' port = 9200 es = None def __init__(self, *args, **kwargs): self.host = kwargs.pop('host', self.host) self.port = kwargs.pop('port', self.port) # Connect to ElasticSearch server self.es = Elasticsearch([{ 'host': self.host, 'port': self.port }]) def __str__(self): return self.host + ':' + self.port @staticmethod def file_encode(filename): with open(filename, "rb") as f: return b64encode(f.read()).decode('utf-8') def index_manage_document(self, doc, doc_id, doc_file, doc_title, bulk=False): filename = doc try: data = self.file_encode(filename) except IOError: data = '' print('ERROR with ' + filename) item_body = { '_id': doc_id, 'data': data, 'relative_path': str(doc_file), 'title': doc_title, } print(doc_id, doc_file, doc_title) if bulk: return item_body result1 = self.es.index( index='omcl', doc_type='annual-report', id=doc_id, pipeline='attachment', body=item_body, request_timeout=60 … -
Django progress bar for registration
Guys I am currently doing registration for courses and each course has 12 place here the image when users register for any course it should be counted my views.py file def register_course(request): if request.method == 'POST': form = UserRegisterForCourse(request.POST) if form.is_valid(): form.save() select_course = form.cleaned_data.get('select_course') messages.success(request, f'You have been successfully registered for {select_course}') return redirect('blog-home') else: form = UserRegisterForCourse() return render(request, 'blog/register_course.html', {'form':form}) models.py class RegisterForCourse(models.Model): name = models.CharField(max_length=50) COURSE_CHOICES = ( ('Python', 'Python'), ('Java', 'Java'), ('JavaScript', 'JavaScript'), ('C#', 'C#'), ('C++', 'C++'), ('Web', 'Web'), ) select_course = models.CharField(max_length=10, choices=COURSE_CHOICES) phone = models.CharField(max_length=13) def __str__(self): return self.select_course and the template file <div class="content-section"> <h3>Register for courses</h3> <p class='text-muted'>Very few places left</p> <ul class="list-group"> <li class="list-group-item list-group-item-light">Python <div class="float-right"> <div class="my-progress" data-count="2"><div></div></div> <span>2</span>/12 </div> </li> <li class="list-group-item list-group-item-light">Java <div class="float-right"> <div class="my-progress" data-count="12"><div></div></div> <span>5</span>/12 </div> </li> <li class="list-group-item list-group-item-light">JavaScript <div class="float-right"> <div class="my-progress" data-count="7"><div></div></div> <span>7</span>/12 </div> </li> <li class="list-group-item list-group-item-light">C# <div class="float-right"> <div class="my-progress" data-count="8"><div></div></div> <span>8</span>/12 </div> </li> <li class="list-group-item list-group-item-light">C++ <div class="float-right"> <div class="my-progress" data-count="8"><div></div></div> <span>8</span>/12 </div> </li> <li class="list-group-item list-group-item-light">Web <div class="float-right"> <div class="my-progress" data-count="8"><div></div></div> <span>8</span>/12 </div> </li> </ul> </div> I cannot do this proccess can you help me please? Now i am using sqlite database I have not added … -
How to know if a submit button clicked on a form with get method when exists another form in the template?
In my base template I want to have a search text box with a submit button on the top of every template. My button name is 'searchbutton' I put it in a form with get method I want to use this for all views in my application I have a view with 2 more forms , one of theese has pagination with page buttons I tried: if ('searchbutton') in request.GET: but this is true even user change pages on pagination. How can I know when user clicked the search button to filter rows as I want? Thanks in advanced Kostas -
Django: Display images from dictionary
I have a dictionary in views.py which contains track_id and image_path. For each track_id there could be one or more image_path, hence it is a dictionary where values are passed as the list. Example representation: {0: ['1.jpg', '2.jpg'], 1: ['3.jpg'], 2: ['4.jpg', '5.jpg', '6.jpg']} For each track_id I want to dedicate one space on the webpage in a div and it should loop through each image in a set timer of say 1 or 2 seconds on hover. How can I achieve this? -
How to solve the URL decoding problem in Django and nginx
My web app is deployed using nginx. I have view like below for the url /incoming/. def incoming_view(request): incoming = request.GET["incoming"] user = request.GET["user"] ... When I hit my url /incoming/?incoming=hello&user=nkishore I am getting the response I need. but when I call this url using requests module with below code I am getting an error. r = requests.get('http://localhost/incoming/?incoming=%s&user=%s'%("hello", "nkishore')) print r.json() I have checked the nginx logs and the request I got was /incoming/?incoming=hiu0026user=nkishoreu so in my view request.GET["user"] is failing to get user. I am not getting what I am missing here, is it a problem with nginx or any other way to call in requests. -
How to reference user account in FreeIPA database to user account in Web app database
My company has decided to use FreeIPA in order to make available Single Sign On feature for our employees. I am not familiar at all with Kerberos/LDAP and similar because i have never used those technologies before. We have 70 users - they have Windows OS machines and SSO should be used for several Python (Django) web apps, WordPress web sites and possibly for Roundcube web email and OpenVPN access. They don't have access to web servers at all so SSH accounts are not important for this story. Our python web app has database table with users' data which is in relation with some other tables and it is very important for us to have every single user added to those tables (via our web app interface) because otherwise our app will not work properly. Having that in mind, i would like to know if there is a way somehow to reference user from FreeIPA's database to our web app's and wordpress' databases, example below: Not every user has access to every web app and not every user has the same privileges in those apps. We have already defined user privileges in every web app separately and everything works perfect, … -
Django graphql graphene removing redundant queries from return value
The last few days I have read up on so much graphql that I can't see the trees from the forest anymore. The results that this person got in the beginning is almost exactly what I want (his problem, not his solution), but it seems that a lot of the code is deprecated and I can't seem to get it working: link I have a bunch of containers that I return. All the containers have the amounts for every day in them. I only want to return the amounts of a certain day. At the moment, I do return these results (day), but all the other results (days) also return with a Null value. Current behavior: { "data": { "listProductcontainers": [ { "id": "1", "productid": { "productid": "CBG2", "processedstockamountsSet": [ { "timeStampID": { "id": "2" }, "id": "77745", "prodName": { "productid": "CBG2" } }, { "timeStampID": null, <-------- "id": "89645", "prodName": { "productid": "CBG2" } }, { "timeStampID": null, <-------- "id": "89848", "prodName": { "productid": "CBG2" } }, // ... Requested behavior: (All values with 'Null' should not return) { "data": { "listProductcontainers": [ { "id": "1", "productid": { "productid": "CBG2", "processedstockamountsSet": [ { "timeStampID": { "id": "2" } My … -
raise TemplateDoesNotExist(template_name, chain=chain)
Traceback (most recent call last): .... raise TemplateDoesNotExist(template_name, chain=chain) django.template.exceptions.TemplateDoesNotExist: None Django project. settings.py TEMPLATES = [ { ... 'DIRS': [ os.path.join(BASE_DIR, 'templates')],}, ...] path in project tree: blog/template/blog (here all .html files) blog/views.py from django.views.generic import View from django.shortcuts import render from django.shortcuts import get_object_or_404 from .models import Post, Tag from .utils import ObjectDetailMixin def posts_list(request): posts = Post.objects.all() return render(request, "blog/index.html", context={'posts':posts}) class PostDetail(ObjectDetailMixin, View): model = Post tamplate = 'blog/post_detail.html' class TagDetail(ObjectDetailMixin, View): model = Tag template = 'blog/tag_detail.html' def tags_list(request): tags = Tag.objects.all() return render(request,'blog/tags_list.html', context={'tags': tags}) blog/utils.py from django.shortcuts import render from django.shortcuts import get_object_or_404 from .models import * class ObjectDetailMixin: model = None template = None def get(self, request, slug): obj = get_object_or_404(self.model, slug__iexact=slug) return render(request, self.template, context={self.model.__name__.lower():obj}) urls.py from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('blog/', include('blog.urls')), ] blog/urls.py from django.urls import path from .views import * urlpatterns = [ path('', posts_list, name='posts_list_url'), path('post/<str:slug>/', PostDetail.as_view(), name='post_detail_url'), path('tags/', tags_list, name='tags_list_url'), path('tag/<str:slug>', TagDetail.as_view(), name='tag_detail_url') ] blog/models.py from django.db import models from django.shortcuts import reverse # Create your models here. class Post(models.Model): title = models.CharField(max_length=150, db_index=True) slug = models.SlugField(max_length=150, unique=True) body = models.TextField(blank=True) tags = models.ManyToManyField('Tag',blank=True,related_name='posts') date_pub = models.DateTimeField(auto_now_add=True) … -
How to protect my .pyc files wont get extract out from docker
We have built the Django application dockerized till now there was no issue since we were hosting solution for a client, but now we also need to support in-house deployment which means my docker will be installed at the client machine. I see from the root access I can copy the files inside the docker. How we can save the copy issue from inside docker. How to add such security in my docker? Please suggest. -
Django read and wright from multiple databases
Hello guys I'm developing a web app in django and I'm using the postgresql database. I must be able also to grab some data from another app which uses a sqlserver database. The tables that I'm trying to get have lots of data so maybe it is not wise to use a direct link. Which is the best approach regarding this issue? Can I use a sql-odbc connection to get the data, also how can I populate the tables lets say I create a local table and migrate data from sql to postgresql schedualy. Would like to understand how you dealt with this issue and your experiences. Thank you! -
Django Rest. Ordering by calculated model field
I stuck with ordering on calculated field. Let's say my model looks like: class Foo(models.Model): fieldA = models.CharField() fieldB = models.CharField() @property def calculatedField(self): return someFunc(fieldA) Now I wan't my ViewSet to be able to apply ordering to calculatedField, so I have following code in there: class SomeViewSet(mixins.ListModelMixin, viewsets.GenericViewSet): ... ordering_fields = ('calculatedField',) ... But when I try to apply ordering using query parameters like Method GET /someEndpoint/?ordering=calculatedField I get the following error Cannot resolve keyword 'calculatedField' into field. Choices are: ... Is there a way to apply ordering to calculatedField? Thanks -
Decrease django's CPU Elapsed time from 31353.191 msec
According to the django-debug-toolbar my CPU Time is around 31000ms (on average). This is true for my own pages as well as for the admin. Here is the breakdown when loading http://127.0.0.1:8000/admin/: Resource usage User CPU time 500.219 msec System CPU time 57.526 msec Total CPU time 557.745 msec Elapsed time 30236.380 msec Context switches 11 voluntary, 1345 involuntary Browser timing (Timing attribute / Milliseconds since navigation start (+length)) domainLookup 2 (+0) connect 2 (+0) request 7 (+30259) response 30263 (+3) domLoading 30279 (+1737) domInteractive 31154 domContentLoadedEvent 31155 (+127) loadEvent 32016 (+10) As far as I understand the "request" step [7 (+30259)] is the biggest bottleneck here. But what does that tell me? The request panel just shows some variables, and no GET nor POST data. The same code works fine hosted on pythonanywhere, locally I am running a MacBook Air (i5, 1.3 Ghz, 8GB RAM). The performance hasn't been this poor all the time. IIRC it happened "over night". One day I started the dev server and it was slow. Didn't change anything in the code or DB. Is it right to assume that it could be an issue with my local machine? EDIT: I tried running ./manage.py runserver … -
How to save data into nested serializers that containing foreign key fields?
How can I post data into different models that contains foreign key fields using nested serializers? -
Exclude swagger docs for specific HTTP methods
I use drf-yasg to generate swagger docs for my Django REST API. I have a couple of endpoints, items/ with GET, POST and DELETE methods; and items/<uuid:itemID>uuid:itemID<uuid:itemID> with only DELETE method. However, the generated swagger docs include erroneously also GET and POST for the latter endpoint. This is a snippet of what I have in urls.py: urlpatters = [ url(r'^items/$', views.ItemViewSet.as_view()), path('items/<uuid:itemID>', views.ItemViewSet.as_view()), ] views.py contains something like: class ItemViewSet(mixins.DestroyModelMixin, GenericAPIView): def get(self, request): # ... return Response(HTTP_200_OK) def post(self, request): # ... return Response(status=status.HTTP_201_CREATED) def delete(self, request, itemID): # ... return Response(status=status.HTTP_204_NO_CONTENT) def delete(self, request): # ... return Response(status=status.HTTP_204_NO_CONTENT) How can I exclude GET and POST from items/<uuid:itemID> documentation? I have read through https://github.com/axnsan12/drf-yasg/blob/master/docs/custom_spec.rst and Exclude URLs from Django REST Swagger but haven't found a working solution yet. -
How can I prefetch related objects in Django?
Assuming I have the following model with related methods: class Turbine(models.Model): ... pass def relContracts(self): contracts = self.contracted_turbines.all() return contracts class Contract(models.Model): turbines = models.ManyToManyField(Turbine,related_name='contracted_turbines') def _contracted_windfarm_name(self): windfarms = self.turbines.order_by().values_list("wind_farm__name", flat=True).distinct().select_related if len(windfarms) == 1: return windfarms[0] else: return ", ".join([str(x) for x in windfarms]) contracted_windfarm_name = property(_contracted_windfarm_name) def _turbine_age(self): try: first_commisioning = self.turbines.all().aggregate(first=Min('commisioning'))['first'] try: start = self.start_operation.year except: start = datetime.now().year age = start - first_commisioning.year if age < 0: age = 0 except: age = 'not defined' return age turbine_age = property(_turbine_age) Django-debug-toolbar tells me, that the functions "_contracted_windfarm_name" and "_turbine_age" result in database duplicates for each contract. My contracts queryset is received by the following get_queryset method where I already prefetched 'turbines' for other methods succesfully: def get_queryset(self, **kwargs): qs = super(ContractTableView, self).get_queryset().filter(active=True).prefetch_related('turbines', 'turbines__wind_farm') self.filter = self.filter_class(self.request.GET, queryset=qs) return self.filter.qs I tried prefetching 'turbines__contracted_turbines' without being able to reduce the number of duplicates. Where am I mistaking? How can I prefetch the associated contracts of a turbine? -
Use the CYCLE postgres sequence property in DJANGO auto generated ids
I often get the error: error: nextval: reached maximum value of sequence "my_id_seq" in django autogenerated ids. Postgres is able to easily deal with this using the CYCLE attribute of sequences. My current solution is to do this manually with: ALTER SEQUENCE my_id_seq RESTART WITH 1; or using a custom migration. Is there a clean django way to do this? -
Paypal IPN notify_url not called in django project
Everything is working apart from notify url receiver call back is not working Following are the codes in my views.py def view_that_asks_for_money(request): # generating invoice id total_invoices = 0 invoices_of_user = Invoice.objects.all().filter(user__username__exact=request.user.username) if invoices_of_user: total_invoices = len(invoices_of_user) total_invoices += 1 invoice_key = request.user.username + "-" + str(total_invoices) Invoice.objects.create(user=request.user, invoice_no=invoice_key) print(invoice_key, reverse('paypal-ipn')) valid_ipn_received.connect(receiver=show_me_the_money) print(valid_ipn_received.receivers) # What you want the button to do. paypal_dict = { "business": "osama.jameel.ahmad-facilitator@gmail.com", "amount": "14.99", "item_name": "One Month Premium Package", "invoice": invoice_key, "notify_url": "http://0.0.0.0:8000/" + reverse('paypal-ipn'), "return_url": "http://0.0.0.0:8000/app/dashboard", "cancel_return": "http://0.0.0.0:8000/app/change_password", } # Create the instance. form = PayPalPaymentsForm(initial=paypal_dict) context = {"form": form} return render_to_response("core/payment.html", context) @require_POST @csrf_exempt def ipn(request): print("ipn(request)") also the receiver method in views.py def show_me_the_money(sender, **kwargs): print("show_me_the_money: ") ipn_obj = sender print("show_me_the_money: " + ipn_obj.payment_status) and following are urls in in my urls.py url(r'^paypal_ipn/', views.ipn, name="paypal-ipn"), url(r'^something/paypal/', include('paypal.standard.ipn.urls')), #patterns('paypal.standard.ipn.views',url(r'^paypal_notification/', 'ipn', name="paypal-ipn"),) #url(r'^show_me_the_money/', core_views.show_me_the_money, name='show_me_the_money'), url(r'^payment/', core_views.view_that_asks_for_money, name='paypal_page'), -
Bulk download of images rendered under mulitple categories in a single html page
I have lot of images stored in a single folder in a S3 bucket. There are three categories(let's say A, B and C) and an image would fall into only one of the three categories. I am rendering all the images category wise on view-all.html page. What I am trying to do is add a separate download button beside the name of each category in the view-all.html. Upon clicking on a particular download button, the images present only under that category should be downloaded as a zip-file. Currently the download buttons are not working for any of the categories. I have edited only the view-all.html and the views.py files. I searched a lot about this but didn't find any exact solution. I am not sure whether I have to add anything else in any other file. Please help me out. Thanks in advance. view-all.html {% extends "cms/base.html" %} {% block title %} View-all {% endblock %} {% block main %} <style> *{box-sizing: border-box;} .wrapper{ overflow-x:scroll; white-space: nowrap; } .container { background: #ccc; position: relative; height: 50%; display: inline-block; } img { padding: 0; display: block; margin: 0 auto auto 0; margin-left: auto; margin-right: auto; max-width: 100%; } .overlay { position: …