Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
take approved replies in comments
i took approved/published comments. However, all approved or unconfirmed replies appear. i tried this method first comment_replies=Comment.replies.objects.filter(post=post,reply=None,statusc=2).order_by('-date') However it doesn't work (sorry my misspellings) i think this problem is in this code= {% for reply in comment.replies.all %} views.py def post_detail(request,slug): post=get_object_or_404(Post,slug=slug) comments=Comment.objects.filter(post=post,reply=None,statusc=2).order_by('-date') comment_count=len(Comment.objects.filter(post=post, statusc=2)) if request.method=='POST': comment_form = CommentForm(request.POST or None) if comment_form.is_valid(): name=request.POST.get('name') email=request.POST.get('email') comment=request.POST.get('comment') reply_id=request.POST.get('id_comment') comment_qs=None if reply_id: comment_qs=Comment.objects.get(id=reply_id) comment=Comment.objects.create(post=post,name=name,email=email,comment=comment,reply=comment_qs,statusc=1) comment.save() messages.success(request, "Yorumunuz Onaylandıktan sonra yayınlanacaktır") return HttpResponseRedirect(post.get_absolute_url()) else: comment_form=CommentForm() context={ 'post':post, 'comments':comments, 'comment_form':comment_form, 'comment_count':comment_count, } return render(request,'post/post.html',context) models.py class Comment(models.Model): STATUS_C_DRAFT = 1 STATUS_C_PUBLISHED = 2 STATUSES_C = ( (STATUS_C_DRAFT, 'Draft'), (STATUS_C_PUBLISHED, 'Published'), ) post=models.ForeignKey(Post,verbose_name='post',related_name='comment',on_delete=models.CASCADE) name=models.CharField(verbose_name="name",max_length=60,blank=False) email=models.EmailField(max_length=120,blank=False,verbose_name="email") comment=models.TextField(max_length=1000,verbose_name="comment") reply=models.ForeignKey('Comment',null=True,related_name='replies',on_delete=models.CASCADE) date=models.DateTimeField(auto_now_add=True) statusc = models.SmallIntegerField(choices=STATUSES_C,default=STATUS_C_DRAFT) class Meta: verbose_name="Yorum" verbose_name_plural="Yorumlar" def __str__(self): return 'Üst Yorum: %s' % (self.comment) html file comments; {% for comment in comments %} <!-- POST COMMENT --> <div class="post-comment"> <!-- POST COMMENT USERNAME --> <p class="post-comment-username">{{ comment.name }}</p> <!-- /POST COMMENT USERNAME --> <!-- POST COMMENT TIMESTAMP --> <p class="post-comment-timestamp">{{ comment.date |timesince }} Önce</p> <!-- /POST COMMENT TIMESTAMP -->... html file comments reply {% for reply in comment.replies.all %} <div class="post-comment"> <!-- POST COMMENT USERNAME --> <p class="post-comment-username">{{ reply.name }}</p> <!-- /POST COMMENT USERNAME --> <!-- POST COMMENT TIMESTAMP --> <p class="post-comment-timestamp">{{ reply.date|timesince }} Önce</p> … -
How to connect microsoft azure dataware house server with django?
Trying to connect to a datawarehouse. This is the configuration I am using DATABASES = { 'default': { 'ENGINE': 'sql_server.pyodbc', 'NAME': 'dbname', 'USER': 'username', 'PASSWORD': 'pass', 'HOST': 'xyz.database.windows.net', 'PORT': '', 'OPTIONS': { 'driver': 'ODBC Driver 17 for SQL Server', }, }, } When I am trying to run the migrate command its giving me the error that Enforced unique constraints are not supported in Azure Data Warehouse. To create an unenforced unique constraint you must include the NOT ENFORCED syntax as part of your syntax. -
Django Rest Framework: Can't get over strange error
Trying a simple request: urls.py from django.conf.urls import url from django.urls import include, path from rest_framework import routers from django.http import HttpResponse from rest_framework.urlpatterns import format_suffix_patterns from .public_views import NavigationBar router = routers.DefaultRouter() router.register(r'navbar', NavigationBar, basename="NavigationBar") urlpatterns = [ path('', include(router.urls)) ] urlpatterns = format_suffix_patterns(urlpatterns) public_views.py from django.shortcuts import render from rest_framework.views import APIView from rest_framework.permissions import AllowAny from rest_framework.throttling import UserRateThrottle from rest_framework.decorators import api_view, throttle_classes from . view_utils import * class OncePerDayUserThrottle(UserRateThrottle): rate = '1/day' class NavigationBar(APIView): """ obtain up to date navigation bar (or side menu navigation) hierarchy. """ permission_classes = ([AllowAny]) def get(self, request, format=None): """ get user addresses """ return Response("this is a good response") def get_extra_actions(cls): return [] When I API call the /v1/navbar or /v1/navbar/ endpoints (I do have my main urls.py lead all /v1/ traffic to another dedicated urls.py), I am getting the following error: AttributeError at /v1/navbar type object 'NavigationBar' has no attribute 'get_extra_actions' Request Method: GET Request URL: http://web/v1/navbar Django Version: 2.1 Exception Type: AttributeError Exception Value: type object 'NavigationBar' has no attribute 'get_extra_actions' Exception Location: /usr/local/lib/python3.6/site-packages/rest_framework/routers.py in get_routes, line 200 Python Executable: /usr/local/bin/uwsgi Python Version: 3.6.8 Python Path: ['.', '', '/usr/local/lib/python36.zip', '/usr/local/lib/python3.6', '/usr/local/lib/python3.6/lib-dynload', '/usr/local/lib/python3.6/site-packages'] Server time: Tue, 2 Jul … -
How to write a data migration to rename objects in the production database?
I changed the instances of "Discipline Points" to "Accountability Points" in the code but I am unable to rename these objects in the database. In a few spots, I have code that grabs a template named "Accountability Points" but this will fail to find an object matching that query because the name of these objects are not changed in the database. An example of code that grabs this is template = NotificationTemplate.objects.get(name="Accountability Points"). Currently, I'm attempting to write a data migration to rename these objects but I'm kind of unsure exactly how to accomplish this. I haven't found much on how to do this specifically, but I've looked at the RenameField migrations operation and I think the solution to my problem could be something similar. I have also tried grabbing all of the objects with the name "Discipline Points" and think a For loop would work to grab each object and rename it. # Generated by Django 1.11.6 on 2019-05-09 21:05 from __future__ import unicode_literals from django.db import migrations def change_to_accountability(apps, schema_editor): notification = apps.get_model('hr', 'NotificationTemplate') discipline = notification.objects.get(name="Discipline Points") for disc in discipline: disc.new_name = "Accountability Points" disc.save() class Migration(migrations.Migration): dependencies = [ ('hr', '0012_auto_20190509_1705'), ] operations = [ … -
Snippets aren't displayed in the wagtail admin page
I have a snippet called event, After upgrading to wagtail 2.5.1 (Still i am not sure if this issue is related to version 2.5.1) The previous events aren't displayed on the wagtail admin page anymore. However i am able to search for them in the search box.any help is appreciated -
How to change Text field to Buttons
Can any body tell me the best practice or way to change Text field to the Button with value 0 or 1. Let me clear what I want so i have here(see below) django form with the 2 field called Up_vote and Down_vote and when I submit it stores pretty nicely into the Votes table. But what I what is to have two buttons like stacoverflow have for up_vote and down_vote and when someone press on the up_vote it should submit value 1 automatically to the database and when someone press the down_Vote it sould submit the value 0 to the database table. see like this: so basically how i can convert text fields to the two buttons, I dont now how i can do with the javascript or with other method. -
Problems using wildwebmidi midi player
I'm trying to add this github code to my project: https://github.com/yazgoo/wild-web-midi It works perfectly when I try it local, but when I try it in my webpage, based on Django, it throws me the following error: uncaught exception: could not load memory initializer wildwebmidi.js.mem I try to load all the scripts from my static folder. Does anybody know how to manage this problem? I'm not sure if it is because of the URLs or something like that. -
How to export django model to pandas dataframe sorted by specific column
I'm working on a django web app which visualizes data stored in a SQLite in the browser using bokeh. Since I want to display the data as a stacked area plot I concluded it might be helpful to use the pandas library to save the data from my django model to a dataframe before plotting. My Django models.py includes the following model: class Activity(models.Model): def __str__(self): return self.title title = models.CharField(max_length=50) sport = models.ForeignKey(Sport, on_delete=models.CASCADE) date = models.DateField(blank=False) duration = models.FloatField() distance = models.FloatField(blank=True, null=True) description = models.CharField(max_length=50, blank=True, null=True) trace_file = models.ForeignKey(TraceFiles, on_delete=models.CASCADE, blank=True, null=True) Some example data in the SQLite db could look similar to: | id | title | date | duration | sport_id | trace_file_id | description | distance | |--------------------------------------------------------------------------------------------| | 1 | biking01 | 2019-01-01 | 183 | 1 | 16 | NULL | 142 | | 2 | running17 | 2019-01-01 | 45 | 2 | 2 | NULL | 14 | | 3 | biking02 | 2019-01-01 | 67 | 1 | 18 | NULL | 45 | What would be the best way to read from the model and convert the data to a pandas dataframe? For example I have similar … -
Import error while trying to import a variable within a function in another python script
I have created a function in views.py which is def func(request).Basically, I tried using the variable var, in another python file, say z.py, by typing: from views import func but I got the error ImportError: cannot import name func. Please help me out. I want to use the variable var in the other python script, but am getting this error. -
Auto-Scheduling Django Celery Tasks
I have a django project that checks and backs up a large amount of data from user's accounts they've authorized. Is there a smart way to distribute the scheduling, say if I want to do it twice a day as to not overload my celery server? -
How to automatically start download after user clicks download button which triggers bucket event?
I am making a website on django which allows a user to upload a csv file and convert it to json. Whenever a user uploads a csv document a lambda fuction is triggered the moment the file lands on an s3 bucket where it gets converted to json and saved to another bucket. After the function generates a pre-signed url with the following code: uri_duration = 90 s3Client = boto3.client('s3') url = s3Client.generate_presigned_url('get_object', Params = {'Bucket': bucket, 'Key': filekey'}, ExpiresIn = uri_duration) My question is how could I start the download with the aid of the boto3 library automatically now that the pre-signed url is generated`? I appreciate any help you can provide -
Django Import Error. Cannot import name reciever
I'm learning django and while trying to use Signal and receiver, I receive an ImportError. File "/Library/Python/2.7/site-packages/django/dispatch/__init__.py", line 9, in <module> from django.dispatch.dispatcher import Signal, receiver ImportError: cannot import name receiver I've seen this post and I tried deleting and re-adding the django module(s) but nothing happened. What can I do to fix this and make it work? I'm using django-2.3 and python 3.7.3 -
Django GenericRelation for the update_or_create
I have an issue with using GenericRelation with update_or_create. I have the following models: class LockCode(TimeStampedModel): context_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) context_id = models.PositiveIntegerField() context = GenericForeignKey('context_type', 'context_id') class Mission(DirtyFieldsMixin, models.Model): lock_codes = GenericRelation( LockCode, content_type_field='context_type', object_id_field='context_id', related_query_name='mission' ) I try to create or update LockCode using the mission as a key: mission = .... LockCode.objects.update_or_create( context=mission, defaults={ #some other columns there } And I have the FieldError: Field 'context' does not generate an automatic reverse relation and therefore cannot be used for reverse querying. If it is a GenericForeignKey, consider adding a GenericRelation. It works when I use the context_id and context_type explicitly: LockCode.objects.update_or_create( context_id=mission.pk, context_type=ContentType.objects.get_for_model(Mission), defaults={ #some other columns there } Is it something wrong in my configuration? Or it is only single way to use GenericForeignKey for the update_or_create? -
How to run migrate script?
Trying to run python manage.py migrate but getting error as ('42000', '[42000] [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Enforced unique constraints are not supported in Azure SQL Data Warehouse. To create an unenforced unique constraint you must include the NOT ENFORCED syntax as part of your statement. (104467) (SQLExecDirectW)') -
Django - sqlite3.OperationalError unable to open database file [on hold]
I am developing a small app with the django framework and when trying to serve it via apache2 I get the following error: (sqlite3.OperationalError) unable to open database file (Background on this error at: http://sqlalche.me/e/e3q8) My settings.py entry for the database looks like that: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3') } } the db file exists and has the following rights given by chmod: root@myVPS:/var/www/lab# ls -l db.sqlite3 total 30236 -rwxrwxr-x 1 www-data www-data 3018568 Jul 1 22:14 db.sqlite3 the root folder /var/www/lab: drwxrwxr-x 8 www-data www-data 4096 Jul 2 01:15 lab I read that it might be a problem with the rights but I can't seem to find what I did wrong. Traceback: File "/var/www/lab/venv/lib/python3.5/site-packages/sqlalchemy/engine/base.py" in _wrap_pool_connect 2228. return fn() File "/var/www/lab/venv/lib/python3.5/site-packages/sqlalchemy/pool.py" in connect 434. return _ConnectionFairy._checkout(self) File "/var/www/lab/venv/lib/python3.5/site-packages/sqlalchemy/pool.py" in _checkout 831. fairy = _ConnectionRecord.checkout(pool) File "/var/www/lab/venv/lib/python3.5/site-packages/sqlalchemy/pool.py" in checkout 563. rec = pool._do_get() File "/var/www/lab/venv/lib/python3.5/site-packages/sqlalchemy/pool.py" in _do_get 1355. return self._create_connection() File "/var/www/lab/venv/lib/python3.5/site-packages/sqlalchemy/pool.py" in _create_connection 379. return _ConnectionRecord(self) File "/var/www/lab/venv/lib/python3.5/site-packages/sqlalchemy/pool.py" in __init__ 508. self.__connect(first_connect_check=True) File "/var/www/lab/venv/lib/python3.5/site-packages/sqlalchemy/pool.py" in __connect 710. connection = pool._invoke_creator(self) File "/var/www/lab/venv/lib/python3.5/site-packages/sqlalchemy/engine/strategies.py" in connect 114. return dialect.connect(*cargs, **cparams) File "/var/www/lab/venv/lib/python3.5/site-packages/sqlalchemy/engine/default.py" in connect 437. return self.dbapi.connect(*cargs, **cparams) The above exception (unable to open database file) … -
Django: Pre-populate form with request data
I am trying to pre-populate a Django form based on a users POST request data. Am using FormView, so i overide get_initial but request.POST is always empty. I guess am missing something below is snippet from my view def get_initial(self): initial = super(Yo_EnView, self).get_initial() if self.request.POST: initial.update({'src': self.request.src}) return initial -
Django deployment to AWS using wrong python version?
I'm getting this error when deploying a Django 1.11.5, Python 2.7 application to AWS elasticbeanstalk. [2019-07-02T14:39:08.658Z] INFO [2951] - [Application deployment app-1376-190702_143948@1/StartupStage0/AppDeployPreHook/03deploy.py] : Starting activity... [2019-07-02T14:39:32.424Z] INFO [2951] - [Application deployment app-1376-190702_143948@1/StartupStage0/AppDeployPreHook/03deploy.py] : Activity execution failed, because: Collecting git+git://github.com/django-crispy-forms/django-crispy-forms.git@c243b01a41ff2cab28fba219f39f996c1125195d (from -r /opt/python/ondeck/app/requirements.txt (line 19)) Cloning git://github.com/django-crispy-forms/django-crispy-forms.git (to c243b01a41ff2cab28fba219f39f996c1125195d) to /tmp/pip-IgLSZW-build Could not find a tag or branch 'c243b01a41ff2cab28fba219f39f996c1125195d', assuming commit. Collecting app-version==0.2.1 (from -r /opt/python/ondeck/app/requirements.txt (line 1)) Downloading https://files.pythonhosted.org/packages/ac/a7/dedf1c4302ffcd271cdc788308bd0c4ae0c1b6e8aeef63295259213cfa3b/app_version-0.2.1.tar.gz Collecting appdirs==1.4.3 (from -r /opt/python/ondeck/app/requirements.txt (line 2)) Downloading https://files.pythonhosted.org/packages/56/eb/810e700ed1349edde4cbdc1b2a21e28cdf115f9faf263f6bbf8447c1abf3/appdirs-1.4.3-py2.py3-none-any.whl Collecting awsebcli==3.14.1 (from -r /opt/python/ondeck/app/requirements.txt (line 3)) Downloading https://files.pythonhosted.org/packages/9c/63/e05679b01575a4a25f482ea1f0420bf491853c60c71656eb8badd1040e51/awsebcli-3.14.1.tar.gz (233kB) Collecting backports.ssl-match-hostname==3.5.0.1 (from -r /opt/python/ondeck/app/requirements.txt (line 4)) Downloading https://files.pythonhosted.org/packages/76/21/2dc61178a2038a5cb35d14b61467c6ac632791ed05131dda72c20e7b9e23/backports.ssl_match_hostname-3.5.0.1.tar.gz Collecting bleach==2.1.3 (from -r /opt/python/ondeck/app/requirements.txt (line 5)) Downloading https://files.pythonhosted.org/packages/30/b6/a8cffbb9ab4b62b557c22703163735210e9cd857d533740c64e1467d228e/bleach-2.1.3-py2.py3-none-any.whl Collecting blessed==1.14.2 (from -r /opt/python/ondeck/app/requirements.txt (line 6)) Downloading https://files.pythonhosted.org/packages/07/f5/a0e4b579053c7c01186e1a32b25bfad54fa25468e0e489c44572d39d3bf8/blessed-1.14.2-py2.py3-none-any.whl (64kB) Collecting botocore==1.7.7 (from -r /opt/python/ondeck/app/requirements.txt (line 7)) Downloading https://files.pythonhosted.org/packages/5c/64/b351ade40f18a8c05f1dfd231790bfad81cf97196a4ebedc6eee298945d4/botocore-1.7.7-py2.py3-none-any.whl (3.6MB) Collecting cement==2.8.2 (from -r /opt/python/ondeck/app/requirements.txt (line 8)) Downloading https://files.pythonhosted.org/packages/70/60/608f0b8975f4ee7deaaaa7052210d095e0b96e7cd3becdeede9bd13674a1/cement-2.8.2.tar.gz (165kB) Collecting chardet==3.0.4 (from -r /opt/python/ondeck/app/requirements.txt (line 9)) Downloading https://files.pythonhosted.org/packages/bc/a9/01ffebfb562e4274b6487b4bb1ddec7ca55ec7510b22e4c51f14098443b8/chardet-3.0.4-py2.py3-none-any.whl (133kB) Collecting colorama==0.3.9 (from -r /opt/python/ondeck/app/requirements.txt (line 10)) Downloading https://files.pythonhosted.org/packages/db/c8/7dcf9dbcb22429512708fe3a547f8b6101c0d02137acbd892505aee57adf/colorama-0.3.9-py2.py3-none-any.whl Collecting django==1.11.5 (from -r /opt/python/ondeck/app/requirements.txt (line 11)) Downloading https://files.pythonhosted.org/packages/18/2d/b477232dd619d81766064cd07ba5b35e956ff8a8c5c5d41754e0392b96e3/Django-1.11.5-py2.py3-none-any.whl (6.9MB) Collecting django-adaptors==0.2.5 (from -r /opt/python/ondeck/app/requirements.txt (line 12)) Downloading https://files.pythonhosted.org/packages/a6/fe/320a75cbebdca3217765f89ca18d322c3eeec5e994c9ede4fd5d75e0e1c5/django-adaptors-0.2.5.tar.gz Collecting django-appconf==1.0.2 (from -r /opt/python/ondeck/app/requirements.txt (line 13)) Downloading https://files.pythonhosted.org/packages/5b/78/726cdf3e04660560cf25f9def95b8f2736310c581dabed9adfe60154a9f8/django_appconf-1.0.2-py2.py3-none-any.whl Collecting django-axes==2.3.3 (from -r /opt/python/ondeck/app/requirements.txt (line 14)) Downloading https://files.pythonhosted.org/packages/47/1c/956fb482004f92f0b4978251a70142c11ba3ffb3f56a5ee9373efefaca8f/django-axes-2.3.3.tar.gz Collecting django-bootstrap3==9.0.0 (from -r /opt/python/ondeck/app/requirements.txt (line 15)) Downloading … -
Force password change on first login (Django)
A client requires the ability for managers to add users to a company (with a random one time password) where the user must change their password before accessing anything. I am developing the app in Django 2.2 I made a custom user, replacing username with an email address and I added a change_password bool flag to the user. My change_password form/function works properly, but redirecting does not. urls.py path('change-password/', views.change_password, name='change-password'), views.py class Login(LoginView): def form_valid(self, form): # form is valid (= correct password), now check if user requires to set own password if form.get_user().change_password: return HttpResponseRedirect(reverse('change-password')) else: auth_login(self.request, form.get_user()) return HttpResponseRedirect(self.get_success_url()) def change_password(request): if request.method == 'POST': form = PasswordChangeForm(data=request.POST, user=request.user) if form.is_valid(): form.save() request.user.change_password = False request.user.save() update_session_auth_hash(request, request.user) return redirect(reverse('user_view')) else: return redirect(reverse('change-password')) else: form = PasswordChangeForm(user=request.user) args = {'form': form} return render(request, 'users/change_password.html', args) The expected behavior is to redirect to change-password if the change_password flag is True, however, while the app does redirect to change-password, upon Submission the following error is thrown: NotImplementedError: Django doesn't provide a DB representation for AnonymousUser. If I add the decorator @login_required to my change_password function this error goes away, however, I am redirected back to the login page with … -
csv file going from 316 KB to ~3GB during django app run time then back instantly once app is terminated
The explanation is a bit long, but most of this is to give some background regarding my problem (the problem is probably not Python related, but having extra information wont hurt): I am currently working on a django application. The application window (browser) has two iframes each taking 50% of the screen. On the left-hand side there will be snopes (fact-check website) pages displayed and on the right-hand side one of the pages linked in that specific snopes article will be displayed. A form in the bottom of the app will let the user choose and post whether the RHS page is a source of the claim in the snopes article or not (there is also "invalid input" or "I dont know"). Submitting calls a function which tries to get the other links of the current snopes page, and if there is none, get any pages annotated (in this priority) twice, once, or least (so 0 then 3 then 4 .....). This is done by using a count.csv which simple stores how many each page+link combination has been annotated (as snopes articles can repeat and so can linked sites). The header of count.csv is : page source_url count The pages … -
Reverse for 'logout' not found. 'logout' is not a valid view function or pattern name
New to Django, and attempting to learn how to create a signup page through tutorial. Getting this issue despite following exactly what the tutorial is. -
Ansible causes error 500 on save to database
When use ansible playbook to setup server, then send post to database cause error 500. If I setup by myself (from start, on terminal commands) it's work without problem. This is code I use, not full, only part that I was doing by terminal. The system is ubuntu 18.04 - hosts: all vars: host: "{{ ansible_host }}" site_folder: "/home/{{ ansible_user }}/sites/{{ ansible_host }}" repo_url: "https://github.com/ForisTale/Django_TDD.git" tasks: - name: Deadsnakes PPA to get Python 3.7 apt_repository: repo: ppa:deadsnakes/ppa - name: make sure required packages are installed apt: name: ["nginx", "git", "python3.7", "python3.7-venv"] state: present update_cache: yes - name: Create site folders. file: path: "{{ site_folder }}" state: directory - name: Check if .git exists. stat: path: "{{ site_folder }}/.git" register: git_exists - name: If .git exists fetch repository. command: git fetch args: chdir: "{{ site_folder }}" when: git_exists.stat.exists == True - name: If .git don't exists clone repository command: git clone {{ repo_url }} . args: chdir: "{{ site_folder }}" when: git_exists.stat.exists == False - name: Get local hash commit. local_action: command git log -n 1 --format=%H register: commmit_hash - name: Reset git to actualy used commit. command: git reset --hard {{ commmit_hash.stdout }} args: chdir: "{{ site_folder }}" - name: … -
Auth0: How to Submit POST Using M2M Token with React Frontend
I was unable to find any sort of solution on integrating a working POST-request submission, using Auth0's M2M Token Client Credential Flow process, to submit a POST entry to my Django backend from my React frontend. I’ve currently fully built on a setup compromising of the following, with Auth0 somewhat fully integrated: Frontend: React Browser Setup making POST to retrieve AUTH0 token via Auth0 server. React Browser Setup using retrieved M2M Token based on JWT authentication, to execute GET requests to backend for data. Backend: Django Backend Setup authenticating M2M Token with GET requests to release data. The above setup currently works originally without any Auth0 implementation and subsequently, with GET data requests. However, the issue finally popped up recently, when I attempted to make POST data requests. I do realised that given my setup where, request codes based on React, token used retrieved via M2M setup, I was unable to find any sort of solution on integrating a working POST-request submission to my Django backend. let getBackendConfig = { headers: { "Content-Type": "application/json", Authorization: process.env.REACT_APP_JWT_AUTH0_HEADER + " " + auth0Token, }, }; async function submitLocationViaPOST( dataToPOST ) { setIsLocationUploaded("process"); try { Promise.all([ await axios .post(urlSubmitLocationPOSTAPI, dataToPOST, getBackendConfig) .then(response => … -
Tastypie showing totals while paginating
I'm struggling to find a good way of doing this. I seem to just keep hitting tastypie erros (shouting at me for not returning a query set most of the time). So, Im using tastypie to return a block of data: name, sales, revenue bob, 1, 100 sarah,2, 200 This data nicely paginates using the limit/offset query params. In the same table, per column, I'd like to show the totals (for the whole dataset - including what is on later pages in the pagination). Basically: name, sales, revenue 3, 300 bob, 1, 100 sarah,2, 200 I'm struggling to get this to work with in tastypie. I decided to create one resource for the normal data (seen above), and then have a seperate Totals resource that I could call seperatly. So, I tried adding the below to my SalesTotal resource: def get_object_list(self, request): q = super(MyResource, self).get_object_list(request).aggregate(Sum('sales')) return q But this gives me the error "expecting queryset", as this func should return a queryset - so apply_filters can run. So I tried adding this instead: def apply_filters(self, request, applicable_filters): return self.get_object_list(request).filter(**applicable_filters).aggregate(Sum('sales')) This now throws up an error from the Paginator class. Which leads me to the Resources function get_list(), where all … -
django template tag not getting invoked more than once in javascript function
In my django application, I have created a template tag function that generates a random number that I am assigning as random IDs to programmatically generated elements. import os import random from django import template register = template.Library() @register.tag(name="randomgen") def randomgen(parser, token): items = [] bits = token.split_contents() for item in bits: items.append(item) return RandomgenNode(items[1:]) class RandomgenNode(template.Node): def __init__(self, items): self.items = [] for item in items: self.items.append(item) def render(self, context): arg1 = self.items[0] arg2 = self.items[1] if "hash" in self.items: result = os.urandom(16).encode('hex') elif "float" in self.items: result = random.uniform(int(arg1), int(arg2)) elif not self.items: result = random.random() else: result = random.randint(int(arg1), int(arg2)) return result In my html template, I have used the load tag to import the template tag .py file: {% load custom_tag %} On a particular button click, the randomgen() function is invoked only once: $(document).on("click", ".add_div_btn", function() { let random_id = "{% randomgen 100 1000 %}"; <!-- will generate a random number between 10 and 100 --> console.log("random id: ", random_id); }); However, every button click after the first one generates the same number. On checking the console log, i found out that the randomgen() function within the custom_tag.py file was getting called only once. I … -
django MultiValueDictKeyError error at request.FILES['file']
I am new to python/django and unable to figure out the issue. The requirement is to upload a csv file to load the data into the database. I have a custom model for users where the data needs to be loaded. Error seems to be occurring at csv_file = request.FILES['file'] Error- MultiValueDictKeyError at /upload-csv/ 'file' Request Method: POST Request URL: http://127.0.0.1:8000/upload-csv/ Django Version: 2.2.2 Exception Type: MultiValueDictKeyError Exception Value: 'file' Exception Location: D:\djreact\backend\env\lib\site- packages\django\utils\datastructures.py in __getitem__, line 80 Python Executable: D:\djreact\backend\env\Scripts\python.exe Python Version: 3.7.2 Python Path: ['D:\\djreact\\backend\\src', 'D:\\djreact\\backend\\env\\Scripts\\python37.zip', 'D:\\djreact\\backend\\env\\DLLs', 'D:\\djreact\\backend\\env\\lib', 'D:\\djreact\\backend\\env\\Scripts', 'd:\\python\\python37\\Lib', 'd:\\python\\python37\\DLLs', 'D:\\djreact\\backend\\env', 'D:\\djreact\\backend\\env\\lib\\site-packages'] Server time: Tue, 2 Jul 2019 12:49:52 +0000 View.py - def user_upload(request): template="user_upload.html" prompt = { 'order': 'order of csv should be first_name, last_name, email' } if request.method == "GET": return render(request, template, prompt) csv_file = request.FILES['file'] data_set = csv_file.read().decode('UTF-8') io_string = io.StringIO(data_set) next(io_string) for column in csv.reader(io_string, delimiter=',', quotechar="|"): _, created = User.Objects.update_or_create( first_name = column[0], last_name = column[1], email = column[2] ) return render(request, template) template - user_upload.html {% if messages %} {% for message in messages %} <div> <strong>{{message|safe}}</strong> </div> {% endfor %} {% else %} {{order}} <form method="post" encrypt="multipart/form-data"> {% csrf_token %} <label> Upload a file </label> <input type="file" name='file'> </br> …