Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Bokeh chart overflowing its div container
I am embedding a bokeh chart into a Django app template. Below is the template: home_board.html {% extends "base.html" %} {% load static %} {% block title %}Home-Board{% endblock %} {% block content %} <link href="{% static "css/home_board.css" %}" rel="stylesheet"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bulma/0.4.0/css/bulma.css" /> <script src="https://cdnjs.cloudflare.com/ajax/libs/bokeh/2.3.2/bokeh.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/bokeh/2.3.2/bokeh-widgets.min.js"></script> <div id="nav-bar">&nbsp; </div> <div id="side-bar"> <button id="home-button" class="side-bar-button">Home</button> </div> <div id="content-container"> <div id="chart-container"> {{ div | safe }} </div> </div> {{ script | safe }} {% endblock %} Here is the view where the chart is created: def home_board(request): ... p = figure(x_axis_type="datetime", tools="", plot_width=300, plot_height=300, title=title,) p.xaxis.major_label_orientation = pi / 4 p.toolbar.logo = None p.grid.grid_line_alpha = 0.3 p.segment(source.date, source.high, source.date, source.low, color="black") p.vbar(source.date[increasing], w, source.open[increasing], source.close[increasing], fill_color="#D5E1DD", line_color="black") p.vbar(source.date[decreasing], w, source.open[decreasing], source.close[decreasing], fill_color="#F2583E", line_color="black") script, div = components(p) return render(request, 'homeboard/home_board.html', {'script': script, 'div': div}) However, this chart appears as overflowing outside of the chart-container div, overlapping with the nav-bar and the side-bar div elements. I don't think it is an CSS problem. How do I configure the chart so it sits squarely in the div that it is under? -
How to in Model.objects.get give attribute name?
I need choose which attribute i use for id getting. def get_object_id(attribute, attribute_value): URL.objects.get(attribute=attribute_value) -
Why my for i in range loop is not working? [closed]
I came into similar problem. Is for b in bottomwear not working? As there wasn't glown on syntax loop line. Is there a problem on loop on my home.html file? enter image description here -
Programming Error: With PhoneNumberField in Django
After pip install phone number field on global as well as in virtual env and importing in the models.py I am facing programming error. Details are as follows DB is POSTGRESQL models.py from django.db import models from phonenumber_field.modelfields import PhoneNumberField class Agent(models.Model): agency_name = models.CharField(max_length=200) prop_name = models.CharField(max_length=30) agency_address = models.CharField(max_length=300) agency_city = models.CharField(max_length=50) agency_country = models.CharField(max_length=50) email_address = models.EmailField(max_length=50) contact_nu = PhoneNumberField() def __str__(self): return self.agency_name admin.py @admin.register(Agent) class AgentAdmin(admin.ModelAdmin): list_display = ('agency_name', 'prop_name', 'agency_address', 'agency_city', 'agency_country', 'email_address', 'contact_nu') Error: [07/Jun/2021 09:52:34] "GET /admin/ HTTP/1.1" 200 5546 Internal Server Error: /admin/rk003/agent/ Traceback (most recent call last): File "/Users/rishipalsingh/Projects/notes/mdndjango/venv/lib/python3.9/site-packages/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql, params) psycopg2.errors.UndefinedColumn: column rk003_agent.contact_nu does not exist Thanks -
Django session_key not working in React app
views.py: @api_view(['GET']) def addToCartForSession(request, pk): product = get_object_or_404(Product, pk=pk) mycart, __ = Cart.objects.get_or_create(session_key=request.session.session_key) mycart.product.add(product) return Response({'response':'ok'}) models.py: class Cart(models.Model): id = models.AutoField(primary_key=True) user = models.ForeignKey(User, on_delete=models.CASCADE, blank=True, null=True) session_key = models.CharField(max_length=200, blank=True) product = models.ManyToManyField(Product, related_name='product_items', blank=True) urls.py: path('addToCartForSession/<str:pk>/', views.addToCartForSession, name='addToCartForSession'), if I go to this http://127.0.0.1:8000/addToCartForSession/8/ url directly from browser search bar, session_key works fine. But it I try to access this url from my React app, it shows server error. Reactjs: addToCart=()=>{ var id = this.props.id var url2 = 'http://127.0.0.1:8000/addToCartForSession/'+id+'/' fetch(url2,{ method:'GET', headers: { 'Content-Type': 'application/json', 'X-CSRFToken': this.csrftoken } }).then(res=>res.json().then(result=>{ if(result.response === 'ok'){ this.props.dispatch({ type: 'itemInCart', }) this.setState({addedToCart: true}) } })) } Can you tell me, how can I use session_key in Django-rest_framework? yesterday I asked 3/4 question about this problem, but no one could answer this. -
how to change color from red to green if mobile verification status converted from unverified to verified?
from last few hours i have been finding the solution for below question and had spent lot of time but couldn't find the one. I am currently working on one project(based on django) which has a user profile where users can verify their mobile number. I am using twilio for that. what i want is when a user go to his/her profile then there should be a option of "verify your mobile number" right below to the mobile number field which will be in red color, as soon as the user verify his/her mobile number via some backend django(python) stuff and come back to profile page again, that message should be "verified"(in green color). i want css and javascript code to achieve that because for sms verification and all the backend stuff i already have the code. Any kind of help would be appreciated... -
How can i use influxdb in django project
i have some trouble about influxdb+django configurations. Firstly let me summarize my situation. I have an influxdb which is already collecting data from endnode(sensors). Data is transfering by LoraWan technology. I can read that datas from terminal by writing flux queries so database is working without any problem. Now my second phase of this project is visualizing that datas on an web page. I am using django framework for that i completed the frontend parts nearly. I looked on internet for the configurations for influxdb on django but i couldnt handle it. In django documentation page they are listed some databases like below: Django officially supports the following databases: PostgreSQL MariaDB MySQL Oracle SQLite How will i use/configure and get data from my influxdb ? Is it possible ? What are the alternative solutions. -
How to enforce automatic timestamp for django model in database level?
I have a django abstract model that goes like this: class AbstractAppendOnly(models.Model): created_at = models.DateTimeField(auto_now=True, editable=False) db_note = models.TextField(default=None, null=True) class Meta: abstract = True This model is extended to multiple other models so that a create_at field is automatically added to all of those. Now when an object is created and saved from django server end the created_at timestamp field is automatically produced, as expected. But it does not enforce it in database level, so anyone can insert a row with fake created_at value. As far as I am concerned django does not let user to set database level default value for model issue-470. What I have found that may solve the issue - I have found an way to customize the migration files using tool like django-add-default-value . But since migrations may sometimes needed to be pruned in big systems and we will have to write customized migrations every time we create a new model, it seems of huge error-prone. Another way I have thought of is to add trigger using django-pgtrigger like this @pgtrigger.register( pgtrigger.Trigger( name='insert_auto_created_at_timestamp', operation=pgtrigger.Insert, when=pgtrigger.Before, func=''' new.created_at = now(); return new; ''' ) ) class AbstractAppendOnly(models.Model): created_at = models.DateTimeField(auto_now=True, editable=False) db_note = models.TextField(default=None, null=True) … -
Movie.py Error file not found on given path
I am currently working on a project in django where i had to extract frames from some part of the video by cropping the video first. Here is the sample code crop and frames extraction code My video is located in the same directory but still when i run this code i get this error Error Can anyone help me in solving this error? Thanks. -
Django model formset : customize empty form fields
If I have a view that shows a formset of users for administration purpose (easy CRUD approach for admin like admin page). I want the instance forms to show normal data like 'username', 'first_name', 'last_name', 'email', but in empty form (adding new user) I want to add extra field for 'password'. To be precise, in formset model table view, the admin can give password to new user but can't change or view password of existing user. how to achieve that ? -
How to add radio buttons with text fields in Flask/WTForms
I have created a form with Flask and WTForms and I'm trying to make a RadioField with a radio button that says "Others . ." and has a text field beside it so the user can add their custom value to the RadioField. class PastebinEntry(Form): language = SelectField(u'Programming Language', choices=[('cpp', 'C++'), ('py', 'Python'), ('text', 'Plain Text'), ('Others', 'Text Input Here')]) Ideally, the radio button would look like this: Image.png -
Show pandas framework as html from csv file
I am trying to show csv files on html content but I havent done properly up to now. Want to show html content without using models because the length or headers is not fixed this is dependable on tasks. This doesnt show proper format. Code; df = pd.read_csv(f_path) objects = df.to_html(header=None)return HttpResponse(objects) csv content html output -
Bootstrap doesn,t show up when using {% extends 'base.html' %}
I have a problem while using bootstrap on my site. The static file show and works when I load my site without problem, but when I click some link it's like bootstrap is not implemented. Even the home page that it actually works at the beginning when I go there from a link in the navbar there is not bootstrap. This is my code, What could be my issue? base.html {% load static %} <!doctype html> <html lang="en"> <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <!-- Bootstrap CSS --> <link rel="stylesheet" href="static/main_page/css/bootstrap.min.css" crossorigin="anonymous"> <title>Hello, world!</title> </head> <body> {% include 'navbar.html' %} <br/> {% block content %} {% endblock %} <!-- Optional JavaScript --> <!-- jQuery first, then Popper.js, then Bootstrap JS --> <script src="static/main_page/js/bootstrap.min.js" crossorigin="anonymous"></script> </body> </html> home.html {% extends 'base.html' %} {% block content %} <h1> Hello World! </h1> {% endblock %} -
'QuerySet' object has no attribute 'product'
Hi I'm building a Webshop. Now I'm trying to add and delete their quantity and calculate the total price of them but I don't know how I could get the product.name or the product.quantity without getting an error as shown below. this is my views.py : def add_cart(request): memid = request.session.get( "memid" ) pnum = request.GET.get("pnum") product = Product.objects.get(pnum=pnum) try: cart = Order.objects.get(order_id_id = memid, prod_num_id = pnum) if cart: if cart.product.pname == product.pname: cart.quantity += 1 cart.save() except Order.DoesNotExist: user = Sign.objects.get(pk=request.user.pk) cart = Order( user=user, product=product, quantity=1, ) cart.save() return redirect('cart') def minus_cart_item(request): pnum = request.GET.get("pnum") cart_item = Order.objects.get(prod_num_id = pnum) product = Product.objects.get(pnum=pnum) try: for item in cart_item: if item.product.pname == product.pname: if item.quantity > 1: item.quantity -= 1 item.save() return redirect('cart') else: return redirect('cart') except Order.DoesNotExist: raise Http404 Now I'm trying to get pnum and quan from Query set but the error describes that AttributeError at /order/add_cart 'Order' object has no attribute 'product' models.py class Order( models.Model) : onum = models.AutoField(null=False, unique=True, primary_key=True) prod_num = models.ForeignKey(Product, on_delete=models.CASCADE) order_id = models.ForeignKey(Sign, on_delete=models.CASCADE) quan = models.PositiveSmallIntegerField(null=True, default=1, validators=[MinValueValidator(1), MaxValueValidator(100)]) this my html : {% for i in j %} <tr> <td>{{i.prod_num.pnum}}</td> <td><img src={{i.prod_num.image.url}} width="100" height="100"></td> <td>{{i.prod_num.pname}}</td> <td>{{i.prod_num.price}}원</td> <td>{{i.quan}} … -
@login_required does not take effect across apps in project
I want to use the decorator @login_required on all apps in my Django project. Following this thread, which shows how to write a middleware for that, here is my middleware: loginmiddleware.py from django.conf import settings from django.utils.deprecation import MiddlewareMixin from re import compile from django.shortcuts import redirect EXEMPT_URLS = [compile(settings.LOGIN_URL.lstrip('/'))] if hasattr(settings, 'LOGIN_EXEMPT_URLS'): EXEMPT_URLS += [compile(expr) for expr in settings.LOGIN_EXEMPT_URLS] class LoginRequiredMiddleware(MiddlewareMixin): def process_request(self, request): assert hasattr(request, 'user') if not request.user.is_authenticated: path = request.path_info.lstrip('/') if not any(m.match(path) for m in EXEMPT_URLS): return redirect(settings.LOGIN_URL) And in my settings.py LOGIN_URL = '/account/login' LOGIN_EXEMPT_URLS = (r'/account/login/',) MIDDLEWARE = [ ... 'account.middleware.loginmiddleware.LoginRequiredMiddleware', ] Here is the folder structure in my project: \projec_root account\ middleware\ loginmiddleware.py models.py views.py ... boards\ models.py views.py ... dashboard\ settings.py urls.py ... In the app boards, this is the view I would like to apple the decorator on: boards\views.py: from django.shortcuts import render from django.contrib.auth.decorators import login_required @login_required() def home_board(request): return render(request, 'homeboard/home_board.html', {}) boards\urls.py from django.urls import path from . import views app_name = 'boards' urlpatterns = [ path('', views.home_board, name='home_board'), ] However, I can still access the template home_board.html without being logged in. What's missing here? -
Cannot assign "'Single Bedded'": "Patients.room_type" must be a "Accomodation" instance
I am new to Django and I have to make a project, with a scenario of a website for a Hospital. I have an Accomodations model which has data regarding what kind of beds are available and have a Patients model which has data regarding the Patient. room_type is a foreign key from Patients model to Accomodations model. Now the trouble I am having is when a new Patient has to register. I have a field which is a dropdown list with the options as the various types of beds available. I need to save the option selected from this dropdown to the DB. I used a custom form, and implemented using crispy fields. The error I am getting is Cannot assign "'Single Bedded'": "Patients.room_type" must be a "Accomodation" instance. I don't know how correct I am but I think that the problem occurs when I am passing 'Single Bedded' instead of Single Bedded (without quotes) to the DB. I am attaching my codes below: forms.py room_types = (('Single Bedded', 'Single Bedded'), ('Double Bedded', 'Double Bedded'), ('General Ward', 'General Ward'), ('Emergency Ward', 'Emergency Ward'), ('ICU', 'ICU')) class NewUserForm(forms.ModelForm): def __init__(self, *args, **kwargs): user = kwargs.pop('user', '') super(NewUserForm, self).__init__(*args, **kwargs) self.helper … -
Running django-simple-buefy in django 3.2.4
When I am trying to compile a Django 3.2 application with django-simple-buefy package, I am getting the following error: File "<frozen importlib._bootstrap>", line 1007, in _find_and_load raise InvalidTemplateLibrary( django.template.library.InvalidTemplateLibrary: Invalid template library specified. ImportError raised when trying to load 'django_simple_buefy.templatetags.django_simple_buefy': No module named 'django.contrib.staticfiles.templatetags' I know that django.contrib.staticfiles.templatetags was removed in Django version 3.0. What can be done to include buefy in my project? -
Django channels with react native resulting this error "Expected HTTP 101 response but was '200 OK'"
Django channels endpoint is working well with WebSocket client(WebSocket king client) and the react-native gives no error when tested with test WebSocket endpoint(wss://echo.websocket.org). But things getting failed with the following error when using Django channels endpoint with react native. Error on error block LOG Expected HTTP 101 response but was '200 OK' Django channels code from channels.generic.websocket import WebsocketConsumer from asgiref.sync import async_to_sync from .models import CustomUser from django.core import serializers import json class EchoConsumer(WebsocketConsumer): def connect(self): self.team_name = self.scope["url_route"]["kwargs"]["teamCode"] self.team_group_name = self.team_name print(self.team_group_name) async_to_sync(self.channel_layer.group_add)( self.team_group_name, self.channel_name ) self.accept() def disconnect(self, close_code): async_to_sync(self.channel_layer.group_discard)( self.team_group_name, self.channel_name ) def receive(self, text_data): async_to_sync(self.channel_layer.group_send)( self.team_group_name, { "type": "get_location", "payload": text_data, }, ) . . Get location function react-native code useEffect(() => { var ws = new WebSocket( 'ENDPOINT__URL ', ); ws.onopen = () => { console.log('connected'); ws.send( 'some data', ); }; ws.onmessage = e => { // a message was received console.log('on message block'); console.log(e.data); }; ws.onerror = e => { // an error occurred console.log('on error block'); console.log(e.message); }; ws.onclose = e => { // connection closed console.log('Connection closed'); console.log(e.code, e.reason); }; }, []); Thanks in advance. -
How to fill response model in Django REST Swagger?
In Django 1.11, I want to fill in this section: Now it's empty and seems like it's not parsed out of comments. I don't see in the docs how to add it for this version of Django. -
python path, can't use Django
i tried to install django, the installation was succeeded but i couldn't create new project. so i uninstalled and try to install again and this message showed up(didn't see it the first time): WARNING: The script django-admin.exe is installed in 'C:\Users\ASUS\AppData\Roaming\Python\Python39\Scripts' which is not on PATH. Consider adding this directory to PATH or, if you prefer to suppress this warning, use --no-warn-script-location. so i look up online and people said used sys.path.append to fix but when i used it: sys.path.append('C:\Users\ASUS\AppData\Roaming\Python\Python39\Scripts') SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 2-3: truncated \UXXXXXXXX escape. please help, i'm still new to Python and Django. -
SQL or NoSQL database for a building company website? [Django, PSQL]
I am developing a buiding company website using django on BE. I have several apps at the moment - Shop, Photo gallery, Blog. All of these apps have their own models (entities). Anyway, tables between these django-apps have no relation (i.e. Photo and Tag in photo gallery and Product, Category in shop). Even Service and Product table within one app are not related. It is not okay to have such structure in relational database, isn't it? If so, should i use a NoSQL for this project (MongoDb in priority)? Is it better to migrate to Flask to use NoSQL or there are no problems to use it in Django? -
AttributeError at /accounts/register/ 'str' object has no attribute '_meta' (Django)
I'm getting AttributeError at /accounts/register/ 'str' object has no attribute '_meta' I could have a spelling mistake in some of my files. urls.py (In project) """QuestionTime URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/3.2/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.urls import include, path 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) """ from django.contrib import admin from django.urls import include, path from django_registration.backends.one_step.views import RegistrationView from users.forms import CustomUserForm # https://django-registration.readthedocs.io/en/3.1.2/activation-workflow.html urlpatterns = [ path('admin/', admin.site.urls), path("accounts/register/", RegistrationView.as_view( form_class="CustomUserForm", success_url="/", ), name="django_registration_register"), path("accounts/", include("django_registration.backends.one_step.urls")), path("accounts/", include("django.contrib.auth.urls")), path("api-auth/", include("rest_framework.urls")), path("api/rest-auth/", include("rest_auth.urls")), path("api/rest-auth/registration/", include("rest_auth.registration.urls")), ] forms.py (in app) from django_registration.forms import RegistrationForm from users.models import CustomUser class CustomUserForm(RegistrationForm): class Meta(RegistrationForm.Meta): model = CustomUser django_registration.forms and django_registration.backends.one_step.views gets highlighted yellow in VSCODE -
Login page error - dictionary update sequence element #0 has length 0; 2 is required
I am getting an error on the login page when I log out. ValueError at /accounts/login/ dictionary update sequence element #0 has length 0; 2 is required I do not know why I get this error because I've never had such an error before. What does this error mean and how can I solve it? traceback Environment: Request Method: GET Request URL: http://127.0.0.1:8000/accounts/login/?next=/ Django Version: 3.1.4 Python Version: 3.8.10 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.humanize', 'register', 'customer', 'financial_analysis', 'ocr', 'core', 'approvals', 'crispy_forms', 'ckeditor', 'rest_framework', 'requests', 'ckeditor_uploader', 'django_filters', 'activity_log', 'djmoney', 'djmoney.contrib.exchange', 'mathfilters', 'bootstrap3', 'phone_field'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback (most recent call last): File "C:\Users\USER\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\USER\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\django\core\handlers\base.py", line 202, in _get_response response = response.render() File "C:\Users\USER\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\django\template\response.py", line 105, in render self.content = self.rendered_content File "C:\Users\USER\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\django\template\response.py", line 83, in rendered_content return template.render(context, self._request) File "C:\Users\USER\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\django\template\backends\django.py", line 61, in render return self.template.render(context) File "C:\Users\USER\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\django\template\base.py", line 168, in render with context.bind_template(self): File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.8_3.8.2800.0_x64__qbz5n2kfra8p0\lib\contextlib.py", line 113, in __enter__ return next(self.gen) File "C:\Users\USER\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\django\template\context.py", line 244, in bind_template updates.update(processor(self.request)) Exception Type: ValueError at /accounts/login/ Exception Value: dictionary update sequence element #0 has length 0; 2 is required register/urls.py from django.conf.urls import … -
Django - Media Sharing/Streaming
I'm making an application that shares locally hosted files on my server. They're all a standard format that won't need transcoding done for the web clients I'm expecting to be used, so theoretically I should just be able to serve the data through my site. The issue is, there's a lot of data. I don't really want it all public-facing at once. I want a system where a user goes to the page for the media, and it then makes the data public. As it stands all the file locations will be stored in a model, so my idea would be some sort of hard-link solution that could temporarily put it in a public-facing location. Is there a more elegant way to do something like this? Are there other frameworks that might be better suited for this use-case? -
In django python i want to get the users name as well as only the active users in the dropdown
I am having two html forms where i fill the forms and submit and show the forms right now I want two fields to be worked simultaneously I have two fields This is what I am fetching the value of database and showing in html form as dropdown <select name="assignee" required id="assignee" class="form-control"> <option hidden value="">Select Assignee</option> {% for r in b %} <option>{{r.firstname}} {{r.lastname}}</option> {% endfor %} </select> This is my status dropdown to select the assignees are active or inactive now from the above html snippet I want to do something that it only fetches the active users right now I am fetching the all users but I want to fetch only the active users and show it in the dropdown and not the inactive how can I do this if anyone knows please help. <select required name="status" id="status" class="form-control"> <option hidden value="">Select Status</option> <option value = "Active">Active</option> <option value="Inactive">Inactive</option> </select>