Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Web Server using Stale Javascript Files - Nginx Cache Issue?
I just updated my website for the first time but the old Javascript files are still being used. I've confirmed the files have been updated by using sudo nano. The server is using the updated html files but not the JS files. My Website uses: Django, Gunicorn, Nginx From my understanding it sounds like Nginx is storing cached files. I found that people mentioning to delete the cache by "/var/cache/nginx" but if I run $ cd ~ $ cd /var/cache/nginx I get a file or directory not found. All help would be greatly appreciated. -
Cant get Ajax Post data in view
I am sending a post request to view . everything is fine but no data is sent by ajax. In ajax call i checked variable there is data exist but not when its sent in view. my ajax is $.post({ url: '/projpost/message/{{project.id}}', data: { 'message': message }, success: function (data) { alert(message); //working perfect } }); In view @csrf_exempt def message(request,id): print(request.POST['message']) return HttpResponse(content_type="application/json" ) But I am getting error MultiValueDictKeyError at /projpost/message/5/ 'message' -
Django passing variable to a form
I'm trying to pass a primary key variable straight into a form (foreign key) so the user doesn't have to select it. This is what I have: I have a html button <a href="{% url 'addfraction' pk=botany.botany_id %}" class="btn btn-primary" role="button">Add Fraction</a> It passes the primary key of the botany table (botany_id) through the urls.py url(r'^addfraction/(?P<pk>\d+)/$', views.addfraction, name='addfraction'), The pk comes in to the def addfraction def addfraction(request, pk): if request.method == "POST": form = FractionForm(request.POST) if form.is_valid(): post = form.save(commit=False) post.save() return redirect('allbotany') else: form = FractionForm() return render(request, 'fraction/create_fraction.html', {'form': form}) And the data in the form is saved to the database. class FractionForm(forms.ModelForm): class Meta: model = Fraction fields = ( #'fraction_id', 'botany_id', 'proportion_analysed', 'soil_volume', 'sample_volume', 'sample_weight', ) botany_id is a foreign key, it becomes a dropdown box, this needs to be greyed out and contain the botany_id pk. Where have I gone wrong? Any pointers welcome. -
Django 1.11 - How do I query a DateTimeRangeField with an upper bound of None (PostgreSQL)
I have the following model: class foo(models.Model): range = DateTimeRangeField() I want to find all rows where range is unbounded above. I tried the following query: foo.objects.filter(range__endswith = None) but it's giving my this exception: ValueError: Cannot use None as a query value. How can I do this? -
SQL - Query latest value from table for each match
I have 2 tables, similar to this: Person: id name HeightStatus: timestamp // The time that this status is relevant to person_id height Possible values can be Person - [1, John], [2, Bob], [3, Jeniffer] HeightStatus - [100, 1, 5], [150, 1, 7], [40, 2, 12], [30, 2, 9], [400, 3, 7] This means that I have 3 persons, and on time 100, john's height was 5, at time 150 his height was 7 and so on querying the latest height of a specific person is easy (for example for the person with id 1): select height from Person, HeightStatus where Person.id==HeightStatus.person_id and Person.id == 1 order by timestamp desc limit 1 My problem is how to use that as part of a larger query? e.g - I want to get all the people that their latest height is greater than 8 I guess it is possible to use a view or just use a query within a query. I'm using Django, but I'm open to writing that as a plain SQL query and necessarily using Django's ORM -
Error in deploying django application in Google's App Engine
I'm trying to deploy a django application in google App Engine and I'm getting the following error: Updating service [default] (this may take several minutes)...failed. ERROR: (gcloud.app.deploy) Error Response: [4] Timed out waiting for the app infrastructure to become healthy. I'm following this tutorial: Execute Django in Google App Engine I am using Google Cloud Shell to do the tutorial, as such I cloned their project in the Shell and did everything there. My app.yaml file looks like this: app.yaml The Database part of my settings.py is correct and the problem is not there. Also, I'm getting the following error in my activity tab in GCP after deploying the App. Kubernetes Error I ran the app logs and got the following result: warning app is listening to server With all this information, can anybody help me solve this problem, since I've spent a few days on, and I can't seem to fix the problem with the information provided in any other thread... -
Django multi language post models
Im begineer on django. Im try create multilanguage blog. I use django 2.1.2 and Python 3.7.1 Now, i can easily translate urls, keywords, etc use to "gettext_lazy" and working awesome... But i can't find any way or plugin for translate my posts models. I try install django-modeltranslation but i cant use. I think this plugin is incompatible with my django version... Because i take _clone() got an unexpected keyword argument '_rewrite' error all time. I have no idea how to solve it. What is solution best way for translate for my posts? I want see my Articles in admin like this; https://image.ibb.co/kiuFFA/Screenshot-16.jpg setting.py lang like settings like this; from django.utils.translation import gettext_lazy as _ LANGUAGE_CODE = 'en' LANGUAGES = ( ('de', _('Deutsch')), ('en', _('English')), ) MULTILINGUAL_LANGUAGES = ( "en", "de", ) my base urls.py like this; from django.conf.urls.i18n import i18n_patterns from django.utils.translation import gettext_lazy as _ urlpatterns = [ path('i18n/', include('django.conf.urls.i18n')), ] urlpatterns += i18n_patterns( path(_('admin/'), admin.site.urls, name="admin"), path(_('about/'), views.about, name="about"), path(_('contact/'), include("contact_form.recaptcha_urls")), path('', include("article.urls")), path(_('user/'), include("user.urls")), path('', views.index, name="index"), prefix_default_language=True, ) + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) my model.py like this; class Article(models.Model): author = models.ForeignKey("auth.User",on_delete = models.CASCADE, verbose_name="Author") title = models.CharField(max_length = 120, verbose_name="Title") category = models.ForeignKey('Category', on_delete = models.CASCADE, null=True, … -
Redirect is not allowed for a preflight request
I have this problem where i get the response when trying to use a rest api: "Access to fetch at 'https://kollektivet.app:8082/api/login/' from origin 'https://kollektivet.app' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: Redirect is not allowed for a preflight request." This happens when i try any of the rest api's I am using. From what i have read, this error means I am trying to re-direct, which I am not. The backend is Django and looks like this: @csrf_exempt @api_view(["POST"]) @permission_classes((AllowAny,)) def register(request,): password = request.data.get("password", "") email = request.data.get("email", "") if not email and not password and not email: return Response( data={ "message": "username, password and email is required to register a user" }, status=status.HTTP_400_BAD_REQUEST ) new_user = User.objects.create_user( email=email, password=password ) return Response(status=status.HTTP_201_CREATED) And the front-end is in react which looks like this: createUser(event) { event.preventDefault(); let data = { name: this.state.name, password: this.state.password, repeatPassword: this.state.repeatPassword, email: this.state.email }; if (this.state.name !== '' && this.state.password !== '' && this.state.email !== '' && this.checkPasswords()) { console.log('name', this.state.name, 'password ', this.state.password, 'email ', this.state.email); fetch("https://kollektivet.app:8082/api/register/", { method: 'POST', headers: { 'Accept': 'application/json', 'Content-Type': 'application/json', }, mode: "cors", body: JSON.stringify(data) }) .then(response => response.json()) … -
Angular 6 Prod build running blank page after upgrading from Angular 5
My team's Angular app was using Angular 5 and production builds to our django app worked perfectly fine. However, after we upgraded to Angular 6, we can no longer run ng build properly. We our Output directory is our django app's static files, where Django can reference the bundle. the django app starts up, spits out no console errors, and just hosts a blank white page. I assume it has to do with some change between Angular 5 to 6 and the default production build settings. Our old build command used to be: ng build --prod --aot --output-path="../ClientApp/static/angular" --deploy-url /static/angular And this build worked perfectly every time, exporting our angular bundle to our Django app's directory. However, running this same build in Angular 6 does not work as intended, as I spoke about above. We have changed our Angular.json to include an href: "/" in our default build options but that does not seem to help either. Again, there are no errors to try and solve, it just seems like the .js files are just not running properly or there is something off with our href, even though it was fine before the upgrade Has anyone else run into this … -
Richtext in Django renders wrong
I'm using wagtail 2.3 on Django 2.1, and for a specific loop, the richtext elements which contain an <a>tag are rendered wrong. This is the template used: <div id="interactions-table"> {% for interaction in value.interactions %} <a href="javascript:;" class="interactions-table__elem combo-not-active" style="background-color: {{ interaction.interaction_type.colour }}"> <p class="interaction-table__elem__interaction__name">{{ interaction.drug_name }}</p> <div class="d-none interaction-table__elem__interaction"> <h4>{{ interaction.interaction_type }}</h4> {{ interaction.description | richtext }} </div> </a> {% endfor %} </div> The snippet below shows 3 elements being rendered. The first two are rendered correctly inside their <a>, however the third one isn't: <div id="interactions-table"> <a href="javascript:;" class="interactions-table__elem combo-not-active" style="background-color: #9BEA8B"> <p class="interaction-table__elem__interaction__name">Paracetamol</p> <div class="d-none interaction-table__elem__interaction"> <h4>Low risk and no synergy</h4> <div class="rich-text"><p>...</p></div> </div> </a> <a href="javascript:;" class="interactions-table__elem combo-not-active" style="background-color: #9BEA8B"> <p class="interaction-table__elem__interaction__name">Ibuprofen</p> <div class="d-none interaction-table__elem__interaction"> <h4>Low risk and no synergy</h4> <div class="rich-text"><p>content.... </p></div> </div> </a> <a href="javascript:;" class="interactions-table__elem combo-not-active" style="background-color: #F37A70"> <p class="interaction-table__elem__interaction__name">Tricyclics</p> </a> <div class="d-none interaction-table__elem__interaction"> <a href="javascript:;" class="interactions-table__elem combo-not-active" style="background-color: #F37A70"> <h4>Dangerous</h4> </a> <div class="rich-text"> <a href="javascript:;" class="interactions-table__elem combo-not-active" style="background-color: #F37A70"></a> <p> <a href="javascript:;" class="interactions-table__elem combo-not-active" style="background-color: #F37A70"> beginning of content... </a> <a href="/somewhere"> link in original content </a> end of content </p> </div> </div> </div> Thanks. -
How to conditionally pass values to django's queryset.values
I have a HTML form that is being submitted to a django view via get method. The goal is to print a list of users from the users table but only print the fields that have been selected in the form i.e. the user will select the columns that they want to print. In my View, I check to see if a given column is selected then append it to a list. I then pass this list to django's queryset.values() method. However, it does not accept a list object as an argument. class PrintUsers(TemplateView): template_name = 'users/print-users.html' def get(self, request, *args, **kwargs): context = super(PrintMembersList, self).get_context_data(**kwargs) users_list = Member.objects.all() values_list = [] if self.request.GET.get('category') == 'on': values_list.append("category") if self.request.GET.get('email') == 'on': values_list.append("email") users_list.values(values_list) # this does not work context['users_list'] = users_list return render(request, self.template_name, context=context) How can I conditionally build the *fields values as the documentation does not explain this here https://docs.djangoproject.com/en/2.1/ref/models/querysets/#values ?? -
Django: int() argument must be a string, a bytes-like object or a number, not 'NoneType'
I need to make a single template which must consist of: two inputs with randomly generated integers input for user to type in a sum of before-mentioned integers button, which checks a user's answer button, which creates new random integers After random creation of integer I mean to pull them to view, so their sum can be checked. But Django throws an exception int() argument must be a string, a bytes-like object or a number, not 'NoneType'. How to fix this issue? forms.py from django import forms class SumForm(forms.Form): sum = forms.IntegerField( widget=forms.TextInput(attrs={'class': "form-control"}), label='', required=False ) views.py from django.shortcuts import render from .forms import SumForm import random def index(request): form = SumForm(request.POST) user_sum = form['sum'].value() if 'randomize' in request.POST: num1 = random.randint(10, 99) num2 = random.randint(10, 99) elif 'check' in request.POST: num1 = int(request.POST.get('int1')) num2 = int(request.POST.get('int2')) if user_sum == int(num1 + num2): exclam = 'Right, ' + str(num1 + num2) else: exclam = 'wrong, ' + str(num1 + num2) return render(request, 'index.html', locals()) index.html <form action="{% url 'sum:index' %}" method="post"> {% csrf_token %} <div class="container"> <div class="row"> <div class="col-4"></div> <div class="col-md-4 offset-md-4"> <table class="table borderless"> <thead> </thead> <tbody> <tr> <td><input type="text" name="int1" class="form-control" disabled="disabled" value=" {{ num1 }} … -
Django 'str' object is not callable when deleting a foreign key object
I have a model with a foreign key to another model and when I try to delete an object (in this example the object with id=0 that exists). Models.py class MyModel(models.Model): example = models.ForeignKey(OtherModel,related_name='example',on_delete=models.SET_NULL ,blank=True,null=True) class OtherModel(models.Model): name = models.CharField(max_length=250) shell >>> import project >>> from project import models >>> project.models.OtherModel.objects.get(id=0).delete() Traceback (most recent call last): File "console", line 1, in "module" File ".../lib/python3.5/site-packages/django/db/models/base.py" , line 890, in delete collector.collect([self], keep_parents=keep_parents) File ".../lib/python3.5/site-packages/django/db/models/deletion.py", line 222, in collect field.remote_field.on_delete(self, field, sub_objs, self.using) TypeError: 'str' object is not callable -
Changing location of sqlite database on rpi running django
I am running a django project on a raspberry pi and want to move the database to an external hard drive that is connected. my settings looks like this: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': '/mnt/MOCStorage/database.db, } } When I run manage.py migrate, I get this error: django.db.utils.OperationalError: unable to open database file I have mounted the drive to /mnt/MOCStorage and used chmod to change the permissions of /mnt and /mnt/MOCStorage to 775. How can I get this database to work here? -
IE 11 Ajax call throws Error 0x2efe or Authentication Creds not provided
I have a very simple ajax PUT call that works in Chrome & Firefox but doesn't work in IE 11. The server is sending a 403_FORBIDDEN status for IE11 and 200_OK for chrome & firefox. I'm getting one of two errors in IE11 dev tools (f12): SCRIPT7002: XMLHttpRequest: Network Error 0x2efe, Could not complete the operation due to error 00002efe. or base Error: responseText"{"detail":"Authentication credentials were not provided."}" here is my html: {% csrf_token %} <select name="1_score_risk" data-score="risk" data-assesspk="1" data-answerpk="1" class="select-post form-control center-block"> <option selected value=0>0</option> <option value=1>1</option> <option value=2>2</option> </select> and my csrf_token setting the header javascript: //this is directly from https://docs.djangoproject.com/en/dev/ref/csrf/ function getCookie(name) { var cookieValue = null; if (document.cookie && document.cookie !== '') { var cookies = document.cookie.split(';'); for (var i = 0; i < cookies.length; i++) { var cookie = jQuery.trim(cookies[i]); // Does this cookie string begin with the name we want? if (cookie.substring(0, name.length + 1) === (name + '=')) { cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); break; } } } return cookieValue; } var csrftoken = getCookie('csrftoken'); function csrfSafeMethod(method) { // these HTTP methods do not require CSRF protection return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method)); } $.ajaxSetup({ beforeSend: function (xhr, settings) { if (!csrfSafeMethod(settings.type) && !this.crossDomain) { console.log(csrftoken); //csrf … -
Stop Jinja2 Execution With IF Statement?
I have some code like: {% if key_var is not none %} {{ my_list[key_var] }} {% endif %} However, I'm getting an error: jinja2.exceptions.UndefinedError: 'list object' has no attribute 'None' Is there a way to get Jinja2 to not run the code if the IF statement is false? Or am I missing something else? Thank you for your help :) -
django ORM *outside* of django project?
I'm trying to use django's ORM from a script from mysite.settings import DATABASES, INSTALLED_APPS from django.conf import settings from django import setup settings.configure(INSTALLED_APPS=['polls.apps.PollsConfig'], DATABASES=DATABASES) setup() # NOW I CAN IMPORT from polls.models import Poll ... This works fine as long as the script is inside the django project folder structure. But if I try to move this outside the project I get a no module "mysite" which makes sense. So, I change it to from x.y.mysite.settings import where x is on my PYTHONPATH But now I get a no module named "polls" error If I change the configuration to INSTALLED_APPS=['x.y.polls.apps.PollsConfig'] and get the same error. Additionally, during the handling of the exception, another exception occurs: django.core.exceptions.ImproperlyConfigured: Cannot import 'polls'. Check that 'x.y.polls.apps.PollsConfig.name' is correct. Which it seems to be. Any ideas what's wrong? -
File uploaded to S3 from Django without Extension
I am using Django to S3 file uploading from FileField and it's working properly. But in a scenario, I am converting a file and storing it locally, then saving to model that also uploaded properly, but when trying to access it, I found it's saved without any file extension. Here is my codebase, if convert == 'true': pdf_name = "temp.pdf" pdf_path = os.path.join(settings.BASE_DIR, 'assets/' + pdf_name) image_path = os.path.join(settings.BASE_DIR, 'assets/images') handle_uploaded_file(request.FILES['file'], pdf_path) pdf2jpg.convert_pdf2jpg(pdf_path, image_path, pages="ALL") os.chdir(image_path + "/" + pdf_name) converted_image = image_path + "/" + pdf_name + "/" + glob.glob("*.pdf.jpg")[0] image_file = open(converted_image, 'rb') saved_img = CCFile.objects.create( file=File(image_file), uuid=uuid.uuid4(), name=request.FILES['file'].name + "_converted", modified_by=request.user.username, media_type=".jpg", size=File(image_file).size, additional_info='converted image file', type='Image' ) saved_file = cc_file_serializer.save(modified_by=request.user.username) return Response({ "converted_img": saved_img.as_json(), "saved_file": saved_file.as_json() }, status=status.HTTP_201_CREATED) -
Keras Model Serving- GPU vs CPU
I would like to put my Keras NER model up to my website which is Django based. My question is that when served, should the model be run on CPU or GPU? How would a GPU handle let's say hundreds of users sending requests at the same time since it cant do multi threading like CPUs can. Thanks for your time. -
What must I do to change a Django ForeignKey that originally was required to make it optional now?
I have a data model with many ForeignKey fields. From the original design, some are optional (via blank=True, null=True) while others are required (by relying on the defaults of blank=False, null=False). Now, several years later, I wish to change a few of these to be optional. I add blank=True, null=True to those fields on the data model, run manage makemigrations and manage migrate, yet the admin page behaves exactly as before: those that were once required are still required. -
Best way to log a user out of several, owned websites?
I have several apps that connect to a central OAuth2 server (this is the only login method). When a user hits Log out, I want him to be logged out of all the apps and the OAuth server. All the apps are Django at the moment but that might change, so I'm looking for the most cross-framework way to do it. I must also keep in mind that all the apps might handle sessions differently (some server-side, some client-side). All logouts must be handled by POST requests as the good practice recommends. The strategy I have in mind: On the app, the user clicks on Log out This Log out link points towards the logout page on the OAuth server, on which a POST request to /logout is issued immediately (or after a countdown). The session is killed on the OAuth server and the user is logged out of it. A ?next=... parameter redirects the user back to app A. The app pulls the user status from OAuth server (server- or client-side) : if logged out from the OAuth server, then logout from the app also. New apps would just have to implement this pulling mecanism along with the logout … -
Django filtering disjoint sets with Q
I have a method in my Django model that can filter related objects by date range: from django.db import models from django.db.models import Q class Foo(models.Model): # (...) def get_bar_from_range(date_from=None, date_until=None): query_from = Q() query_until = Q() if date_from is not None: query_from = Q(date__gte=date_from) if date_until is not None: query_until = Q(date__lte=date_until) # I have to check whether date_from is greater than date_until if date_from > date_until: # !!! query = query_from | query_until else: query = query_from & query_until return self.bar_set.filter(query) class Bar(models.Model): foo = models.ForeignKey(Foo, on_delete=models.CASCADE) date = models.DateTimeField(null=True) It can filter joint and disjoint time periods. <-------+ +-------> | | ------------x-------------x-----------------> date_until date_from +-------------+ | | ------------x-------------x------------------> date_from date_until I cannot just do self.bar_set.filter(query_from, query_until). I guess that by default Django joins queries with 'AND'. Is there any way I do not have to check manually whether date_from is greater than date_until? -
Can not import X model
I'm getting this error: cannot import name Provider this is my model(products/models.py): from __future__ import unicode_literals from django.db import models from provider.models import Provider class Product(models.Model): name = models.CharField(max_length=100) image = models.FileField(upload_to='products/', null=True) detail = models.CharField(max_length=100) provider = models.ForeignKey(Provider, on_delete=models.CASCADE) ... ... this is my model from provider app: class Provider(models.Model): name = models.CharField(max_length=100) rut=models.CharField(max_length=13, default='9999999999') addres = models.CharField(max_length=100) contact_name = models.CharField(max_length=100) ..... .... I get this error when I try to run my server -
cant-open-lib-odbc-driver-13-for-sql-server-sym-linking-issue
I have de same problem as this post, but the solutions are not working for me my computer is in debian9 thank's for your help (sorry for my poor english) Christophe -
Turn off commands in installed packages for Django
I was wondering if there was a way to disable commands that come from an installed Django package that I do not control. For instance: cities_light is installed and has its own manage commands. I'd like to make those commands unavailable in the ./manage.py command list.