Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
URL scheme & Django views for extremely similar API and webpage
I am designing an API for a website I manage which will more or less be the same data shown tabularly on the site as will be served as JSON to clients. Essentially, I hope that the webpages themselves could be rewritten as API clients if I really wanted. I have two primary questions: What is an appropriate URL scheme separation between calls to show HTML webpages and calls to the API? My initial thought is to use the singular form (/city/1) for the webpage and the plural (/cities/1) for the API, as I did not yet know that the plural is the preferred way to structure my URL scheme. Since both the API and the webpage view return such similar data, is there any consolidation that can be done in views.py so that the HTML and JSON outputs use the same code for gathering their queryset? I feel that the API endpoint could call to the webpage view code and then pass its result through a serializer before returning it, but I want to double-check that is a reasonable option. -
How to filter the Parents ID by its children foreign key?
\\views def Parents_login_form(request): if request.method != 'POST': raise Http404('Only POSTs are allowed') try: m = ParentsProfile.objects.get(Parent_User=request.POST['p_user']) if m.Parent_Password == request.POST['p_pass']: aa = request.POST['p_user'] parents = ParentsProfile.objects.all().filter(Parent_User=aa) student = request.POST.get('parentsID') students = StudentProfile.objects.filter(Parent_Users = student) print(students) return render(request, 'accounts/ParentsProfile.html', {"parents": parents, "students": students}) except ParentsProfile.DoesNotExist: messages.warning(request, 'Please correct the error below.') return render(request, 'accounts/Plogin_form.html') //html {% for me in parents %} <input type="hidden" value="{{me.id}}" name="parentsID" id="parentsID" onchange="" readonly> {% endfor %} //model class StudentProfile(models.Model): . . . Parent_Users = models.ForeignKey(ParentsProfile, related_name='+', on_delete=models.CASCADE,null=True,blank=True,) -
How do we handle 'View Live' while creating a page/child page in a decoupled wagtail project?
I have a decoupled wagtail project in which front-end is served by ReactJS. Front-end build files are served from /proj_dir/frontend/react and is defined in /proj_dir/settings/base.py as STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'proj_dir/frontend/react', "build", "static"), ] STATIC_URL = '/static/' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'projdir/frontend/react')], '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', 'wagtail.contrib.settings.context_processors.settings', ], }, }, ] So when I 'build' the react application, this frontend application is served on 'python runserver' How can I handle the 'View Live' scenario when we create a page/child page in this case. In order to reduce the development time is it possible not to write template files for each pagetypes? -
Rewrite URL in Django 1.10
Looking for how to convert this to Django 1.10: ('^plugins/(?P<path>.*)$', 'redirect_to', {'url': '/static/plugins/%(path)s'}), Basically I have ~50 files in a HTML theme that reference files at /plugins/blah-blah and I want to serve via /static/plugins/blah-blah. So any request to /plugins/ should go to /static/plugins - any idea how? -
Django provide GET variable to the filter from template
I have filter which has one field lawyersspec__lawyer_spec. To use this filter there is form which works fine and is available on website A, but I want to have links to this website with filter already set to some value. (i.e. lawyersspec__lawyer_spec=2) filters.py class LawyerFilter(django_filters.FilterSet): class Meta: model = TestPy.models.Lawyer fields = ['lawyersspec__lawyer_spec'] def __init__(self, *args, **kwargs): super(LawyerFilter, self).__init__(*args, **kwargs) views.py object_list = TestPy.models.Lawyer.objects.filter(Q(confirmed=True) & Q(is_active=True)) filter = LawyerFilter(request.GET, queryset=object_list) template.html {% for i, spec in specs.items %} <a href=" {% url 'lawyer-list' %}?lawyersspec__lawyer_spec={{ i }}">{{ spec }}</a> How can I achieve this? I've tried setting url in template as {% url 'lawyer-list' %}?lawyersspec__lawyer_spec=value but it's not working. I mean, the filter is the form is set to proper one, but results aren't filtered. I've checked if the lawyersspec__lawyer_spec is available in GET and it is there, but for some reason filter is not filtering according to those variable. -
How can I make an ORM query that leverages MySQL late row lookups?
In my django application I have defined a model like so: class NamedContainer(models.Model): name = models.CharField(max_length=50) capacity_ml = models.PositiveIntegerField() created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class Meta: ordering = ['name', 'capacity_ml'] Over time, this table has grown big enough to start causing some query performance issues, specifically when relying on limit/offset for slicing. Other slicing methods may have better performance by design, but for now I'm stuck with limit/offset, unfortunately. However, MySQL has a technique called "late row lookups" which greatly helps with my problem and, in short, a raw MySQL query using this technique could look something like SELECT t2.* FROM ( SELECT * FROM `core_namedcontainer` WHERE `updated_at` >= '2019-01-01 05:00:00.000Z' ORDER BY id ASC LIMIT 500 OFFSET 10000 ) AS t1 JOIN `core_namedcontainer` AS t2 ON t1.id = t2.id ORDER BY `name` ASC, `capacity_ml` ASC I have only managed to mangle the ORM query to produce a query like SELECT * FROM `core_namedcontainer` WHERE ( `core_namedcontainer`.`id` IN ( SELECT U0.`id` FROM `core_namedcontainer` U0 WHERE ( U0.`updated_at` >= 2019-01-01 05:00:00 ) ORDER BY U0.`name` ASC, U0.`capacity_ml` ASC LIMIT 500 OFFSET 10000 ) ) ORDER BY `core_namedcontainer`.`name` ASC, `core_namedcontainer`.`capacity_mL` ASC which simply uses a subquery instead of a join to … -
Django not validating values changed with JS
I've been trying to simulate some sort of picklist on Django forms, where there's 3 SelectMultiple involved, all begin in Area field, when Area is changed the field Course_Area is reloaded with the Courses related of the Area selected(this part is already working) and finally the field Course where the problem happens, the Course field should be filled with the non repeated selected objects from Course_Area a task that from what i've searched is better performed with JS, with my actual JS code the selected items from Course_Area are being passed to the Courses field but when the form is submited the Course field dont pass on the validation phase. Any help would be welcome. Form code: class MyEntityForm(forms.ModelForm): area = forms.ModelChoiceField( label='Area', queryset=Area.objects.all(), required=False, empty_label='Area', widget=forms.Select(attrs= {'onchange': "filterCourses();"} ) ) courses_area = forms.ModelMultipleChoiceField( label='Courses by Area', queryset=Curso.objects.none(), required=False, widget=forms.SelectMultiple(attrs= {'onclick': "addCourse();"} ) ) class Meta(): model = Entidade fields = ['area', 'courses_area', 'courses'] The JS code: function filterCourses(){ area_id=document.getElementById('id_area').value; $.ajax({ url: '/myentity/ajax/load_courses/', data: { 'area': area_id, csrfmiddlewaretoken: '{{ csrf_token }}' }, success: function (data) { $("#id_courses_area").html(data); } }); } function adicionaCurso(){ $("#id_courses").append( $("#id_courses_area option:selected")); } -
Accessing json objects with spaces in html table
Apologies if this has been asked before but I can't seem to find the answer. I'm super new to html/java/django but I feel like this shouldn't be this hard and is a stupid question but I'm going crazy over it. I'm making a web app that pulls json data from firebase so I'm using python/pyrebase/django etc. and I simply need to access a json object from my database and put it into an html table. It all works great, except accessing the child that has spaces in it (unfortunately I need to keep the spaces in for my mobile app purposes). I assumed it would be the same at dot/bracket notation but this doesn't seem to work. I've also tried declaring a variable <script> var score = 'JUDGE A RUN 1: '; </script> and using result.score with no luck but maybe I'm putting it in the wrong spot or something silly. <div class="container"> <h2></h2> <p></p> <table class="table table-striped"> <thead> <tr> <th>BIB</th> <th>Ridername</th> <th>Stance</th> <th>Score</th> </tr> </thead> <tbody> {% for result in data%} <tr> <td>{{ result.bib }}</td> <! works! > <td>{{ result.ridername }}</td> <! works! > <td>{{ result.stance}}</td> <! works! > <td>{{ result['JUDGE A RUN 1: '] }}</td> <! doesn't work … -
Django Stale CSRF Token
I set up my django application to perform email confirmation when a user signs up using the code from this tutorial. When I test it, I go to the sign up page, fill out the required fields, and submit. The page sends me to the login page. I go check my email and click the link provided to activate my account which creates a new tab. Then, I go to the other tab containing the login page (which we were redirected to previously) and enter the information to login. Unfortunately, I am met with an invalid/missing csrf token page. After pressing back, and logging in again, it is successful! What is the problem here? And how do I solve it? When I click the link in the activation email, is a new csrf token generated and the other tab that has the login page has the old csrf token which is causing the issue? How do I fix this? -
Setting bulk_create to a variable (Django)
I'm using bulk_create to create multiple profiles: def bulk_create_and_get(cls, profile_ids): tickets_to_create = [] for profile_id in profile_ids: ticket = cls(profile_id=profile_id) tickets_to_create.append(ticket) cls.objects.bulk_create(tickets_to_create) Were the cls is the Ticket Class model Can I save my bulk_create to a variable and return it? created_tickets = cls.objects.bulk_create(tickets_to_create) Instead of querying for the tickets I just created? created_tickets = cls.objects.filter( Q(profile_id__in=profile_ids) | Q(unregistered_profile_id__in=profile_ids) ) return created_tickets -
How to prevent Django object from sending signal when I use save in the function that receives the post_save?
So I am trying to post process the content of an object after it is saved. @receiver(post_save, sender=Model) def changed_model(instance, **kwargs): ... ... model.data = post_processed_data model.save() And this leads to the function calling itself forever. -
URL to static files with django-storages
I have set Django to serve static files from an S3 bucket using django-storages. Unfortunately the urls to the static files look like: https://[bucket name].s3.amazonaws.com/profile_pics/[filename]?AWSAccessKeyId=[...]&Signature=[...]&Expires=[...] Is there way to encode the urls to avoid revealing the AWS access key and signature? -
How do I get data assume html name is very similar to each other? (Django) (POST method)
Let say I have a dynamic html form (POST method), user can click 'add item' to add as many item as they like. Each item attribute after added is named like this: name="item1", name="item2", name="item3"... What should I do from view.py to loop through this list of items and save each item in my Item model? I know how to get 1 item, but not a list of item since i don't know how many item user is going to add. -
How to perform django full text searchvector on one model object field
I have the following model which has response_results json field which contains large dataset of json objects: My model Response_Grab has only one object with id 8 , i'm strong all data in one object, from django.contrib.postgres.fields import JSONField,ArrayField from django.contrib.postgres.search import SearchVectorField class Response_Grab(models.Model): response_domains = ArrayField(models.TextField(blank=True),blank=True,null=True,default=list) response_results = JSONField(blank=True,null=True,default=dict) response_grab_interval = models.IntegerField(default=48) search_vector = SearchVectorField(null=True) response_results jsonfield format example: { "http://google.com": {"Version": "1.0", "Server": "AkamaiGHost"}, "https://facebook.com":{"Version":"1.0","Server":"Apache"}, ... ... } Here's what I did so far: >> from elasticapp.models import Response_Grab as rg >> from django.db.models import TextField >> from django.db.models.functions import Cast ### TO Convert JSON to Text >> rg.objects.annotate(search=SearchVector(Cast('response_results',TextField())),).filter(search='http://google.com') <QuerySet [<Response_Grab: default>]> How do I query such that providing following KEY http://google.com should return all its values i.e {"Version": "1.0", "Server": "AkamaiGHost"}? -
Django: Safely Remove Old Migrations?
I've got a Django app with a lot of out-of-date migrations. I'd like to remove the old migrations and start fresh. The app has 14 different "migrations" folders. Here is what a few of them look like: Is it safe to remove all the contents from each of these folders? Or, do I have to make sure to only remove some of the files -- and if so which files? -
Django validation - avoiding multiple full_cleans()
I am new to Django, and after reading a bunch of docs/guides and googling stuff, I am still a little confused about the best practice way to do validation. It seems like the best place to do validation is on the Model level, to ensure that it is always applied, regardless of where the data comes from (e.g. Django front-end, some JS server, API, etc). If I override the Model save() method in my base model to call full_clean(), that seems like the best way to guarantee that the saved data is always good. However, I am running into various issues with this in my project. The obvious one is that Django's ModelForms call Model full_clean() already, so I end up calling it twice in this case. On top of that, there are other complications, for example: if there is a Model level method that saves a compound Model that has another Model inside it (e.g. Address inside some Account), I can't just save Address, because Account might fail validation afterwards. So I really need to validate both Models first, and only then save them (keep it transactional). But then, I need to call full_clean() to validate, and it's called … -
How can i fix this Django admin issue? Django admin Site matching query does not exist
My admin does not work. I alredy try it a couple of hours. The miration works: C:\Users\sebas\AI_MachineLearning\Django_Projekt\pythonprojects\cookbook>python manage.py migrate Operations to perform: Apply all migrations: admin, auth, contenttypes, recipes, sessions, sites Running migrations: No migrations to apply. C:\Users\sebas\AI_MachineLearning\Django_Projekt\pythonprojects\cookbook> The Superuser is created. Runserver works: C:\Users\sebas\AI_MachineLearning\Django_Projekt\pythonprojects\cookbook>python manage.py runserver Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). September 18, 2019 - 22:06:57 Django version 2.2.5, using settings 'cookbook.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. If I try the urls ../admin: http://dpaste.com/069QF7H DoesNotExist at /admin/login/ Site matching query does not exist. Request Method: GET Request URL: http://127.0.0.1:8000/admin/login/?next=/admin/ Django Version: 2.2.5 Exception Type: DoesNotExist Exception Value: Site matching query does not exist. Exception Location: C:\Users\sebas.conda\envs\pythonDjango\lib\site-packages\django\db\models\query.py in get, line 408 Python Executable: C:\Users\sebas.conda\envs\pythonDjango\python.exe Python Version: 3.6.7 Python Path: ['C:\Users\sebas\AI_MachineLearning\Django_Projekt\pythonprojects\cookbook', 'C:\Users\sebas\.conda\envs\pythonDjango\python36.zip', 'C:\Users\sebas\.conda\envs\pythonDjango\DLLs', 'C:\Users\sebas\.conda\envs\pythonDjango\lib', 'C:\Users\sebas\.conda\envs\pythonDjango', 'C:\Users\sebas\.conda\envs\pythonDjango\lib\site-packages'] Server time: Mi, 18 Sep 2019 21:55:32 +0200 Envoi -
urls files started to look like scratch files with no colored fonts in Pycharm
My problems started by changing the shape of th all urls files when I use pycharm only, then I modified some models but the site does not work properly, and unable to read the models members. I tried to start a new project all the new rls.py converted to scratch files I do not the meaning of this error:- django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. -
Can I load a fixture with the DateField set to null?
I'm have some Datefields I would like to keep null or blank when I load a fixture. Is there a way to keep them null or blank without putting some default value? In the model, I have already set null=True, blank=True. -
npm can't resolve babel_loader when running React with Django
I am following this tutorial for integration React with Django. I have gone through all the steps, but when I run npm run dev, I get this error: > AttractoraProject@1.0.0 dev /Users/hugovillalobos/Documents/Code/AttractoraProject > webpack --mode development ./Attractora/frontend/src/index.js --output ./Attractora/frontend/static/frontend/main.js Insufficient number of arguments or no entry found. Alternatively, run 'webpack(-cli) --help' for usage info. Hash: cf46d3c1f598793a6a6e Version: webpack 4.40.2 Time: 111ms Built at: 09/18/2019 2:05:08 PM ERROR in Entry module not found: Error: Can't resolve 'babel_loader' in '/Users/hugovillalobos/Documents/Code/AttractoraPro ject' npm ERR! code ELIFECYCLE npm ERR! errno 2 npm ERR! AttractoraProject@1.0.0 dev: `webpack --mode development ./Attractora/frontend/src/index.js --output ./Attractora/ frontend/static/frontend/main.js` npm ERR! Exit status 2 npm ERR! npm ERR! Failed at the AttractoraProject@1.0.0 dev script. npm ERR! This is probably not a problem with npm. There is likely additional logging output above. npm ERR! A complete log of this run can be found in: npm ERR! /Users/hugovillalobos/.npm/_logs/2019-09-18T19_05_08_809Z-debug.log I ran this command to install babel, so I don't know what I am missing: npm i @babel/core babel-loader @babel/preset-env @babel/preset-react babel-plugin-transform-class-properties --save-dev -
How do I model Django timestamps if I must import old data initially?
I have some basic timestamp fields that should end up as auto_now_add: class Example(models.Model): created = models.DateTimeField(auto_now_add=True) However, I need to seed the initial Django project database from an external database where these creation timestamps are already populated for existing data. I imagine I may need to do the following: Start with created = models.DateTimeField(default=timezone.now) Import old database data Migrate to created = models.DateTimeField(auto_now_add=True) Is this necessary to preserve the old timestamps, or can I start with the desired auto_now_add and import somehow while ignoring this? -
Django: 'weblearn' is not a registered namespace
I am a beginner with Django, and I have been following this tutorial so far - with the small exception of naming the app weblearn instead of polls as done in the tutorial. So far it worked fine, all worked as expected. I am in about the half on the fourth page, and just created the file weblearn/templates/weblearn/results.html, and I double checked that the name polls is not used in any of the code/html. But still, when I navigate to the page http://127.0.0.1:8000/weblearn/1/ as suggested, I get an error In template /Users/alex/Coding/Django/learnit/weblearn/templates/weblearn/detail.html, error at line 5 'weblearn' is not a registered namespace What can I do to debug this error? I have not the slightest idea what the error could mean... detail.html: <h1>{{ question.question_text }}</h1> {% if error_message %}<p><strong>{{ error_message }}</strong></p>{% endif %} <form action="{% url 'weblearn:vote' question.id %}" method="post"> {% csrf_token %} {% for choice in question.choice_set.all %} <input type="radio" name="choice" id="choice{{ forloop.counter }}" value="{{ choice.id }}"> <label for="choice{{ forloop.counter }}">{{ choice.choice_text }}</label><br> {% endfor %} <input type="submit" value="Vote"> </form> -
How to fix this error when running celery task
When I try to run this code it throws an error, I want to run task_number_one and print_test as a periodic task but it throws the same error for both. from celery.task import periodic_task from celery.schedules import crontab from celery import task @task() def task_number_one(): print("Celery Task Working...") @periodic_task(run_every=crontab(minute='10', hour='6,8,9,10,11,12')) def print_test(): print(1) task_number_one.delay() I get this below error [2019-09-18 17:21:17,093: ERROR/MainProcess] Received unregistered task of type 'page.tasks.task_number_one'. The message has been ignored and discarded. Did you remember to import the module containing this task? Or maybe you're using relative imports? Please see http://docs.celeryq.org/en/latest/internals/protocol.html for more information. The full contents of the message body was: '[[], {}, {"callbacks": null, "errbacks": null, "chain": null, "chord": null}]' (77b) Traceback (most recent call last): File "/home/naanal/venv/lib/python3.6/site-packages/celery/worker/consumer/consumer.py", line 559, in on_task_received strategy = strategies[type_] KeyError: 'page.tasks.task_number_one' -
issue in printing dictionary value in django
I have two list li_title and a_href as below. i have combine it in to dictionary but it not print any thing in template file. This is the code in view(value are appended in list with same length) param = {li_title[i] : a_href[i] for i in range(len(li_title))} return render(request, 'index.html', param) This is the code in index.html. {%for i,j in param.items% {{j}} {% endfor %} -
403 Client Error: Forbidden for url: https://api.twitter.com/oauth/request_token - can't sign in with Twitter
I'm trying to add twitter sign in option to my python application and I'm getting following error from web server: GET /social-auth/login/twitter/ HTTP/1.1" 500 103190 403 Client Error: Forbidden for url: https://api.twitter.com/oauth/request_token I work on dev environment django + unicorn with SSL on localhost. I've checked following instruction on Twitter callback url's guide: Don’t use localhost as a callback URL Instead of using localhost, please use a custom host locally or http(s)://127.0.0.1. My callback URL: https://127.0.0.1:8000/social-auth/complete/twitter/ Is it possible to make it work without hosting real domain?