Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django python: Referrer to go two pages back
I know using referrer = self.request.META.get('HTTP_REFERER') I can find the previous page referrer link but I need to go one step further back, something like: referrer = self.request.META.get('HTTP_REFERER', -2) maybe? -
Back end tasks and frontend separation
I use Django and Django Reset Framework for my internal API and I use Vue.js for my frontend. The backend (API) and the frontend are totally separated. I need to run a background task (every time a user is created) and I am considering 2 solutions: Call (with a post_save signal) a function that runs the task. Note that this function will call a 3rd party API. The call might fail for various reasons and/or run during a long period ~20sec. Create a background task With Redis or RabbitMQ or django-background-tasks) Which solution should I go for ? If both solutions are acceptable, what would be the limitations/advantages of each one ? -
Gunicorn Timeout Server Slow issues
I have deployed a webapplication Python Django Rest Framework Front end is Vue js and Database is Mysql. Hosted the website on digital ocean i am using CPU Optimized Droplets with the below configuration 8 GB 4 vCPUs i facing performance issue the site is very slow though the hosting is CPU optimized with 8gb of ram. When i checked the error log i am able to find [CRITICAL] WORKER TIMEOUT (pid:9116) i increased the timeout time of the gunicorn still i am facing the same issue. 1)I want to increase the performance 2)I want to fix the timeout issue i have increased the value in gunicorn as nginx the maximum value is 75s i have not done any addition to it. what will be th best solution. Kindly help me is there any alternative ways to test the performance of the site. -
Django: Annotate based on annotations with conditional
I'm doing this at the end of an annotation chain on my queryset: .annotate(diff=F("total_views")/F("previous_views") The issue is that both total_views and previous_views are annotations themselves. This is working, except when F("previous_views") equals 0. I then get a division by zero error. All attempts to use Case/When have failed. I'm looking for a way to calculate diff as a fraction, unless previous_views is 0, in which case diff should be None. -
Django - how to pass context in base.html?
I have well_list.html that looks like this: Clicking on one of the rows will lead to this page: The above page uses two html files: base.html + contextual_main.html. Base has sidebar navigation, and the latter one extends from the base. In my views.py, I can easily pass in context data into contextual_main.html like this: views.py class ContextualMain_DetailView(DetailView): template_name = 'contextual_main.html' context_object_name = 'single_well_info' model = models.WellInfo contextual_main.html <button type="button" class="btn btn-default" data-container="body" data-toggle="popover"> <a href="{% url 'contextual:bha' pk=single_well_info.api %}">BHA</a> </button> I need to inject context, single_well_info, into base.html too. So I tried injecting it in the same way I did with contextual_main.html, but it won't work. How can I do this? -
Can I set endDate while using AdminDateWidget in django form
I am using the AdminDateWidget in my django form. I want to set an end date so that all dates after the end date are disabled. How can we do this. -
I want to add a count in data base using jquery in django
im trying to add a count on databse according to the no of attempts of file fetch from a server.pls help with the methods..im new to django and jquery and need step wise advise -
Django signup with FirebaseUI?
I am wondering if anyone has attempted using firebaseUI for django registration / signup. Firebase UI does integration of google, facebook, twitter and OTP (one time pin) and when user is verified, the user is logged in to django application. Any resources toward this or what workflow to use for this? -
Django: change project name static error
I just changed my project name from ecommerce to my_project. I went through every file (using a find feature) and did changed ecommerce to my_project. Now when I try to run it I get the following error from the command line: Traceback (most recent call last): File "C:\\Dev\my_project\lib\site-packages\django\core\handlers\exception.py", line 41, in inner response = get_response(request) File "C:\\Dev\my_project\lib\site-packages\django\core\handlers\base.py", line 217, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\\Dev\my_project\lib\site-packages\django\core\handlers\base.py", line 215, in _get_response response = response.render() File "C:\\Dev\my_project\lib\site-packages\django\template\response.py", line 107, in render self.content = self.rendered_content File "C:\\Dev\my_project\lib\site-packages\django\template\response.py", line 84, in rendered_content content = template.render(context, self._request) File "C:\\Dev\my_project\lib\site-packages\django\template\backends\django.py", line 66, in render return self.template.render(context) File "C:\\Dev\my_project\lib\site-packages\django\template\base.py", line ... File "C:\\Dev\my_project\lib\site-packages\django\templatetags\static.py", line 102, in url return self.handle_simple(path) File "C:\\Dev\my_project\lib\site-packages\django\templatetags\static.py", line 117, in handle_simple return staticfiles_storage.url(path) File "C:\\Dev\my_project\lib\site-packages\django\utils\functional.py", line 238, in inner self._setup() File "C:\\Dev\my_project\lib\site-packages\django\contrib\staticfiles\storage.py", line 504, in _setup self._wrapped = get_storage_class(settings.STATICFILES_STORAGE)() File "C:\\Dev\my_project\lib\site-packages\django\core\files\storage.py", line 467, in get_storage_class return import_string(import_path or settings.DEFAULT_FILE_STORAGE) File "C:\\Dev\my_project\lib\site-packages\django\utils\module_loading.py", line 20, in import_string module = import_module(module_path) File "C:\\Dev\my_project\lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 941, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "<frozen importlib._bootstrap>", line 994, in … -
Django - django.urls.exceptions.NoReverseMatch: Reverse for 'bha' with no arguments not found
project/urls.py - Here, I passed in regex for primary key from django.urls import path, re_path, include from contextual import views urlpatterns = [ url('admin/', admin.site.urls), path('well_list/', include([ re_path(r'^$', views.WellList_ListView.as_view(), name='well_list'), re_path(r'^create/', views.AddWell_CreateView.as_view(), name='create'), re_path(r'^(?P<pk>[-\w]+)/contextual/', include('contextual.urls')), ])) ] contextual/urls.py app_name = 'contextual' urlpatterns = [ re_path(r'^$', base_views.ContextualMainView.as_view(), name='main'), re_path(r'^bha/$', base_views.BHA_UpdateView.as_view(), name='bha'), ] views.py class ContextualMainView(DetailView): template_name = 'contextual_main.html' model = models.WellInfo class WellList_ListView(ListView): template_name = 'well_list.html' context_object_name = 'well_info' model = models.WellInfo def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) # get string representation of field names in list context['fields'] = [field.name for field in models.WellInfo._meta.get_fields()] # nested list that has all objects' all attribute values context['well_info_values'] = [[getattr(instance, field) for field in context['fields']] for instance in context['well_info']] # includes well instance objects & values string list for each well context['well_info_zipped'] = zip([instance for instance in context['well_info']], context['well_info_values']) return context class BHA_UpdateView(UpdateView): template_name = 'contextual_BHA.html' model = models.WellInfo fields = '__all__' success_url = reverse_lazy('well_list') well_list.html - primary key is provided in html <tbody> {% for well_instance, values in well_info_zipped %} <tr> {% for value in values %} <td><a href="{% url 'contextual:main' pk=well_instance.api %}">{{ value }}</a></td> {% endfor %} </tr> {% endfor %} </tbody> contextual_main.html - primary key is NOT provided in html <button … -
Why does my facebook login redirect url still using my docker container name?
I am developing django web application, using django-allauth in a docker environment. In my facebook login redirect URI, I already set the value to be my website URL (https://whizkids.id). But somehow in the redirect URL return by facebook, it change to my docker container name: web. https://web.facebook.com/v2.12/dialog/oauth?redirect_uri=https%3A%2F%2Fweb%2Faccounts%2Ffacebook%2Flogin%2Fcallback%2F&client_id=2180006765347725&scope&state=xp0mwKV8NW5w&response_type=code&_rdc=1&_rdr The part redirect_uri=https%3A%2F%2Fweb%2Faccounts%2Ffacebook%2Flogin%2Fcallback%2F should be redirect_uri=https%3A%2F%2Fwhizkids.id%2Faccounts%2Ffacebook%2Flogin%2Fcallback%2F I am using nginx + letsencrypt configuration below: upstream web { ip_hash; server web:8000; } server { listen 8000; server_name whizkids.id www.whizkids.id; return 301 https://$host$request_uri; location ~ /.well-known/acme-challenge { allow all; root /usr/share/nginx/html; } } server { listen 443 ssl http2; listen [::]:443 ssl http2; server_name whizkids.id www.whizkids.id; ssl_certificate /etc/letsencrypt/live/whizkids.id/fullchain.pem; ssl_certificate_key /etc/letsencrypt/live/whizkids.id/privkey.pem; ssl_protocols TLSv1.2 TLSv1.1 TLSv1; ssl_prefer_server_ciphers on; ssl_ciphers '...'; location /static/ { autoindex on; alias /src/static/; } location / { proxy_pass http://web/; } } Is there any configuration that I missed? -
make mode inherit multiple foreign keys on creation
I have 2 models named: PaymentMode and Store as: PaymentMode Model: (id will be auto generated by django) id = integerfield(primarykey) name = model.charfield() - eg: cash, debit, credit etc Store Model: (id will be auto generated by django) id = integerfield(primarykey) payment_mode = model.foreignkey(paymentmode, ondelete=model.cascade) name ... some other fields So what i want is whenever a store is created, all payment modes inherits automatically, inherit all foreign keys, this will make multiple rows in store table as: store_id | payment_mode | name ------------------------------ 1 1 abcd 1 2 abcd 1 3 abcd 2 1 xyz 2 2 xyz 2 3 xyz i looked at various stackoverflow question, probably this might be duplicate, but those all overrides save function and make only one inherited object like: Stackoverflow question so the question is will save function override approach in above question inherit all foreign keys? or will it make only one? Obviously payment modes will be created first. Also in future if a payment mode is added, is it possible to add new payment mode to all pre-existing stores automatically? Probably my approach of creating model is wrong. -
Django Admin CSS Loading in IE 8 but not loading in UC Browser, Firefox or Opera
After a recent upgrade from Django 2.0.2 to Django 2.0.5, i discovered that the CSS styling for the Django admin panel are missing in my usual browser, UC Browser. However, weirdly, they work fine in IE 8, which is preinstalled on my PC and which i do not want to use. I have tried other browsers; Opera and Firefox but the problem still avails. App level CSS works fine, django.contrib.admin and django.contrib.staticfiles work are installed. Any help would be appreciated! -
Visual Studio Poll Django example execution order
I am a newbie to Python and Django. I have been playing with the Polls solution available in VS 2017 to help learn Django and Python. My question has to do this execution of python script files. By strategically adding print statements within the .py files of this solution I am trying to understand the order in which the execution occurs. The first file executed, that is listed on the Solutions Explorer, is manage.py, from there execution jumps to settings.py but it passes through the init file first (which is empty but I added a print statement anyways, so I was able to track it to that point. The settings.py file as expected sets variables, etc.. but the last file in the settings.py file is NOT a call, it is just an assignment of STATIC_ROOT, yet the execution jumps to the models.py via the init once the last line of the settings.py is executed. The question is how and why ? Also when the last line of a python script is reached what happens? Is there an order to execution of various "Packages" or "Modules"? Are script files linked using import statements? Thanks Alphamoose -
How do i set up external access for my locally hosted app? (mac)
I am having trouble setting up the a web app with external access. I am using MacOs High Sierra, I have a django app running on port 8000. Port 8000 is forwarded to the machine's internal ip in router settings. App loads via localhost (localhost:8000) Firewall is disabled Connection is refused via internal ip (192.168.1.4:8000) Connection times out via external ip (*.*.*.*:8000) My intention is to access the app via external ip as well as internal ip. Any ideas? -
Setting different permissions for different kinds of requests on serializer based api (using router)?
I'm using DRF and working on a single URL for handling all user operations such as LIST, GET, POST, etc. I have used a router but I'm unable to find how I should go about tweaking the permissions such as... Even anonymous users can create users. Only registered users (or admins, as an exception) can delete their own posts. And so on.. urls.py from django.urls import path, include, re_path from .api import UserAPI from rest_framework.routers import DefaultRouter urlpatterns = [ # path('register/<int:pk>', UserAPI.as_view(), name='user_create'), ] router = DefaultRouter() router.register(r'user', UserAPI) urlpatterns = [ ] + router.urls Serializers.py from rest_framework import serializers from django.contrib.auth import get_user_model from django.forms import ValidationError User = get_user_model() class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = '__all__' write_only_fields = ('password',) read_only_fields = ('id',) extra_kwargs = {'last_name': {'required': True}} password = serializers.CharField(write_only=True) def create(self, validated_data): user = User.objects.create(email=validated_data['email'], first_name=validated_data['first_name'], last_name=validated_data['last_name'], ) user.set_password(validated_data['password']) user.save() return user api.py from rest_framework.viewsets import ModelViewSet from django.contrib.auth import get_user_model # used custom user model from rest_framework import mixins from .serializers import UserSerializer User = get_user_model() class UserAPI(ModelViewSet): queryset = User.objects.all() serializer_class = UserSerializer -
Django 404 page not found
I've been doing a lesson on udemy trying to make a clone site of producthunt using django. I've tried asking there, but I don't get an answer. For some reason when I run the exact same code as the instructor, I get an error when trying to load the page localhost:8000/signup or any other pages other than the home page. I get this error: error Settings file: settings Main urls: main urls app urls (named accounts): app urls views: app views finally my file structure for reference: directory I've been trying to figure it out with no avail. Any help would be great thank you. -
host not found in upstream when i use nginx and docker-compose
this is my docker-compose.yml file i want to make a nginx to reverseproxy and django to webserver and i also separate them each container version: '2' services: django: build: ./django container_name: django nginx: restart: always build: ./nginx container_name: reversproxy ports: - "7891:7891" depends_on: - django and follwoing is my nginx.conf i set the uwsgi_pass to uwsgicluster, upstream to django containter but nginx container doesn't work with error nginx: [emerg] host not found in upstream "django:7893" worker_processes 1; events { worker_connections 1024; } http { sendfile on; upstream uwsgicluster { server django:7893; } server { listen 7891; location / { include /etc/nginx/uwsgi_params; uwsgi_pass uwsgicluster; proxy_redirect off; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Host $server_name; } } } how can i solve that problem?? -
Django Rest Framework override viewset list() method without loosing filter_backends functionality
I have a viewset and I override list() method, but filtering by field stop working. How can I call filtering options from my code: This is my viewset: class SupplementViewSet(viewsets.ModelViewSet): permission_classes = (permissions.IsAuthenticated,) queryset = models.Product.objects.filter() serializer_class = serializers.SuplementSerializer filter_backends = (DjangoFilterBackend, SearchFilter, OrderingFilter,) search_fields = ('hotel', 'name') filter_fields = ('id', 'hotel', 'name') def perform_create(self, instance): instance.save(product_type=models.Product.SUPPLEMENT) def list(self, request, pk=None): if pk == None: supplements = models.Product.objects.filter(product_type=models.Product.SUPPLEMENT) else: supplements = models.Product.objects.get(product_type=models.Product.SUPPLEMENT, id=pk) page = self.paginate_queryset(supplements) if page is not None: serializer = self.get_serializer(page, many=True) return self.get_paginated_response(serializer.data) serializer = self.get_serializer(page, many=True) result_set = serializer.data return Response(result_set) def get_result_set(self, supplements): result_set = serializers.ProductSerializer(supplements, many=True).data return result_set Thanks for the help. -
Retrieve newly updated article without refreshing the page
I'd like to make a edit link to update the article when it's clicked, In the template, it's structured as: post-text article-content article-form post-menu I hide "article-form" in first place as <div class="article-form" style="display: none;"> until edit link is clicked. <div class = "col-md-12 post-text" > <div class="article-content"> {{article.content}} </div> <div class="article-form" style="display: none;"> <form class="form-horizontal" action="/article/edit/{{ b.id }}" method="POST"> <div class="form-group"> <div class="col-sm-12"> <textarea class="form-control" id="editContent" name="content" rows="10" cols="30"> {{form.content.value}} </textarea > </div> </div> <div class="form-group" > <div class="col-sm-offset-0 col-sm-12"> <button type = "submit" class = "btn btn-success btn-sm" id = "saveEditBtn"> Save Edits </button> </div> </div> </form> </div><!-- article-form --> </div> <div class="post-menu pull-left"> <a id="editArticleLink" href="{% url 'article:article_edit' article.id %}"> <span class="glyphicon glyphicon-edit" aria-hidden="true">edit </span> </a> <a id="delArticleLink"> <span class="glyphicon glyphicon-trash" aria-hidden="true">delete</span> </a> </div> After updating is completed and submit is cliked, send data to backend using Ajax, hide "article-form" and show "article-content". <script> $(document).ready( $(".post-menu a").on("click", function(e){ e.preventDefault(); //retrieve the topmost element which the target lives in $postText = $(e.target).closest(".post-text"); //hide article-content $postText.find(".article-content").hide(); //show the article-form for users to update $postText.find(".article-form").show(); //capture the button submitting event $(".article-form button").on("click", function(e){ var content = $postText.find("textarea").val(); $.ajax({ type:"POST", url: , data:, success: function(){ //if saved successfully $postText.find(".article-content").show(); $postText.find(".article-form").hide(); },//success … -
How to delete the Django model but not the database?
I'm running a production server with Django. I want to delete a model that is no longer needed. Migration makes it easy to apply them to the database. However, I do not want to delete the database that I have accumulated so far. Is there a way to think that the migration manager has been deleted without actually deleting the database? -
command not found: django
I installed django using pip install Django My result was Requirement already satisfied: Django in /usr/local/lib/python2.7/site-packages (1.11.14) When I run django --version I get zsh: command not found: django -
How to manage concurrency in querys?
I have this code: if LikedSlot.objects.filter(restaurant__id=r.id, user__id=u.id).count() == 0: l = LikedSlot.objects.create(restaurant=r, user=u) So the idea is to create a new LikedSlot only if the user didn't liked the restaurant before, but I have a race condition because two requests can get True in the first line if it's reached at the same time. I tried the following but it doesn't seem to fix the issue either: from django.db import transaction with transaction.atomic(): if LikedSlot.objects.filter(restaurant__id=r.id, user__id=u.id).count() == 0: l = LikedSlot.objects.create(restaurant=r, user=u) Do you have an idea how to fix this? -
Django: How to lock rows for reading?
My table contains 'Tasks' for concurrent workers. So worker should be able to 'get' task from the table, means atomically check task is exist and if exist, delete it. Other worker should be locked till this atomic process will complete. How to perform such locking in Django? I am using code like the following, but rows are not locking for reading, two concurrent workers both enters transaction, find same task, one successfully obtain it, but second got OperationalError('database is locked',) SQLite is used class Task(models.Model): @staticmethod def get(): with transaction.atomic(): task = Task.objects.select_for_update().filter(...).first() if task: task.delete() return task return None -
Django ModelChoiceField validation error
I have been trying to create a select input from options based on a Model. I have tried several changes but the error persists. I hope someone can help. The forms.py code. transaction_type = forms.ChoiceField(choices=TRANSACTION_TYPE_CHOICES, widget=forms.RadioSelect(), required=True) transaction_purpose = forms.ChoiceField(choices=TRANSACTION_PURPOSE_CHOICES, widget=forms.RadioSelect(), required=True) transaction_payment_method = forms.ChoiceField(choices=TRANSACTION_PAYMENT_METHOD_CHOICES, widget=forms.RadioSelect(), required=True) transaction_currency = forms.ChoiceField(choices=TRANSACTION_CURRENCY, widget=forms.RadioSelect(attrs={'checked':'checked'}), required=True) transaction_description = forms.CharField(widget=forms.Textarea(), required=False) transaction_after_balance = forms.IntegerField(required=False) transaction_account = forms.ModelChoiceField(required=False, queryset=Accounts.objects.none(), empty_label="Select Account") class Meta: model = Transactions fields = ('transaction_amount','transaction_type', 'transaction_title', 'transaction_description','transaction_currency','transaction_account', 'transaction_purpose', 'transaction_payment_method','transaction_after_balance') views.py code def get(self, request): employee_name = Employees.objects.get(user=request.user) form = TransactionForm() form.fields['transaction_account'].queryset = Accounts.objects.filter(user=request.user) print(form.fields['transaction_account'].queryset) args = {} args['transaction_form'] = form args['employee_search'] = employee_name return render(request,'finance/add_transaction.html', args) def post(self, request): transaction_form = TransactionForm(request.POST) transaction_balance = Transactions.objects.filter(user=request.user).latest('transaction_created_at').transaction_after_balance print (transaction_form) if transaction_form.is_valid(): form_obj = transaction_form.save(commit=False) if form_obj.transaction_type == "Credit": transaction_balance = transaction_balance - form_obj.transaction_amount form_obj.transaction_after_balance = transaction_balance else: print (transaction_balance, form_obj.transaction_amount) transaction_balance = transaction_balance + form_obj.transaction_amount form_obj.transaction_after_balance = transaction_balance form_obj.user= request.user form_obj.save() return render(request,'dashboard') return render(request,'Error') html template code <div class="col-lg-3"> <label> Account: </label> <div class=""> {% render_field transaction_form.transaction_account class="form-control m-select2" id="account_select" name="transaction_account" %} </div> </div> Template is rendering ok. This is the rendered template showing options. Rendered HTML Code: <select name="transaction_account" id="account_select" class="form-control m-select2 select2-hidden-accessible" data-select2-id="account_select" tabindex="-1" aria-hidden="true"> <option value="" selected="" data-select2-id="2">Select Account</option> <option …