Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django searches for url which does not exist in my current project. Why is this happening? The project used to exist but no longer
i used to have an app in a project called catalog but i have deleted the project upon completion. Currently i have started a new project, but i have realised that the django searches for catalog which was an app in the old project. Instead of django searching for urls in my new project. i uninstalled anaconda and reinstalled it with django to see whether that will solve the issue but it still remains. One thing i noted was that in the previous project which contained catalog as a app i imported the Redirect View and redirected the homepage which was empty to the url of the app so that it rather acts as the index. Now whenever i run the server it points to the page where the redirect was done in my current project which does not exist throwing the exception below. Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/catalog/ Using the URLconf defined in main.urls, Django tried these URL patterns, in this order: admin/ ^media/(?P<path>.*)$ The current path, catalog/, didn’t match any of these. You’re seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django … -
Django ArrayField creating three Charfields within?
It's my first time trying to pass in a field type within Django models.py where I can create a list within an arrayfield. For example I want to create.. neighborhood = Arrayfield(models.Charfield(max_length=100)) But within neighborhood I want to have the drop down choices of... area = [Brooklyn, Manhattan, Queens] How do I do this within models.py, is area suppose to be it's on class within my models.py? I am using Postgres SQL. -
How to resolve specific fields.E304 error
I'm learning to create custom user form on django and the procedure is still not very clear to me. So, I'm following a tutorial. However, when I try to make migrations I encounter the follow error, but the instructor's code program worked. I don't understand why mine is throwing back an error message. Please I need some clarification. I checked the answer to similar question online but I couldn't identify my mistake model.py from django.db import models from django.contrib.auth.models import (AbstractBaseUser, BaseUserManager, PermissionsMixin) from django.utils.translation import gettext_lazy as _ from django_countries.fields import CountryField class CustomAccountManager(BaseUserManager): def create_superuser(self, username, email, password, **other_fields): other_fields.setdefault('is_staff', True) other_fields.setdefault('is_superuser', True) other_fields.setdefault('is_active', True) if other_fields.get('is_staff') is not True: raise ValueError( 'Superuser must be assigned to is_staff=True.') if other_fields.get('is_superuser') is not True: raise ValueError( 'Superuser must be assigned to is_superuser=True.') return self.create_user(email, username, password, **other_fields) def create_user(self, email, username, password, **other_fields): if not email: raise ValueError(_('You must provide an email adresss')) email = self.normalze_email(email) user = self.mode(email=email, username=username, **other_fields) user.set_password(password) user.save() return user class UserBase(AbstractBaseUser, PermissionsMixin): username = models.CharField(max_length=30, unique=True) first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) email = models.EmailField(max_length=254, unique=True) company = models.CharField(max_length=50) license_number = models.CharField(max_length=50) country = CountryField() state = models.CharField(max_length=50) city = models.CharField(max_length=50) address = … -
Multiple LEFT JOIN with GROUP CONCAT using Django ORM
These are my 2 Django models: class Brand(models.Model): brand_no = models.CharField(max_length=100, unique = True) class Meta: db_table = 'brand' class BrandWhereUsed(models.Model): # Brand is a component of parent brand brand = models.ForeignKey(Brand, related_name="where_used", on_delete=models.CASCADE) parent_brand = models.ForeignKey(Brand, on_delete=models.PROTECT) class Meta: constraints = [ models.UniqueConstraint(fields=['brand', 'parent_brand '], name='brand_parent') ] db_table = 'brand_where_used' And I would like to do convert this SQL query to Django ORM, not raw query: SELECT t1.id, t1.brand_no , GROUP_CONCAT(t2.parent_brand_id) AS where_used , GROUP_CONCAT(t3.item_no) AS where_used_brand_no FROM brand AS t1 LEFT OUTER JOIN brand_where_used AS t2 ON (t2.item_id = t1.id) LEFT OUTER JOIN brand AS t3 ON (t3.id = t2.parent_brand_id) GROUP BY t1.id I tried this thread :GROUP_CONCAT equivalent in Django . But seems like it generated incorrected result query. Could you please help me on this? -
Django / React - Production API URL routing issues
I have a backend Django REST API that also helps serve my React frontend. I currently have an issue with my API requests url paths to my Django API in production for every page except my home page... API URL's that work: I'm able to visit my home page, within my home page, I have a GET request to my API which works great and loads data as expected. This is the only working GET request of my website because the API URL path is correct to my urlpatterns syntax. API URL's that DON'T work: The issues arise when I visit a page OTHER than the home page of my React app. My API requests to Django on other pages are using the wrong URL path according to my network panel (they are also responding with index.html), which has me believe I set up my django URLs wrong. Please checkout my configuration below: main urls.py: def render_react(request): return render(request, "index.html") #<---- index.html from React urlpatterns = [ path('auth/', include('drf_social_oauth2.urls', namespace='drf')), path('admin/', admin.site.urls), path('api/', include('bucket_api.urls', namespace='bucket_api')), path('api/user/', include('users.urls', namespace='users')), path('api-auth/', include('rest_framework.urls', namespace='rest_framework')) ] urlpatterns += [ re_path('',render_react) #<---- Serving React index.html ] Here is an example of the issue: When I … -
Django: Why does my Django model get "on_deleate" error
I know that ForeignHey of Django 2.2 require "on_delete" parameter and defined it in my model. Nevertheless, I got the error "TypeError: init() missing 1 required positional argument: 'on_delete' " Please tell me the resolution of this error I use Python3.7 and Django 2.2 My model is from django.db import models from treebeard.mp_tree import MP_Node from django_model_to_dict.mixins import ToDictMixin class Project(ToDictMixin,models.Model): name=models.CharField(max_length=200) def __str__(self): return self.name class Task(MP_Node, ToDictMixin): name=models.CharField(max_length=100) start=models.DateTimeField() end=models.DateTimeField() progress=models.PositiveIntegerField(default=0) custom_class=models.CharField(max_length=20,null=True, blank=True) project = models.ForeignKey( Project, related_name="tasks", on_delete=models.CASCADE, ) def __str__(self): return self.name and error is File "/Users/gensan/python/basic3_7/lib/python3.7/site- packages/django_model_to_dict/models.py", line 127, in <module> class Order(models.Model, ToDictMixin): File "/Users/gensan/python/basic3_7/lib/python3.7/site-packages/django_model_to_dict/models.py", line 134, in Order customer = models.ForeignKey(to=Customer, verbose_name=_('customer'), related_name='orders') TypeError: __init__() missing 1 required positional argument: 'on_delete' Thank you -
Django APScheduler job hang up without Error
I use django-apscheduler to manage task. But after the server start for a while, the job stop working and when I check the django admin page. There is no error log, too. This is my runapscheduler.py ... def start(): scheduler = BackgroundScheduler(timezone=settings.TIME_ZONE) scheduler.add_jobstore(DjangoJobStore(), "default") scheduler.add_job( process_tt_file.start_tt_process, trigger=CronTrigger(minute='5,20,35,50', hour='*'), id='process_tt_file', max_instances=1, replace_existing=True ) logger.info("Added job 'process_tt_file'.") ... try: logger.info("Starting scheduler...") scheduler.start() except KeyboardInterrupt: logger.info("Stopping scheduler...") scheduler.shutdown() logger.info("Scheduler shut down successfully!") ... this is my urls.py where I start apscheduler when django start ... urlpatterns = ... runapscheduler.start() The task should run every 15min. But somehow apscheduler didn't fire the job until I check the status. How should I prevent this? -
Django HTML Dropdown
I am trying to make a html dropdown and pass the values into Postgrase SQL database. My dropdown values are being retrieved from another database table. It gives me a MultiValueKeyDictError every time I submit the form. I know I can use forms.py to do the same thing but I want to explore the HTML way of doing this. My HTML file <form action = "" method = "post"> {% csrf_token %} <label for = "LogType"></label> <input id ="LogType" type = "text" value = "{{ user.department }}"> <label for ="DelayCategory">Delay Category</label> <select id = "delaycategory" class = "form-control"> {%if user.department == 'TechAssembly'%} {%for techdelay in techdelay%} <option value = "{{ techdelay.DelayCode }}">{{ techdelay.DelayCategory}}</option> {%endfor%} {%endif%} {%if user.department == 'Testing'%} {%for testdelay in testdelay%} <option value = "{{ testdelay.DelayCode }}">{{ testdelay.DelayCategory}}</option> {%endfor%} {%endif%} </select> <label for = "iterations">Iterations</label> <input type = "number" id = "iterations"> <center><input type="submit" value=Submit id = "button"></center> </form> My Views.py file def rulesView(request, user_name): testdelay = TestingDelayCategory.objects.all() techdelay = TechDelayCategory.objects.all() if request.method == "POST": rulesnew = rules() rulesnew.DelayCategory = request.GET['DelayCategory'] rulesnew.LogType = request.POST('LogType') rulesnew.iterations = request.POST('iterations') rulesnew.save() context = { 'techdelay':techdelay, 'testdelay':testdelay, } return render(request, 'rules/rules.html', context) -
No "Access Control-Allow-Origin' header is present even when Django CORS_ORIGIN_ALLOW_ALL = True
I just deployed my React/Django web app to a VM. Everything worked fine on my local before deployment. Just to test, I attempted to use my site with the development server. When my React code (statically bundled in the Django app) makes the following api call to http://localhost:8000/token-auth/ (this endpoint is automatically constructed from django rest_framework.views.obtain_jwt_token): fetch('http://localhost:8000/token-auth/', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(data) }) the following error message is received: Access to fetch at 'http://localhost:8000/token-auth/' from origin 'http://34.XXX.XXX:8000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled. Note that the curl from an external origin (my local machine pinging the vm) works fine: curl -X POST -H "Content-Type: application/json" -d '{"username": "wgu_test_user", "password": "fgDq7YUmcd3n"}' http://34.XXX.XXX:8000/token-auth/ so this error seems solely to do with CORS. Strangely, after I whitelisted the domains, and even used CORS_ORIGIN_ALLOW_ALL = True in my settings.py, I still get the same problem. I did restart the development server after changing this file and saving. As one possible solution, … -
How to handle several search fields on one page using raw sql?
I have for now two serach field(planning to add more) and I want to use only raw sql whem filtering the objects(I know that Django provides ORM which makes life so much easier, but in my work right now I need to use SQL) I know how to do it with ORM in Django,like this: def my_view(request): value_one = request.GET.get("value_one", None) value_two = request.GET.get("value_two", None) value_three = request.GET.get("value_three", None) objects = MyModel.objects.all() if value_one: objects = objects.filter(field_one=value_one) if value_two: objects = objects.filter(field_two=value_two) if value_three: objects = objects.filter(field_three=value_three) But is there a way to use SQL instead of filtering? def profile(request): cursor = connection.cursor() value_one = request.GET.get("searchage", None) value_two = request.GET.get("search", None) objects= cursor.execute('SELECT * from People p JOIN Jobs j on p.JobId = j.Id ') objects = dictfetchall(cursor) if value_one: objects = cursor.execute('SELECT * from People p JOIN Jobs j on p.JobId = j.Id WHERE p.Age = %s',[value_one] ) if value_two: objects = ??? return render(request,'personal.html', {'value1':value_one, 'value2':value_two, 'objects':objects}) I have only one idea and it's to have if clause like this if value_one and value_two: .. elif value_one and !value_two: ... elif !value_one and value_two: But if I have more than 2 search fields it gets kind of difficult … -
Taking input as argument for another script in Python
I have a python script with a main method that takes input. Now I need to use this input as an argument for another script without a main method. The first script is Django so it takes input on a webpage and when this input is submitted, the second script should take this input as a parameter and execute itself. The second script is a socket listener. Can someone help with this? Thank you -
Comment not being added to the database
I am working on a movie website with Django and I'm trying to add user comments. Only the registered users should be allowed to comment. I have the following so far: models.py: class Comment(models.Model): movie = models.ForeignKey(Movie, related_name = "comments", on_delete=models.CASCADE) user = models.ForeignKey(User, on_delete = models.CASCADE) content = models.TextField() date_added = models.DateTimeField(auto_now_add=True) def __str__(self): return '%s - %s' % (self.movie.title, self.name) forms.py class CommentForm(forms.ModelForm): content = forms.CharField(label ="", widget = forms.Textarea( attrs ={ 'class':'form-control', 'placeholder':'Comment here!', 'rows':5, 'cols':50 })) class Meta: model = Comment fields =['content'] views.py class MovieDetailsView(generic.DetailView): model = Movie template_name = "details.html" def comment(request, id): movie= Movie.objects.get(id) if request.method == 'POST': cf = CommentForm(request.POST or None) if cf.is_valid(): content = request.POST.get('content') comment = Comment.objects.create(movie = movie, user = request.user, content = content) comment.save() return redirect(movie.get_absolute_url()) else: cf = CommentForm() context ={ 'comment_form':cf, } return render(request, 'details.html', context) details.html <form method="POST" action="#" class="form"> {% csrf_token %} {{comment_form.as_p}} <button type="submit" class="btn btn-primary btn-lg">Submit</button> <textarea id="text" name="text" class="form__textarea" placeholder="Add comment"></textarea> <button type="button" class="form__btn">Send</button> </form> The MovieDetailsView displays the details page of the movie and has a comment section. However, when I submit the comment, it simply displays a white page and this link: http://127.0.0.1:8000/details/1# . The comment is not … -
Sending data from computer to django website
I work at a computer repair shop. We have a lot of computers we work on that we collect information from. CPU, GPU, RAM, HD space, etc. I wrote a python script that can capture all that information. Now I want to know how I can automatically send that information to a django site and store it in the database. I want the program to ask for the customer id and the asset id and set pass that information along as well. If the computer doesn't have internet, I want it to send it once it gets internet. Then I'm thinking on the server, I'll run the logic to checks if the information is valid (if the computer already exists in the database). How would I begin to start something like this? Is this socket programming? Can you point me in the right direction? -
django on_delete when adding post author
for the on_delete I am seeing this error: File "/home/kensei/Documents/school/bubbles/models.py", line 11, in bubbles user = models.ForeignKey(settings.AUTH_USER_MODEL,) TypeError: __init__() missing 1 required positional argument: 'on_delete for this file in my app from django.conf import settings # Create your models here. class bubbles(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL,) content = models.CharField(max_length=200) timestamp = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now_add=True) def __str__(self): return str(self.content) ``` even with several alterations attempting to add on_delete -
Python ( PIL ) '<_io.BufferedReader' error
specs ubuntu 18.04 ( VPS ) django python 3.8 Error: File "/django/venv/lib/python3.6/site-packages/PIL/Image.py", line 2931, in open "cannot identify image file %r" % (filename if filename else fp) PIL.UnidentifiedImageError: cannot identify image file <_io.BufferedReader name='/django/wall/media/wallpaper.jpg'> this error occurred while I was processing an image with help of Django-imagekit i m processing 1000's of images but this error occurs only on few, rest works fine -
Insert a dictionary in all data of a django queryset
I am getting the Django Query Set output like this. <QuerySet [ { 'transaction_date': datetime.datetime(2021, 4, 28, 13, 39, 47, 66880, tzinfo=<UTC>), 'coin': 200 },{ 'transaction_date': datetime.datetime(2021, 4, 28, 13, 39, 54, 132439, tzinfo=<UTC>), 'coin': 150 }]> I want to insert a key value pair in all quesryset inside the list. The desired output should be. <QuerySet [ { 'transaction_date': datetime.datetime(2021, 4, 28, 13, 39, 47, 66880, tzinfo=<UTC>), 'coin': 200, 'transiction_type':'credit' }, { 'transaction_date': datetime.datetime(2021, 4, 28, 13, 39, 54, 132439, tzinfo=<UTC>), 'coin': 150, 'transiction_type':'credit' } ]> I have done this By this way. coin_withdraw_list = [dict(coin_withdraw, transaction_type="CREDIT") for coin_withdraw inuser_withdraw_list] But I am looking for if their any way to do this using any django function. Thanks in advance. -
How can I capture the name or reg_no of the book in this list?
I'm working on a library system. I am unable to get the registration number of a book/books to be returned back to library... My intention is to click on Return which captures the book name for return processing.. With what I have, when I print(book) it returns None meaning nothing has been taken from the click My models class Books(models.Model): DEPARTMENT = ( ('COM', 'Computer'), ('ELX', 'Electronics'), ('CIV', 'Civil'), ('BBS', 'Business'), ('MSC', 'Miscellaneous'), ) reg_no = models.CharField(max_length=20, blank=True) book_name = models.CharField(max_length=200) no_of_books = models.IntegerField() book_detail = models.TextField(default='text') department = models.CharField(max_length=3, choices=DEPARTMENT) def Claimbook(self): if self.no_of_books>1: self.no_of_books=self.no_of_books-1 self.save() else: print("not enough books to Claim") def Addbook(self): self.no_of_books=self.no_of_books+1 self.save() def __str__(self): return self.book_name class Return(models.Model): return_date = models.DateField(default=datetime.date.today) borrowed_item = models.ForeignKey(Issue,on_delete=models.CASCADE) def new_issue(request): if request.method == 'POST': i_form = IssueForm(request.POST) if i_form.is_valid(): name = i_form.cleaned_data['borrower_id'] book = i_form.cleaned_data['book_id'] i_form.save(commit=True) books = Books.objects.get(book_name=book)#Get a book names as selected in the dropdown semest = Student.objects.get(name=name).semester#Get a student with a semester as selected in the dropdown departm = Student.objects.get(name=name).depart Books.Claimbook(books) return redirect('new_issue') else: i_form = IssueForm() semest = None departm = None sem_book = Semester.objects.filter(sem=semest, depart=departm) return render(request, 'libman/new_issue.html', {'i_form': i_form, 'sem_book': sem_book}) The return view def return_book(request): book = request.GET.get('book_pk') print(book) books = Books.objects.get(id=book) … -
NewConnectionError('<urllib3.connection.HTTPConnection object at 0x0000020B1B5FB640>: Failed to establish a new connectio
I'm new to django and trying to connect django with docker. I'm trying to call docker compase from my django app using url. But docker in port "localhost:5000" and my django app is running on port "127.0.0.1:8000". I think my error is occured from different port numbers. I'm having so much trouble about this issue. How can I solve this error? Please, help. views.py def sentiment(request): output = {} if 'input' in request.GET: input = request.GET['input'] url = 'http://localhost:5000/sentiment/%s' % input response = requests.get(url) user = response.json() return render(request, 'blog/links/Link1.html', {'output': output}) Link1.html <form class="text" method="get" action="{% url 'da_sonuc'%}"> <label for="textarea"> <i class="fas fa-pencil-alt prefix"></i> Duygu Analizi </label> <h2>Test with your own text...</h2> <input class="input" type="text" name="input"> <br> <button type="submit" class="btn" name="submit" >Try!</button> </form> <label > Result </label> <div class="outcome"> {% if output %} <p><strong>{{ output.text }}</strong></p> {% endif %} </div> Error: HTTPConnectionPool(host='localhost', port=5000): Max retries exceeded with url: /sentiment/iyi (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x0000020B1B5FB640>: Failed to establish a new connection: [WinError 10061] -
Django How to organize models so there is only one owner
I have two models Company and User: class Company(models.Model): name = CharField("Name", max_length=60) owner = OneToOneField( "Employee", related_name='owner', on_delete=SET_NULL, null=True) class BaseUser(AbstractBaseUser, PermissionsMixin): objects = CustomUserManager() join_date = DateTimeField(default=timezone.now) name = CharField("Name", max_length=60) email = EmailField(('Email'), unique=True) company = ForeignKey(Company, on_delete=models.CASCADE) I need to have only one User as owner. I made it so two models point to each other which doesn't seem right. Is there a way to fix it and still have only one possible owner? I know standard way would be to add is_owner = Boolean to User but it allows other Users to be owners. -
django form not saving new user is user model
I've made this Signup form in django but the problem is whenever I hit register button it does not save anything on the user model in my admin. Please do help to solve the problem. Forms.py from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm from django.contrib.auth import login, authenticate class register(UserCreationForm): email = forms.EmailField() class Meta: model = User fields = ['username', 'email', 'password1', 'password2'] Views.py from django.shortcuts import render, redirect from .models import mypost from .forms import register from django.contrib.auth.forms import UserCreationForm from django.contrib.auth import login, authenticate def signup(req): if req.method == 'POST': form = register(req.POST) if form.is_valid(): form.save() return redirect('/') else: form = register() return render(req, 'signup.html',{'form':form}) Signup.html {% load crispy_forms_tags %} {% block title %}Sign Up{% endblock %} {% block body %} {% include 'nav.html' %} <div class="container"> <div class="row"> <div class="col-md-3"></div> <div class="col-md-6"> <h3 class="text-center">Sign Up Form</h3> <form method="post">{% csrf_token %} {{form|crispy}} <input type="submit" value="Register"> </form> </div> <div class="col-md-3"></div> </div> </div> {% endblock %} -
How to add site models to Cookiecutter Django project
I have a Cookiecutter Django project in which I'd like to add a "SiteSettings" model to control constants. My first instinct was to run manage.py startapp site. However I received the following message: CommandError: 'site' conflicts with the name of an existing Python module and cannot be used as an app name. Please try another name. Upon closer inspection, it appears that Cookiecutter already created a sites module within contrib, but with no models.py file. So I decided to make a models.py with the SiteSettings model in this directory. However when I run makemigrations it says: No changes detected in app 'sites' How can I add my desired model to this module and get migrations working for this module? -
How to insert JavaScript object into Django JSONField
In my django web app I have two pages- One is a form for the user to fill out the name, size, image, and specify the names of some points of interest on the image. The next page displays that image and allows the user to place some SVG circles corresponding to the points of interest on top, and when the user submits, I want the form from the first page and a JSONField for the locations of the circles (points of interest) on the image to all get saved into one model. Currently, my solution is a page with the first form, then pass that entire form into the next page. Since I don't want the user to see that form anymore, I put it in a hidden div. I render the image from the form and using JavaScript, I draw the circles where the user clicks. When the submit button is pressed, it runs a function in the script that submits the form for a second time, but updates the JSONField with the locations of all the circles before submitting. The code below works up until the form is submitted, but when I get to the view2 function, … -
check checkboxes for values that exists in a list
I am trying to check checkboxes that have values in a list of strings returned from a ModelForm class. The field is declared in models.py file like this: class IC(models.Model): class Meta: verbose_name = "Get Info" p_data = MultiSelectField("Some data", max_length=255, choices=choices.P_DATA_CHOICES, blank=True, null=True) P_DATA_CHOICES looks like this P_DATA_CHOICES = [ ("ch1", "Choice 1"), ("ch2", "Choice 2"), ("ch3", "Choice 3"), ("ch4", "Choice 4"), ("ch5", "Choice 5"), ] I have this ModelForm class in forms.py that I am implementing to the entire class: class ICForm(ModelForm): class Meta: model = IC exclude = ["fk_field"] def __init__(self, *args, **kwargs): super(ICForm, self).__init__(*args, **kwargs) for i, f in self.fields.items(): f.widget.attrs['class'] = "custom_class" In my template I am generating the checkboxes as such: {% for value, text in ic_modelform.p_data.field.choices %} <li> <input id="value_{{ forloop.counter0 }}" name="{{ ic_modelform.p_data.name }}" type="checkbox" value="{{ value }}" {% if value in ic_modelform.p_data.field.checked %} checked="checked" {% endif %}> <label for="value_{{ forloop.counter0 }}">{{ text }}</label> </li> {% endfor %} If I check a few checkboxes (say Choice 1 and Choice 2) and submit the form, I can see ch1,ch2 in the p_data column of the database, but when I load the page again, their respective checkboxes are not checked. I believe this has … -
JQuery Ajax mangles incoming JSON data
I'm sending a dict through my Django API that looks like this: data = { 'total_sales': total_sales, 'salesperson_sales': salesperson_sales, 'date_range': { 'from_date': from_date, 'to_date': to_date } if from_date and to_date else 'all' } and 'salesperson_sales' is a list of dicts that looks like this: salesperson_sales = [{ 'name': string, 'sales': float, 'sales_percent': float }] I'm calling this route from a JavaScript file on one of my pages using the following code: let get_salesperson_sales = async() => { response = await $.ajax({ type: 'GET', url: `/reports/salesperson-sales/${fromDate && toDate ? `?from_date=${fromDate}&to_date=${toDate}` : ''}`, success: (response) => { document.getElementById('total_rep_sales').innerText = '$'+Number(response.total_sales.toFixed(2)).toLocaleString() }, error: (error) => { errorMessage.innerHTML += '<p>Error getting sales by rep: '+error.responseJSON.details+'</p>' } }) return response } I then use that response data in a promise callback function. Promise.allSettled([...]).then((results) => {sales_data = results[0].value; ...})` The problem is that the data I get in the callback function has 'salesperson_sales' sorted by name, but all other fields are left in place. So if my API returns a list that looks like this: [ {'name': 'Courtney', 'sales': 100, 'sales_percent': 17}, {'name': 'Anthony', 'sales': 200, 'sales_percent': 33}, {'name': 'Blake', 'sales': 300, 'sales_percent': 50} ] Then the data I see in my JavaScript file looks like … -
Passing Django user information to Dash app
I am curious whether it is possible to pass the currently logged in user full name into a Dash app created in Django? Assume you have a simple Dash table integrated into Django: import dash from dash.dependencies import Input, Output, State import dash_table import dash_core_components as dcc import dash_html_components as html import pandas as pd from django_plotly_dash import DjangoDash df = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/solar.csv') app = dash.Dash(__name__) app.layout = dash_table.DataTable( id='table', columns=[{"name": i, "id": i} for i in df.columns], data=df.to_dict('records'), ) if __name__ == '__main__': app.run_server(debug=True) Are there any way to access the -Django- user information of the person who is logged in? This is just a simple example, but I want to create an SQL folder conditional on user name and user ID located in Django Admin. I solely need to know how to grab the name e.g. "name = request.user.get_full_name" or some type of similar function (in the latter case 'request' is not defined so it does not work). Thanks!