Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to access datatable values from a django url in my Flutter datatable?
I have a project which shows the values of volts and current etc... The actual source of the data is a Django URL, and I want to read that values in my flutter data table. How to do it... Note: I am not familiar with Django. I know only flutter & dart. Here is my Django code ss. On the left side is the code & on the right side is the output of which accessed by a URL. and here is my data table code of Flutter ```rows: [ DataRow( cells: [ DataCell( Text( 'Red', style: TextStyle( color: Colors.red, fontWeight: FontWeight.bold), ), ), DataCell( Text('$c1R1'), ), DataCell( Text('$c2R1'), ), DataCell( Text('$c3R1'), ), ], ), DataRow( cells: [ DataCell( Text( 'Blue', style: TextStyle( color: Colors.blue, fontWeight: FontWeight.bold), ), ), DataCell( Text('$c1R2'), ), DataCell( Text('$c2R2'), ), DataCell( Text('$c3R2'), ), ], ), DataRow( cells: [ DataCell( Text( 'Yellow', style: TextStyle( color: Colors.yellow, fontWeight: FontWeight.bold), ), ), DataCell( Text('$c1R3'), ), DataCell( Text('$c2R3'), ), DataCell( Text('$c3R3'), ), ], ), ], ),``` Here is the output of the flutter code -
Bootstrap dropdown in each table row where the page refresh every five seconds not opening for a single record, but opens for multiple records Why?
I have a bootstrap dropdown, inside each table row cell. The page refresh in every five seconds. The dropdown will not open if single record appears but opens perfectly for multiple records. -
Django - Is it possible to access some content of one function from another function?
I have two functions in one of my Django-based projects, under the views.py file. Where the first function generates a view page and the second function is just returns some response based on jQuery request. Here's how they look like: First function that renders a show page: @login_required() def watchlist_details(request, iid): ... ... ... ... ... ... contracts = dict(enumerate(x.rstrip() for x in symbols)) automate = Automate() automate.init_symbol(contracts) automate.live_stream() ... ... ... ... ... ... return render(request, 'watchlist_show.html') Second function that will return some response on a jQuery call: def streaming_response(request): automate = Automate() # need to replace this with: automate = automate_of_first_function result = automate.get_stream_result() json_result = json.dumps(result) return json_result Here the problem is in the second function is, I reinitialize automate which does not have any content to generate a response. So, I need to access the method automate instance that is initialized in the watchlist_details function. As I follow function-based views in my Django apps rather than class-based views so there is no way to create a global/common variable. And I think Django does not allow the creation of more than one method in class-based views (and it is also a confusing concept for me). So my … -
'django-admin' is not recognized as an internal or external command, operable program or batch file
I have installed Django and my python path seems ok. whenever I try to create a new folder with the command line django-admin it is showing me up this message. I have tried reinstalling python but is not working. -
Django Celery - Some task messages are getting skipped
I've created a django-celery task. The task worker is hosted using supervisord. Normally whenever I call the method using celery's .delay() method a new task is received by the celery worker & immediately starts processing the same (as expected :D ) However, at frequent times this happens that we call the method using .delay() & receive no errors on main thread (where .delay was originally called). But as per the logs of the celery worker, the task never reaches it. Never seen such a behavior previously. Tried searching the docs as well as "SO" community, but can't get to why this is happening. The worker is up & free, redis-server is also up & running, after a few tries of adding new task, the worker receives the task again, without even restarting the worker. Thanks -
How would you make this interface in django? [closed]
I need to do something similar to this. What would be the best structure using classes and forms if I need to present them all together? At the time of creating a product I need: 1- add a model A. 2- Add one or more models B. 3- Add one or more models C. But I need each model to keep a key about the product. interface -
React rest-hooks authentication
I have to admit that I already asked this but it was answered correctly. But I can't still focus on how to authenticate against the backend. I have both sides: frontend (React) and backend (Django). I am reading the rest-hooks authentication documentation but I can't see how to use their resources the send the data and retrieve the token. Thanks to @LindaPaiste, "I" wrote this AuthResource.ts: import { Resource } from '@rest-hooks/rest'; import { API_URL } from '../utils/server'; export default class AuthResource extends Resource { static getFetchInit = (init: RequestInit): RequestInit => ({ ...init, credentials: 'same-origin' as const }); readonly email: string = ''; readonly password: string = ''; pk(parent?: any, key?: string | undefined): string | undefined { return; } static urlRoot = API_URL + 'auth-token/' } But, after reading the previous documentation I can't figure out which hook I should use. Is useFetcher(AuthResource.create(), { formData })? Just looking at it, you can tell is wrong..., but anyway...: import React, { useState } from 'react'; import { useFetcher } from 'rest-hooks'; import AuthResource from '../../../resources/AuthResource'; export default function LoginPage() { const create = useFetcher(AuthResource.create()); function submitForm(e: any) { e.preventDefault(); create({}, new FormData(e.target)); } return ( <div className="login-container"> <form className="login-form" … -
When I try to set the href attribute with Javascript, undesired text is added
I am developing on localhost: http://127.0.0.1:8000 When I do some search on the website, I want that if the query does not return results, the New entry button allows the creation of a new article from what has been searched in the search input. So if I search 'whatever' and there is no article called 'whatever', the button should redirect me to the creation page of the article 'whatever'. <script> $( document ).ready(function() { var newEntryUrl = window.location.hostname+":8000/wiki/_create/?slug="+"{{ search_query }}"; document.getElementById('newEntrybtn').setAttribute('href',newEntryUrl); }); </script> {% for article in articles %} {% block wiki_search_loop2 %} {% endblock %} {% empty%} There is no page created for '{{ search_query }}', would you like to create a page nowee? <a class="btn btn-success" id="newEntrybtn" role="button"><i class="fa fa-plus" aria-hidden="true"></i> New entry ({{ search_query }})</a> {% endfor %} To calculate the url to create the new article, I use this line: var newEntryUrl = window.location.hostname+":8000/wiki/_create/?slug="+"{{ search_query }}"; If I do an alert(newEntryUrl); it returns the desired result: 127.0.0.1:8000/wiki/_create/?slug=whatever However, if I click the newEntrybtn button, it redirects me to the following url: http://127.0.0.1:8000/wiki/_search/127.0.0.1:8000/wiki/_create/?slug=whatever Which is strange to me since at no time have I assigned the href attribute to the button, much less have I assigned it … -
How to Automatically Change English Typing from Korean Typing in Password Input in Django?
I'm working on Login Function using Django. I'd like to automatically change letters typed in Korean to English. For example, 가나다 -> rkskek How can I make it? I started yesterday, but still struggling with it.. Anyone could help me out!? FYI I've been trying Adding 'lang' attribute in password element -> Failed Using LoginView -> Failed -
Django iterate zip from same position in lists
first I zip all my lists just like books= zip(*bookName, *detail) the length of bookbName and detail is same, and I want to get the table like {% for bookName, detail, in books %} <tr> <td>{{bookName}}</td> <td>{{detail}}</td> </tr> {% endfor %} As I can not confirm the length of bookName and detail, I got the error message like "Need 3 values to unpack in for loop; got 5. " I tried {% for record in books %} <tr> {% for item in record %} <td>{{ item }}</td> {% endfor %} </tr> {% endfor %} but the result is get detail after all the bookname show. How can I get the table when I got first bookname then I can get the first book's detail? -
how to integrate video call and chat functionality in Django project?
i don't know whether i am violating the Stack Overflow guidelines but can anyone tell me who to integrate Video calling and Chatting functionality in a Django project. I don't want to create anything from scratch so how to use additional packages to accomplish this task? -
Django: what does new group, create mean?
I am trying to create different groups to be given different permission: new_group, created = Group.objects.get_or_create(name ='new_group') Came across this code and I just want to clarify what it means. This is my guess: I am creating a new group and that will be the name of that variable. But what does the ', created' mean? Then for the groups basically you just want to get a group and if there isnt a group you will create it. Thanks. -
django, admin jet- Problems with the same privileges of admin and staff
I designated admin menu through django-jet. settings.py JET_SIDE_MENU_ITEMS = [ { "label": _("board"), "app_label": "board", "items": [ {"name": "notice"}, {"name": "event"}, ], }, { "label": _("user"), "app_label": "users", "items": [ {"name": "user"}, {"name": "devices"}, {"name": "pushnotifications"}, {"name": "pushnotificationlogs"}, ], },] And then, I classified the member type as "manager" and called it [is_staff = true] I gave the manager access to the board app only. board_groups.py GROUPS_PERMISSIONS = { "Manager": { models.Notice: ["add", "change", "delete", "view"],} However, like the account in [super_admin], the account with the privileges of [is_staff] can see all models("label": _("board") &"label": _("user")) Is it because of the menus I prepared in the settings.py? -
How can i access to my application using IP I'm really tired
I'm working on a small project using Vue.js / Django Rest Framework I created my application, now I just want to visit my work, but I don't know which IP address I have to use in the browser to see my work, I tried everything this is my vue.config.js const BundleTracker = require("webpack-bundle-tracker"); module.exports = { publicPath: "http://0.0.0.0:8080/", outputDir: './dist/', chainWebpack: config => { config .plugin('BundleTracker') .use(BundleTracker, [{filename: './webpack-stats.json'}]) config.output .filename('bundle.js') config.optimization .splitChunks(false) config.resolve.alias .set('__STATIC__', 'static') config.devServer // the first 3 lines of the following code have been added to the configuration .public('http://127.0.0.1:8080') .host('127.0.0.1') .port(8080) .hotOnly(true) .watchOptions({poll: 1000}) .https(false) .disableHostCheck(true) .headers({"Access-Control-Allow-Origin": ["\*"]}) }, // uncomment before executing 'npm run build' // css: { // extract: { // filename: 'bundle.css', // chunkFilename: 'bundle.css', // }, // } }; I do npm run serve also I do python manage.py runserver / but when i access to the browser nothing is work -
Django app with gunicorn and container stack not running when deployed to heroku
I built a Django 3.1.0 app on my dev server (local windows machine) with postgreSQL, and I can run it perfectly well from inside a Docker container. When I deploy to heroku, I get no error, but when I click Open App (or run command heroku open -a myapp) it opens a browser window with a message as follows: Heroku | Welcome to your new app! Refer to the documentation if you need help deploying. I've tried several things, including running heroku ps which says 'no dynos on myapp'. Also tried running heroku ps:scale web=1 but to no effect. I have a Profile at the appropriate folder level, and it does not have a .txt or any other suffix. Also, it contains the following line: web: gunicorn config.wsgi --log-file - The stack is set to container on heroku. Another app deployed successfully but without using container. Another thing: when I run heroku run python manage.py migrate, or heroku run python manage.py createsuperuser, the commands seem to run forever and I have kill with CTRL-C. Not sure what's going on. Any help would be greatly appreciated. I've looked at a dozens similar threads here but my problem remains unresolved. Not sure … -
Django admin add view with custom actions (buttons)
I want to add in the admin, the possibility to approve or reject the registration of certain users. For that I want to add in the listing of these users a custom action that redirets to another view. In this other view I want to be able (as the admin) to check the info of the user and then either Approve or Reject the registration with two buttons. Having differentt logic for each choice. I've managed to the add the action in the listing, but can't seem to see the view. It automatically goes to the second step of approving. register.html {% extends "admin/base_site.html" %} {% block content %} <div id="content-main"> <form action="" method="POST"> {% csrf_token %} <fieldset class="module aligned"> {% for field in form %} <div class="form-row"> {{ field }} </div> {% endfor %} </fieldset> <div class="submit-row"> <input type="submit" class="default" value="Aprobar"> <input type="submit" class="default" value="Rechazar"> </div> </form> </div> {% endblock %} form.py class RegisterForm(forms.Form): def approve(self, student): pass def reject(self, student): pass def save(self, student): try: student.registered = True student.save() except Exception as e: error_message = str(e) self.add_error(None, error_message) raise return student admin.py @admin.register(PreRegisteredStudent) class StudentPreRegistered(StudentCommonAdmin): def check_button(self, obj): return format_html( '<a class="button" href="{}">Check</a>', reverse('check', args=[obj.pk]), ) actions = … -
Django restframework and markdownx
I want to know how to use preview of markdownx in restframework serializer. Example: I can show the preview by rendering the HTML with followings: {{form}} {{form.media}} However, Idk how to do it with {% render_form serializer %} Should i manually make a preview div in HTML and manually achieve it through ajax? -
Django Pagination Issues - Beginner
I'm making a project with Django and learning about pagination for the first time. I've read a lot of documentation so far but still can't get it to work. I don't know what I'm doing wrong. Any insight is helpful. From my understanding, this should make only 3 posts appear on the page. Instead, all of the posts appear. I want to make it so only 3 posts appear on the page at once. I don't get any errors with this. I just see all the posts on the page. views.py from .models import User, Post from django.core.paginator import Paginator def index(request): list_of_posts = Post.objects.all().order_by('id').reverse() paginator = Paginator(list_of_posts, 3) page_number = request.GET.get('page', 1) page_obj = paginator.get_page(page_number) return render(request, "network/index.html", { "list_of_posts": list_of_posts, "page_obj": page_obj }) Portion of the html for pagination: <div class="container"> <ul class="pagination justify-content-center"> {% if page_obj.has_previous %} <li class="page-item"><a href="?page=1" class="page-link">&laquo; First</a></li> <li class="page-item"><a href="?page={{ page_obj.previous_page_number }}" class="page-link">Previous</a></li> {% else %} <li class="page-item disabled"><a class="page-link">&laquo; First</a></li> <li class="page-item disabled"><a class="page-link">Previous</a></li> {% endif %} {% if page_obj.number %} <li class="page-item"><a class="page-link">{{ page_obj.number }}</a></li> {% else %} <li class="page-item"><a class="page-link">0</a></li> {% endif %} {% if page_obj.has_next %} <li class="page-item"><a href="?page={{ page_obj.next_page_number }}" class="page-link">Next</a></li> <li class="page-item"><a href="?page={{ page_obj.paginator.num_pages }}" class="page-link">Last … -
Performance difference of template logic vs. get_context_data
I am displaying a list of Bicycles. The Bicycle model has a function get_wheels that gets objects of type Wheel related to that model Bicycle instance. For each instance of Bicycle, I want to list all related Wheel objects in the template. Is it faster to call get_wheels in the get_context_data method, or is it faster to call get_wheels in the template? How I call it in the template: {% with wheels=p.get_wheels %} {% if files %} {% for w in wheels %} {{ w.store.label }} {% endfor %} {% endif %} {% endwith %} How I would call it in get_context_data: def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) bicycles = context['object_list'] for bicycle in bicycles: wheels = bicycle.get_wheels() if wheels: test.wheels = wheels return context Kind of related to Iterate over model instance field names and values in template Disclaimer: I am using Bicycles and Wheels as examples, this is not my actual use case. But I do have a model one one type that has a class function that gets the related models of type B. The question is about the speed of getting data in the template rather than in get_context_data -
pyexcel save to Django model
Having difficulties understanding the documentation for interaction between dest_initializer and dest_model? If I have a Django model like: class MyModel(Model) file = FileField() How can I write a file to an instance of this model? instance = MyModel() records = [OrderedDict([("Test Key", "Test Value")])] pyexcel.save_as( records=records, dest_model=MyModel, ...... ?????? How to write to instance.field? ) -
TypeError at / 'NoneType' object is not callable
this is the code. kindly tell me what i'm doing wrong ... def allowed_users(allowed_roles=[]): def decorator(view_func): def wrapper_func(request, *args, **kwargs): group = None if request.user.groups.exists(): group = request.user.groups.all()[0].name if group in allowed_roles: return view_func(request, *args, **kwargs) else: return HttpResponse('You are not authorized to view this page') return wrapper_func return decorator def admin_only(view_func): def wrapper_function(request, *args, **kwargs): group = None if request.user.groups.exists(): group = request.user.groups.all()[0].name if group == 'customer': return redirect('user-page') if group == 'admin': return view_func(request, *args, **kwargs) return wrapper_function -
static file loading problems on pythonanywhere
i'am trying to deploy restframework on pythonanywhere so i can use it in for my android project but the issues here that the restframework page is shown whitout a css or js files [enter image description here][1] [1]: https://i.stack.imgur.com/ImW94.png i tried evrey solution on stackoverflow but nothing work ! i collectstatic file using python manage.py collectstaticfile i set up `STATIC_ROOT='/home/ssmedicament/api/static/'` `STATIC_URL = '/static/'` -
How do I get FormSet to validate in my view?
I am doing something a bit unusual with FormSets. I am attempting to use a queryset as the input to my formset. This seems to be working at this point just fine. What isn't working is the form validation. Thanks in advance for any thoughts. I can't create this relationship via a traditional foreign key for reasons I won't bother people with. My Models.py class Team(models.Model): team_name = models.CharField(max_length=264,null=False,blank=False) class Player(models.Model): player_name = models.CharField(max_length=264,null=False,blank=False) team_pk = models.integerfield(Team,null=True,on_delete=models.CASCADE) My views.py class CreateTeamView(LoginRequiredMixin,UpdateView): model = Team form_class = CreateTeamForm template_name = 'create_team.html' def get_context_data(self, **kwargs): context = super(CreateTeamView, self).get_context_data(**kwargs) dropdown = self.request.GET.get("dropdown", None) queryset = Player.objects.filter(company_pk=dropdown) player_form = PlayerFormSet(queryset=queryset,dropdown=dropdown) context['player_form'] = player_form context['dropdown'] = dropdown return context def get_form_kwargs(self): kwargs = super(CreateTeamView,self).get_form_kwargs() kwargs['user'] = self.request.user kwargs['dropdown'] = self.request.GET.get("dropdown") return kwargs def get(self, request, *args, **kwargs): dropdown=self.request.GET.get("dropdown") self.object = self.get_object() context = self.get_context_data(object=self.object) self.object = None context = self.get_context_data(object=self.object) form_class = self.get_form_class() form = self.get_form(form_class) form_kwargs = self.get_form_kwargs() player_form = PlayerFormSet(dropdown=dropdown) return self.render_to_response( self.get_context_data(form=form, player_form=player_form, context=context, )) def form_valid(self, form, player_form): self.object = form.save() player_form.instance = self.object player_form.save() def form_invalid(self, form, player_form): return self.render_to_response( self.get_context_data(form=form, player_form=player_form, )) def post(self, request, *args, **kwargs): self.object = None form_class = self.get_form_class() form = self.get_form(form_class) dropdown=self.request.GET.get("dropdown") player_form … -
Can I use a 6-digit pin code instead of password in logging in my users in django authentication?
Is there a way where the users can login to my webapp using their username and a 6-digit pin (like the ones we use in our atms) instead of using the password? I am new to django and don't know how or where to look in this. Thank you! -
Django URL path not matching
I am currently having a non-matching URL error for the following URL http://127.0.0.1:8000/report/?report=Report. The questions/answers found here and elsewhere have been of no use. I have a button that I am trying to redirect with. report/ ?report=Report [name='candidate-report'] The current path, report/, didn't match any of these. project.urls: from django.urls import include, path from . import views urlpatterns = [ path('', views.home_view, name='home'), path('report/', include('Reports.urls')) ] Reports.urls: from django.urls import path from . import views urlpatterns = [ path('?report=Report', views.candidate_report_view, name='candidate-report'), ] Reports.views: from django.shortcuts import render from .forms import CandidateReportForm def candidate_report_view(request): category_form = CandidateReportForm.category() comment_form = CandidateReportForm.comment() return render(request, 'candidate_report.html', {'category_form': category_form, 'comment_form': comment_form}) base.html: <form class="d-inline-block float-right" action="report/" method="get"> <input class="btn btn-primary" id="report_button" name="report" type="submit" value="Report">