Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django , react , redux authentication token is null
im new to react and redux , i have been trying to utilize django as my backend , react as my frontend and redux as my local storage to store authentication states. However i have encountered an error and im not too sure how to debug this. There is no error messages , just that i am unable to pass the token into my components. index.js import React from 'react'; import ReactDOM from 'react-dom'; import App from './App'; import registerServiceWorker from './registerServiceWorker'; import { createStore, compose, applyMiddleware } from 'redux'; import { Provider } from 'react-redux'; import thunk from 'redux-thunk'; import reducer from './store/reducers/auth'; const composeEnhances = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose const store = createStore(reducer, composeEnhances( applyMiddleware(thunk) )); const app = ( <Provider store={store}> <App /> </Provider> ) ReactDOM.render(app, document.getElementById('root')); registerServiceWorker(); App.js import React, { Component } from 'react'; import { BrowserRouter as Router } from 'react-router-dom'; import { connect } from 'react-redux'; import BaseRouter from './routes'; import 'antd/dist/antd.css'; import * as actions from './store/actions/auth'; import CustomLayout from './containers/Layout'; class App extends Component { componentDidMount() { this.props.onTryAutoSignup(); } render() { return ( <div> <Router> <CustomLayout {...this.props}> <BaseRouter /> </CustomLayout> </Router> </div> ); } } const mapStateToProps = state => { return … -
Do I really need to use {% load static %} in Django Templates?
I am using Django 3, the latest version. I have defined the static files directories properly as required. Currently to display an image, both the following source codes work fine. Code 1: <img src="static/img/logo.png"></img> Code 2: {% load static %} <img src="{% static 'img/logo.png' %}"> </img> Since both the code snippets are working and running fine without any problems, I am wondering why not to simply use the way of Code 1 above and refrain from the extra lines of Code 2. Which one would be beneficial and why? Please guide. -
django.urls.exceptions.NoReverseMatch on second level context
I believe my situation is different to other questions and I've tried multiple other answers to no avail. I have a config with a uuid pk. On my list of configs, one can add, edit, delete a config, if you click a config name, it doesn't take you into a detail of the config itself but rather a view of data in other models that references the config as a foreign key (i.e. data "in" that configuration). Within that configuration, one can CRUD each model. I have just started adding the "Add" buttons but get a NoReverseMatch exception. I think this is something to do with my URLs but can't work it out. I know I need to somehow pass the pk from the config to the next view. In addition, when creating an entry for each model, the pk from the config needs to automatically save as a foreign key of the new item (in the background). URLS.PY # My configuration list, and CRUD (this works) path('configurations/', ConfigurationsListView.as_view(), name='configurations'), path('configurations/create/', views.ConfigurationCreate.as_view(), name='configuration_create'), path('configurations/<uuid:pk>/update/', views.ConfigurationUpdate.as_view(), name='configuration_update'), path('configurations/<uuid:pk>/delete/', views.ConfigurationDelete.as_view(), name='configuration_delete'), # My configuration detail view (actually a view of data with the config as a foreign key) path('configurations/configuration/<config_id>', views.ConfigurationDetailView.as_view(), name='configuration_detail'), # … -
How to run a cronjob in a Django app running on nginx uwsgi
I have a django app running on a webserber with nginx and uwsgi. On my local server the crons are working. i add it with python3 manage.py crontab add command. I guess it doesnt work this way on the weberserver as it's not working when i try. I can't find / figure out how to configure it properly. Maybe someone can enlight me ? Thanks -
Django: not able to run application using uwsgi
I ma trying to run django application using uwsgi but it throws continuously one error : not able to import site module the issue is was previously running it under python2.7 env but then i switched to virtual env with python3.6 and after that i am not able to run this project under python3.6 env it always runs in 2.7 I have tried all the tutorials but i'm not able to get the result this is my uwsgi.ini file : [uwsgi] # telling user to execute file # telling group to execute file #gid = webapps # name of project you during "django-admin startproject <name>" project_name = xyz_dev # building base path to where project directory is present [In my case this dir is also where my virtual env is] base_dir = /home/ubuntu/croydoner/%(project_name) # set PYTHONHOME/virtualenv or setting where my virtual enviroment is # WSGIPythonPath = /usr/local/lib/python2.7/dist-packages/ virtualenv = /home/ubuntu/croydoner/venv/ # plugins-dir = /usr/local/uwsgi-2.0.18/plugins/python # plugins = python3.6 # unprivileged-binary-patch = /home/ubuntu/croydoner/venv/bin/uwsgi # changig current directory to project directory where manage.py is present chdir = %(base_dir) # loading wsgi module wsgi-file = %(base_dir)/demo/wsgi.py http = :8090 # enabling master process with n numer of child process master = true processes … -
DRF explicit ordering direction
Im looking for a solution for DRF where I would get query like this: ..../?sort=foo&order=asc/desc I was able to change order param to "sort" but I dont know how to add explicitly "&order=asc" except current solution which uses "-" before column. thank you in advance. -
convert mp3 file to wave and send via request django
so i want to send auido file of mp3 type to my backend which is a Django and i want to convert it to wav file in the django backend and return it to the front end my problem is how to do it directly without saving it in my current folder because i want to deploy it later in heroku ijust started learnig Django the problem i am facing is in converting and return it as a request HTTP i tried sound=pydub.AudioSegment.from_mp3(mp3_file) sound=sound.set_frame_rate(8000) sound.export(wav, format="wav") but the problem that sound.export save it in my current folder and i have to send it back to my frontend as a HTTP request and i have to do it a lot so its not ok to save it each time in my folder -
Set default tags in Django/Wagtail
I want to be able to set a list of default tags using Taggable Manager. city_region_tags = TaggableManager(through=CityRegionSnippetTag, blank=True) The CityRegionTableSnippetTag is - class CityRegionSnippetTag(TaggedItemBase): content_object = models.ForeignKey( 'CityRegionSnippet', on_delete=models.CASCADE, related_name='tagged_city_region' ) Ideally I would pass a list of default tags e.g. tag_list = ['Spatial Patterns', 'Functional dynamics', 'Social-eco dynamics', 'Global-local dynamics'] and so on. Is there a way to do this? I had a look at custom tagging here and doesn't appear to be what I want to do - (https://django-taggit.readthedocs.io/en/latest/custom_tagging.html#) Documentation on tags in forms shows what the tags would look like in a list but that is after user input. I want to be able to put these tags in before the user gets there from the tag_list - (https://django-taggit.readthedocs.io/en/latest/forms.html#tags-in-forms) -
Django - best way to update a summary stats table based on incoming API data
Background: I've got a Django project which uses the restful api to send in user data. This data comes from a few different devices, and consists of the player's name and a score. A version of the models is shown below. class User(models.Model): full_name = models.TextField(null=True, blank=True) device = models.TextField(null=True, blank=True) class Score(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="scores") score = models.CharField(max_length=64, blank=True, null=True) timestamp = models.DateTimeField(null=True) I now want the site to calculate some user summary statistics based on the scores, and store them in another table that I can reference elsewhere on the site. This will be called something like UserStats, and contains data that can't just be aggregated by querying the scores. Things like number of games, that will require processing through the scores. class UserStats(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="stats") number_of_games = models.IntegerField(default=0) Question: My question is, what is the best way of processing the incoming Scores on the server? Essentially once a new score appears I want to process it and update the fields in the UserStats model. Methods I'm aware of: Add the code to the score api view. So when a score is submitted, it checks the UserStats model and creates or updates it. … -
Django Rest Framework ,logic of Like button for blog posts
I have a Django Rest Framework project, users can post,comment any post and like any post. I can't figure it out the logic in models.py from django.db import models from django.contrib.auth.models import User class Post(models.Model): title = models.CharField(max_length=100) body = models.CharField(max_length=100) post_author = models.ForeignKey(User,on_delete=models.CASCADE,related_name='posts') def __str__(self): return self.title class Comment(models.Model): body=models.CharField(max_length=100) commet_post = models.ForeignKey(Post,on_delete=models.CASCADE,related_name='comments') comment_author = models.ForeignKey(User,on_delete=models.CASCADE) def __str__(self): return self.body class Like(models.Model): like_post = models.ForeignKey(Post,on_delete=models.CASCADE) like_author=models.ForeignKey(User,on_delete=models.CASCADE) created = models.DateTimeField(auto_now_add=True) -
How to save the data we get from GET request to models in Django?
I am using APIView of Django restframework for my API. my serializer file: class HelloSerializer2(serializers.Serializer): '''Searlizes id field for viewing details ''' id = serializers.CharField(max_length=None, min_length=None, allow_blank=False, trim_whitespace=True) I want to save the response i am getting in database. How do i do that?? the response is like this { "json": { "ver": "1.0", "version": "1.0", "name": "xxxxx", "attr_names": [ "xxxxx" ], "main_id": "xxxxxxx", "seqNo": 1234 } } model.py : class Table(models.Model): """Database model for saving """ #id = models.IntegerField() main_id = models.TextField() name = models.TextField() version = models.TextField() attributes = models.TextField() seq_num = models.IntegerField() def __str__(self): return self.main_id -
I'm trying to complete the Django website tutorial, following the youtube tutorial - and at the beginning I have this "error"
The tutorial writes in "source env/bin/activate" When I write it in this is what comes out: (venv) C:\Users\user\PycharmProjects\FirstProject>source env/bin/activate 'source' is not recognized as an internal or external command, operable program or batch file. He uses a mac and I use Windows 10, do I need a different line of code? -
Uncaught ReferenceError: function is not defined - when calling function from outside jQuery ajaxSetup
I am including the below code (found here Django CSRF check failing with an Ajax POST request) to get my AJAX requests to send back the CSRF token in he custom X_CSRFTOKEN header - it was working fine for me so far: $.ajaxSetup({ beforeSend: function(xhr, settings) { 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]); if (cookie.substring(0, name.length + 1) == (name + '=')) { cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); break; } } } return cookieValue; } if (!(/^http:.*/.test(settings.url) || /^https:.*/.test(settings.url))) { xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken')); } } }); But now, when calling the getCookie() function below, I get the error Uncaught ReferenceError: getCookie is not defined at previous_selection: var preselection = localStorage.getItem("preselection"); function previous_selection () { if (localStorage.getItem("preselection") != null) { const data = new FormData(); data.append("preselection", preselection); const request = new XMLHttpRequest(); request.open('POST', '/prebasket'); request.setRequestHeader("X-CSRFToken", getCookie('csrftoken')); request.send(data); return false; } } previous_selection(); Is it a scope problem? If so, why did the exact same ajaxSetup-code work in a previous getCookie() call I had out of a different script? For completion's sake: I am trying to use/access … -
Unable to get Primary Key as a model instance
I have two models Role and User. When use the object's get() method with the Role model like this - role= Role.objects.get(pk=1) It returns id as an instance of Role like this - <Role: Role object (2)> But when I do the same thing with User model like this - user= User.objects.get(pk=1) It returns an email as an instance of User model like this - <User: pqw109@inc.com> How can I make User model return an id as an instance, exactly like Role model. -
nuxt.js config token type for JWT header
so i am a django app that i build using rest freamworks and djoser i am using jwt auth for my app. I did apply cors for the app. I am tring to connent to the user using nuxt.js the problom i am facing is in the token type. i can send the request form the client to the server and get the response which is a object that has two keys: "access", "refresh" token. when i send the request to check the token the request need to look like that url with the header that has the key Authorization and the value is "JWT toekn". my issue is while sending the request for the nuxt app i need to config nuxt.js.config token type i tried JWT, Brear, Token, and access but none of them seems to work. i see in the application tag and cookie that the token is undifiend and i get 401 Unauthorized Error. I will send the python code and nuxt code here The first file will be the request test with python. The second is the setting from my django app. The third will be the nuxt config . And the last will show just … -
Perform sum operation in django template
I have a checkbox pagination where user select some of the option after user submit he get redirect to the page where he sees what all item he selected and value of the item , I want to get the sum of the value of item he selected . <tbody> {% for booktest in var1 %} <tr> <td width="100%">{{ booktest }}</td> <td>{{ booktest.rate }}</td> </tr> {% endfor %} </ul> </tbody> Above is the HTMl code where i get select item and i want to add all value in {{ booktest.rate }} views.py def ResultTest(request): var = request.POST.get('selectedTests') booktests = BookTest.objects.filter(test__in=var.split(',')) views.py from where i get selected checkbox data. -
Getting error while communicating django channel with Redis
enter image description here I am trying to crate a chatapp.I referred to django tutorial provided in documentation.How to get rid of this error?? -
Can't show new added attr in template from object in Queryset in UpdateView (Django)
I'm trying to output a list of objects that are affected by this object. The main model doesn't affect the additional one, so I'm trying to add the list to the new object attribute. When I output .__dict__ of an object after adding a new attribute, everything is OK, but the template outputs a blank. How do I fix this? My code in UpdateView: def get_queryset(self): print('ID: ', self.kwargs['adapter_account_id']) deals = Deal.objects.filter(adapter_account=self.kwargs['adapter_account_id']) adapter_acc = AdapterAccount.objects.filter(id=self.kwargs['adapter_account_id']) for obj in adapter_acc: obj.deals = deals print(adapter_acc[0].__dict__) return adapter_acc Output for .__dict__: {'_state': <django.db.models.base.ModelState object at 0x7fa0590547c0>, 'id': 13, 'adapter_id': 9, 'params': {'secret': 'secret', 'pay_gate': 'VV', 'product_id': '10731', 'merchant_id': '1998'}, 'deals':<QuerySet [<Deal:#28>, <Deal: #30>]>} My try to render value in template: {{ adapteraccount.deals}} For example, {{ adapteraccount.params}} works fine. -
wagtailmenus - iterating submenu items
I'm getting started with wagtail, (and Django), and using wagtailmenus. I'm having trouble getting the submenu object that I (presumably) iterate to build submenus where required. main_menu.html {% for item in menu_items %} <li class="dropdown nav-item"> <a class="nav-link href="{{ item.href }}">{{ item.text }}</a> {% if item.has_children_in_menu %} {% sub_menu item %} {% endif %} </li> {% endfor %} This code renders the top level items fine, and recognises when the submenu is required, and references the correct template. sub_menu.html <div class="dropdown-menu"> <a href="{{ item.href }}" class="dropdown-item"> {{ item }} </a> </div> However, item is the previous item - so I just get the top level item repeated, once. As far as I can figure out, I need to get a iterable object of the sub menu, and build it in the same way as the top level menu. Something like, pseudo_sub_menu.html {% for sub_item in item %} <a href="{{ sub_item.href }}" class="dropdown-item"> {{ sub_item.text }} </a> {% endfor %} But that returns 'MainMenuItem' object is not iterable How can I go about this? -
How to get the desired column name?
In my app/views.py, I have got all the column names: columns = MyModel._meta.get_fields() How to get the desired column names here? Eg. How to cut the above columns to get the last 10x column names? How to get the 1st + 3nd + 6th + 10th column names together? Thanks for the help! -
Ajax & Django to calculate a price before submitting to database
I have this so far. But I want to take the input fields and add first with the calculate button. I have successfully implemented a Submit button, but the problem I run into is I'm trying to first calculate and display before submitting to my database. This is what I have so far, but I'm not sure how to create the html function to add them all up.. Book Price: $10 (input field) Delivery charge: $3 (input field) Delivery type: $5 (input field) Final Result: $18 (result of adding the fields above when user clicks the calculate button) [calculate] [submit] submit button will finalize the results and send the values to the database. This is my model for the table class book(models.Model): user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, ) book_price = models.IntegerField() delivery_charge = models.IntegerField() delivery_type = models.IntegerField() final_result = models.IntegerField() def save(self, *args, **kwargs): self.final_result = self.book_price + self.delivery_charge + self.delivery_type print(self.final_result) super(book, self).save(*args, **kwargs) views.py for the form def final_price(request): response_data = {} if request.method == 'POST': form = RequestForm(request.POST) book_price = request.POST.get('book_price') delivery_charge = request.POST.get('delivery_charge') delivery_type = request.POST.get('delivery_type') response_data['book_price'] = book_price response_data['delivery_charge'] = delivery_charge response_data['delivery_type'] = delivery_type book.objects.create(book_price=book_price, delivery_charge=delivery_charge,delivery_type=delivery_type) return JsonResponse(response_data) if form.is_valid(): instance = form.save(commit=False) instance.user = … -
Django use old database backup
I have 2 servers: production (master branch) and test (dev branch). On my local machine I work on dev branch, it has all the latest features and the newest DB schema. Now I need to inspect some problems that occurred on the production server. For that I want to download DB backup from production server onto my local machine and do some manipulations with it. On my local machine I have a postgres running and that is where my local DB is stored. What I usually do is drop local DB, apply the backup instead of what I've deleted and that works fine. I am able to work with the database. However, if the production database is several migrations behind the local database (which happens often) than I get Django migration errors when I try to apply all the latest migrations. The errors are usually like some_relation / some_column already exists. Probably, that happens because Django tries to apply all migrations starting at the very first one. To work this around I usually run all migrations with --fake option, than make small changes in models (like blank=True), just enough to create new migration which I apply then. After that I … -
Can I convert html in dict?
How can I paste/convert code html. I get code from file .txt and function like {for} etc. it's paste as text. respone = { "Pic" : str(File_read_to_div.readline()), "h1" : str(File_read_to_div.readline()), "WpisChild" : File_read_to_div.readline(), "Messags" : list(Messages) } return JsonResponse(respone, safe=False) And now in site I see {for} as text in div. Objects are not displayed. -
Django template data update using ajax
I am trying to update my data periodically (10 seconds) on a Django template using ajax scripts. I am relatively new in developing the front end. Using other articles, I am able to do so. But everytime page refreshes, multiple threads for page refreshing are created and update requests are doubled every 10 secods. Following is my django template snippet: <body id="page-top"> <div class="table-responsive"> <table class="table table-striped"> <thead> <tr class="table-info"> <th style="text-align:center">Parameter</th> <th style="text-align:center">A</th> <th style="text-align:center">B</th> </tr> </thead> <tbody> {% for para, details in manualData.items %} <tr> <th style="text-align:center" scope="row">{{ details.1.name }}</th> {% for key, entity in details.items %} <td style="text-align:center"> <font color="white" size="4px">{{ entity.value }}</font> </td> {% endfor %} </tr> {% endfor %} </tbody> </table> </div> </body> I am using ajax script as follows: <script type="text/javascript"> function refresh() { var_ref = $.ajax({ success: function (data) { $('#page-top').html(data); } }); } $(function () { setInterval('refresh()', 10000); }); </script> Conclusively, all I need is to once the refreshing process is defined, new process should not be created or else past process to be aborted if new process is to be defined. Kindly help me to attain the same. Thanks in advance Nakul -
Django: How to load dynamic data to chartjs
I want to load my models' data into a chart, using chartjs. Curiously, only the 'dummy-data' is working, that looks as follow: data: { labels: ['red', 'Blue', 'Yellow', 'Green', 'Purple', 'Orange'], datasets: [{ label: '# of Votes', data: [12, 19, 3, 5, 2, 7], My raw data looks like this: labels = ['/truck-alerts-analysis/fleet-history', '/truck-alerts-analysis/map-view', '/truck-alerts-analysis/fleet-status', '/truck-alerts-analy sis/truck-history', '/truck-alerts-analysis/truck-history', '/truck-alerts- analysis/fleet-status', '/truck-alerts-analysis/truck-histor y', '/setup/QCFcKp', '/reset-password', '/login'] data = [251, 243, 238, 220, 174, 158, 151, 88, 87, 86] Using django, I defined these values in views.py as follow: def pages(request): showData = start_date pageV = PageView.objects.all() FPage = FinalPage.objects.all() typeUser = list(FinalPage.objects.values_list('page', flat=True)) count = list(FinalPage.objects.values_list('sessionCount', flat=True)) # manipulation in order to get the right labels that I want t=[] for i in typeUser: new = i.split("?", 1)[0] t.append(new) k = t[-10:] c = count[-10:] # Where the labels and data is being returned return render(request, 'gaapp/pages.html', {"showData": showData, "labels": k, "data": c}) The curious behaviour is that, when calling for {{labels}} and {{data}} in the HTML file (where the chart is being processed), only the {{data}} is being excepted? In other words, the {{labels}} aren't valid. I don't understand why? Please help My HTML: <div class="PageMines"> <canvas id="myChart1" width="40" height="30"></canvas> …