Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Need to show User count other data count on Django admin interface
I've created custom index.html for django admin. Here is the ScreeenShot Here count of user or model 1 is static. I want to update from database. Is there any way to pass variable from admin.py to main Admin interface? -
How do i edit/delete data from the frontend in Django?
I would like to retrieve data from my backend (postgresql) to the frontend so i can edit/delete it. I have implemented this in views.py: def update(request, id): resp = Response.objects.get(pk = id) resp.response = request.POST.get('Response') resp.save() return render(request, 'app/update', { }) urls.py: url(r'update/(\d+)/$', views.update, name="update") How would i display it in my forms? update.html: <table class="dataTable"> {% for field in qform.visible_fields %} <tr> <th>{{ field.label_tag }}*</th> <td>{{ field }}</td> </tr> {% endfor %} <tr> <th>{{ rform.Response.label_tag }}*</th> <td>{{ rform.Response }}</td> </tr> <tr> <th>{{ rform.Topic.label_tag }}*</th> <td>{{ rform.Topic }}</td> </tr> <tr> <th>{{ rform.Client.label_tag }}*</th> <td>{{ rform.Client }}</td> </tr> <tr> <th>{{ rform.Planit_location.label_tag }}*</th> <td>{{ rform.Planit_location }}</td> </tr> <tr> <th>{{ rform.Date_added.label_tag }}</th> <td>{{ rform.Date_added }}</td> </tr> <tr> <th>{{ rform.Document.label_tag }}</th> <td>{{ rform.Document }}</td> </tr> Also I am getting an Assertion error "No exception message supplied" when i try to access the url .../update -
Django Admin multiple template inheritance
I thought it was a quite simple task but turns out it's not. So, I have two different mixins to use on a Django admin class. they both have some codes in it with templates. admin.py class AdminMixin01(admin.ModelAdmin): change_form_template = "change_form1.html" class AdminMixin02(admin.ModelAdmin): change_form_template = "change_form2.html" class ModalAdmin(AdminMixin01, AdminMixin02, admin.ModelAdmin): pass change_form1.html {% extends "change_form.html" %} {% block content %} {{ block.super }} Form 1 {% endblock content %} change_form2.html {% extends "change_form.html" %} {% block content %} {{ block.super }} Form 2 {% endblock content %} it's looks quite simple both python and html sides. The problem is Django renders only first mixin's template and ignores the second mixin's template. In this case only change_form1.html rendered into original change_form.html template and no traces from change_form2.html. The python codes in the both mixin are working except html codes. Any ideas ? -
Django 1.3: Is it possible to create a Listview from 2 or more objects?
I'm a newbie in Python and I'm struggling with syntax(and old usage of it). I need to make some changes to an existing Python app which is in Django 1.3. I have an existing Listview and I want to add a new column(contactDate) from another object. Is it possible at all? Thank you in a dvance! -
Library not loaded: @rpath/libmysqlclient.21.dylib Reason: image not found Django migrate error using mysqlclient DB driver and MySQL 8 with macOS
While changing to a MySQL database from the default SQLite one that Django uses by default, I ran into this tricky error while trying to run python manage.py migrate --database mysql: Traceback (most recent call last): File "/Users/xoadra/Programming/Syntax/Python/Environments/pfitzer/lib/python3.7/site-packages/django/db/backends/mysql/base.py", line 15, in <module> import MySQLdb as Database File "/Users/xoadra/Programming/Syntax/Python/Environments/pfitzer/lib/python3.7/site-packages/MySQLdb/__init__.py", line 18, in <module> import _mysql ImportError: dlopen(/Users/xoadra/Programming/Syntax/Python/Environments/pfitzer/lib/python3.7/site-packages/_mysql.cpython-37m-darwin.so, 2): Library not loaded: @rpath/libmysqlclient.21.dylib Referenced from: /Users/xoadra/Programming/Syntax/Python/Environments/pfitzer/lib/python3.7/site-packages/_mysql.cpython-37m-darwin.so Reason: image not found The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 20, in <module> execute_from_command_line( sys.argv ) File "/Users/xoadra/Programming/Syntax/Python/Environments/pfitzer/lib/python3.7/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/Users/xoadra/Programming/Syntax/Python/Environments/pfitzer/lib/python3.7/site-packages/django/core/management/__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/Users/xoadra/Programming/Syntax/Python/Environments/pfitzer/lib/python3.7/site-packages/django/core/management/base.py", line 316, in run_from_argv self.execute(*args, **cmd_options) File "/Users/xoadra/Programming/Syntax/Python/Environments/pfitzer/lib/python3.7/site-packages/django/core/management/base.py", line 350, in execute self.check() File "/Users/xoadra/Programming/Syntax/Python/Environments/pfitzer/lib/python3.7/site-packages/django/core/management/base.py", line 379, in check include_deployment_checks=include_deployment_checks, File "/Users/xoadra/Programming/Syntax/Python/Environments/pfitzer/lib/python3.7/site-packages/django/core/management/commands/migrate.py", line 59, in _run_checks issues = run_checks(tags=[Tags.database]) File "/Users/xoadra/Programming/Syntax/Python/Environments/pfitzer/lib/python3.7/site-packages/django/core/checks/registry.py", line 71, in run_checks new_errors = check(app_configs=app_configs) File "/Users/xoadra/Programming/Syntax/Python/Environments/pfitzer/lib/python3.7/site-packages/django/core/checks/database.py", line 9, in check_database_backends for conn in connections.all(): File "/Users/xoadra/Programming/Syntax/Python/Environments/pfitzer/lib/python3.7/site-packages/django/db/utils.py", line 217, in all return [self[alias] for alias in self] File "/Users/xoadra/Programming/Syntax/Python/Environments/pfitzer/lib/python3.7/site-packages/django/db/utils.py", line 217, in <listcomp> return [self[alias] for alias in self] File "/Users/xoadra/Programming/Syntax/Python/Environments/pfitzer/lib/python3.7/site-packages/django/db/utils.py", line 202, in __getitem__ backend = load_backend(db['ENGINE']) File "/Users/xoadra/Programming/Syntax/Python/Environments/pfitzer/lib/python3.7/site-packages/django/db/utils.py", line 110, in load_backend return import_module('%s.base' % backend_name) … -
Static Files not getting loaded in Django Python
Here is the code I am trying to run: {% load staticfiles %} <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <style> body { font: 10px sans-serif; } .axis path, .axis line { fill: none; stroke: #000; shape-rendering: crispEdges; } .x.axis path { display: none; } </style> <script src="http://d3js.org/d3.v3.js"></script> <script src="http://misoproject.com/js/d3.chart.js"></script> </head> <body> <script src="{% static 'stock-line.js' %}"></script> <script src="{% static 'stock-line-app.js' %}"></script> </body> </html> Reference Link for Js and sample data: Reference link My static path is: C:\Users\aims\Desktop\mysite\static I am getting the following error in the console log: GET http://127.0.0.1:8000/static/stock-line.js 404 (Not Found) GET http://127.0.0.1:8000/static/stock-line-app.js 404 (Not Found) Cross-Origin Read Blocking (CORB) blocked cross-origin response http://misoproject.com/js/d3.chart.js with MIME type text/html. See https://www.chromestatus.com/feature/5629709824032768 for more details. GET http://127.0.0.1:8000/static/stock-line.js 404 (Not Found) GET http://127.0.0.1:8000/static/stock-line-app.js 404 (Not Found) Pease do let me know what I have missed. I have placed the respective files in the static folder. Still file is not found. It is a mystery for me. Help me solve it. -
Django Serializers - Return the sum of values by filter
Following this post: Serializer - Django REST Framework - The serializer field might be named incorrectly and not match any attribute or key on the `str` instance I use this function: def get_month_hours(self): last_year = timezone.now() - datetime.timedelta(days=365) # for more accurate result, please use python-dateutil or similar tools return Timesheet.objects.annotate(total_hour=Sum('working_hour')).filter(owner=self.user, date__gte=last_year).order_by('date') I want to populate the chart who use exactly the same code: "data": [65, 59, 80, 81, 56, 55, 40], All values corresponding to the total working_hours (my models field) per month. So, I have 2 problems: The first, I receive this data: { "id": 3, "title": "Développement intranet", "date": "2018-11-19", "working_hour": 8.5, "week": 47, "owner": 1 }, { "id": 1, "title": "Développement intranet", "date": "2018-11-26", "working_hour": 8.5, "week": 48, "owner": 1 }, { "id": 2, "title": "Développement intranet", "date": "2018-11-27", "working_hour": 8.5, "week": 48, "owner": 1 }, { "id": 4, "title": "dev python", "date": "2018-11-28", "working_hour": 5.25, "week": 48, "owner": 1 }, { "id": 5, "title": "Développement intranet", "date": "2018-12-03", "working_hour": 8.5, "week": 49, "owner": 1 } But I want to receive only one value: the sum of working_hour per month. The second problme is: how to pass this values to my "data" ? I thinked like … -
DOCSTRING IN THE FUCNTION BASED VIEW
how to add docstring to function based view so that it can be visible in the swagger UI? I have created a manual schema for each my API and its working through swagger but I need to add docstring as well example responses in the Swagger UI. -
What is python datastream and why this us used for
I am not getting Python DataStream, What is python data stream and why this is used for? Can anyone tell me about it or give me link of a good article on this? TIA -
Import error after attempt at importing Class
I attempting to to run a python script inside another python script, upon entering a webpage using Django framework. This is my views script that is running the python script tech_scripts.py import subprocess from django.shortcuts import render from .models import ConfigInfo from .forms import ConfigInfoForm from .models import dhcp from .forms import dhcpForm def post_list_three(request): from .models import ConfigInfo ConfigInfo.objects.all().delete() if request.method =="POST": form =ConfigInfoForm(request.POST) if form.is_valid(): ConfigInfo=form.save(commit=False) ConfigInfo.save() subprocess.Popen(["python3", "/home/pi/tutorial/device_interfaces/device_interfaces/tech_scripts.py","-m"]) else: form=ConfigInfoForm() return render(request, 'device_interfaces/post_edit.html', {'form':form}) So, upon opening a webpage i want the function post_list_three to be executed. The subprocess manages to run the tech_scripts file which is below #!/usr/bin/env python3 import json import re import os.path import pathlib import uuid import subprocess from models.py import ConfigInfo def info(): creds=ConfigInfo.objects.first() SSID_name=creds.SSID psk_name=creds.psk sIP=creds.sIP netmask=creds.netmask gateway=creds.gateway netwrokIP=creds.networkIP broadcast=creds.broadcast dns_servers=creds.dns_servers config['ssid']=getattr(creds,SSID_name) config['password']=getattr(creds,psk_name) config['StatIP']=getattr(creds,sIP) config['Netmask']=getattr(creds,netmask) config['gateway']=getattr(creds,gateway) config['Network']=getattr(creds,networkIP) config['Broadcast']=getattr(creds,broadcast) config['DNS']=getattr(creds,dns_servers) jstring = json.dumps(config) with open("/home/techuser/config.json", "w+") as handle: handle.write(jstring) However, when going to my website after launching it using python3 manage.py rserver 192.168.1.150:8000 I get a traceback , [03/Dec/2018 09:51:24] "POST /post/new/static HTTP/1.1" 200 1884 Traceback (most recent call last): File "/home/pi/tutorial/device_interfaces/device_interfaces/tech_scripts.py", line 9, in <module> from models.py import ConfigInfo File "/home/pi/tutorial/device_interfaces/device_interfaces/models.py", line 7, in <module> class ConfigInfo(models.Model): File "/home/pi/tutorial/device_interfaces/myvenv/lib/python3.5/site-packages/django/db/models/base.py", line 87, … -
Django not fetch the static file csv
I am trying to run the following example of D3 with the Django framework: {% load staticfiles %} <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta http-equiv="cache-control" content="max-age=0" /> <meta http-equiv="cache-control" content="no-cache" /> <meta http-equiv="expires" content="0" /> <meta http-equiv="expires" content="Tue, 01 Jan 1980 1:00:00 GMT" /> <meta http-equiv="pragma" content="no-cache" /> <style> body { font: 10px sans-serif; background-color: #151512;; color: #FFF; } text { fill: white; } h1 { text-transform: uppercase; padding-left: 180px; } .axis path, .axis line { fill: none; stroke: #FFF; shape-rendering: crispEdges; } .line { stroke: #FFF; fill: none; stroke-width: 0.75px; } .line.close{ stroke: steelblue; } .summary.Close { color: steelblue; } .legend.Close { fill: steelblue; } .line.volume { stroke: indianred; } .summary.Volume { color: indianred; } .legend.Volume { fill: indianred; } .line.high { stroke: #aa81c5; } .summary.High { color: #aa81c5; } .legend.High { fill: #aa81c5; } .line.low { stroke: #7fc9bd; } .summary.Low { color: #7fc9bd; } .legend.Low { fill: #7fc9bd; } .invisible { fill: grey; } .overlay { pointer-events: all; } .focus line { stroke: white; stroke-dasharray: 3 3; opacity: .5; } .brush .extent { stroke: orange; fill: orange; fill-opacity: .125; shape-rendering: crispEdges; } #popup { left: 100px; top: 100px; width: 128px; background-color: rgba(255,255,255,0.2); font-size: 16px; position: absolute; padding: … -
How to get data from Django Many-Many relationship?
How to get all product for every order on Templates. Please help me Model.py class Order(models.Model): customer_id= models.ForeignKey(Customers ) delivery_add_id= models.ForeignKey(DeliveryAddresses) class OrderItem(models.Model): order_id = models.ForeignKey(Order, related_name='orderId') product_id = models.ForeignKey('Products', related_name='productId') class Products(models.Model): cat_id = models.ForeignKey('Categories') name = models.CharField(max_length=200) price = models.FloatField() Templates <tr> <th>Product ordered</th> <td> <ul> {% for prod in order.orderId.productId.product_set.all%} <li>{{pro}}</li> {% endfor %} </ul> {{order.orderId.productId.product_set.all}} </td> </tr> https://i.stack.imgur.com/XJ3zG.png Views.py class productList(ListView): model= Products context_object_name = 'product_list' def get_queryset(self): return Products.objects.all() class productDetail(DetailView): context_object_name = 'product' model = Products queryset = Products.objects.all() class orderList(ListView): model = Order context_object_name= 'order_list' def get_queryset(self): return Order.objects.all() class orderDetail(DetailView): context_object_name ='order' model = Order queryset= Order.objects.all() This is the general relationship I have set up.I'm trying to do is, in a templates, i want to show all product for every order. Order-product : many to many relationship. Please help me -
How can i show sub-category in category into data collapse, Using Djagno
I want to show subcategory in category into data collapse using django. As I am a noob developer that's why i can't understand the logic. Category and Sub-Category model is, category.py class Category(models.Model): category = models.CharField(max_length=120) timestamp = models.DateTimeField(auto_now_add=True) subcategory.py class SubCategory(models.Model): sub_category = models.CharField(max_length=120) category = models.ForeignKey(Category, on_delete=models.CASCADE, null=True, blank=True) timestamp = models.DateTimeField(auto_now_add=True) I wanna show those value using generic.ListView views.py class PagetListView(ListView): model = ModelName template_name = 'template.html' context_object_name = 'main_content' def get_context_data(self, *args, **kwargs): context = super().get_context_data(*args, **kwargs) context['category_list'] = Category.objects.all() # context['sub_category'] = return context I wanna show just like this, -
Google App Engine python37 build error error: `pip_download_wheels` returned code: 1
I am using Django REST based framework to deploy on Google App engine and my python pip req.txt file is as following asn1crypto==0.24.0 astroid==2.1.0 boto3==1.9.55 botocore==1.12.55 certifi==2018.8.13 cffi==1.11.5 chardet==3.0.4 colorama==0.4.1 coreapi==2.3.3 coreschema==0.0.4 cryptography==2.4.2 defusedxml==0.5.0 Django==2.1 django-allauth==0.36.0 django-filter==2.0.0 django-rest-auth==0.9.3 django-rest-swagger==2.0.7 djangorestframework==3.8.2 djangorestframework-jwt==1.11.0 docutils==0.14 idna==2.7 isort==4.3.4 itypes==1.1.0 Jinja2==2.10 jmespath==0.9.3 lazy-object-proxy==1.3.1 lxml==4.2.5 MarkupSafe==1.0 mccabe==0.6.1 oauthlib==2.1.0 openapi-codec==1.3.2 Pillow==5.3.0 pycparser==2.19 PyJWT==1.6.4 pylint==2.2.2 PyMySQL==0.9.2 python-dateutil==2.7.5 python-social-auth==0.3.6 python3-openid==3.1.0 pytz==2018.5 requests==2.19.1 requests-oauthlib==1.0.0 s3transfer==0.1.13 simplejson==3.16.0 six==1.11.0 social-auth-app-django==3.1.0 social-auth-core==2.0.0 typed-ast==1.1.0 uritemplate==3.0.0 urllib3==1.23 virtualenv==16.0.0 wrapt==1.10.11 Here is my app.yaml file and my project runs fine on local pip venv but when i # [START django_app] runtime: python37 handlers: # This configures Google App Engine to serve the files in the app's static # directory. - url: /static static_dir: static/ # This handler routes all requests not caught above to your main app. It is # required when static routes are defined, but can be omitted (along with # the entire handlers section) when there are no static files defined. - url: /.* script: auto # [END django_app] try to deploy it on google app engine using the following command i am getting following error on build time using following article https://cloud.google.com/python/django/appengine gcloud app deploy Error from Build log:- ERROR: build step … -
How to shuffle model also ArrayField values within each row in Django?
I have an MCQ model with an ArrayField. I want to shuffle or randomly sort the model data rows and the ArrayField values on each row while loading the page. ArrayField contains data in following formats- {{"London", "NYC", "Sydney", "CA"}} At present, I can only randomly sort the data rows without the ArrayField values. sorted(MCQ.objects.filter(), key=lambda x: random.random()) -
How to tag a comment with the blog post in django?
i am new to django and am currently working on the diy blog project to improve my understanding. I am trying to insert a comment form for my viewers using the CreateView template. Viewers will need to log in to type their comment. Their username will be tagged to the comment for the respective blog without them needing to indicate anything. However, i am only able to tag their comment with their username but not to the blog post. I am not sure why. Below is my code that is stored in the (view.py) class CommentCreate(LoginRequiredMixin,CreateView): model = Comment fields = ['comment','blog'] template_name = 'catalog/blog_comment.html' def get_context_data(self, **kwargs): context = super(CommentCreate, self).get_context_data(**kwargs) context['blog'] = get_object_or_404(Blog, pk = self.kwargs['pk']) return context def form_valid(self, form): form.instance.author = self.request.user return super(CommentCreate, self).form_valid(form) def get_success_url(self): return reverse('blog-detail', kwargs={'pk': self.kwargs['pk'],}) Any advice is appreciated. Thank you. -
Firebase FCM push notifications not show on iOS 12
I am using python 3 and Django framework with Firebase FCM to send push notifications from an iOS device. The push notifications did not show on device, until yesterday. When I now send a push notification, everything shows successful, but nothing is received on the device. If I send directly via a curl request, this is the response: {'failure': 0, 'canonical_ids': 0, 'success': 1, 'multicast_ids': [8348728835412078810], 'topic_message_id': None, 'results': [{'message_id': '0:1543820637538874%6467bacd6467abcd'}]} If I send from the Notification dashboard on the firebase console, it shows successfully completed. I have done the following with no success: Locked in pod for, 'Firebase/Core' and 'Firebase/Messaging'. Generated a new APN key on developer console and replaced the existing key on FCM setup in Firebase. Downloaded a fresh GoogleService-Info.plist and replaced existing Checked that bundle id's etc all match. Updated firebase pods to latest versions Turned message swizzling off in info.plist file (i.e. FirebaseAppDelegateProxyEnabled = No) Setting Messaging.messaging().shouldEstablishDirectChannel = true Made sure remote notification in Capabilities are still turned on -
Django: CSRF cookie not set. CSRF cookie does not exists
I have a Django application that serve with uwsgi and nginx. Sometimes when login, There isn't csrf cookie in browser cookie and does not renew when refresh browser. In login receive "CSRF cookie not set." error and after clean cookie this issue has solved. I used Django runserver for run app and i still have this issue. my setting is: MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.locale.LocaleMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'debug_toolbar.middleware.DebugToolbarMiddleware', 'app.middlewares.apply_all_requests.SetDefaultLanguage',] SESSION_EXPIRE_AT_BROWSER_CLOSE = True SESSION_COOKIE_SECURE = False SESSION_COOKIE_AGE = 10 * 60 * 60 SESSION_SAVE_EVERY_REQUEST = True -
I want to add products to my cart and display the cart details..I am not able to understand why the code is not showing the details on the page?
class Cart(object): def __init__(self, request): self.session = request.session cart = self.session.get(settings.CART_SESSION_ID) if not cart: cart = self.session[settings.CART_SESSION_ID] = {} self.cart = cart def add(self, product, quantity=1, update_quantity=False): product_id = str(product.id) if product_id not in self.cart: self.cart[product_id] = {'quantity': 0, 'price': str(product.price)} if update_quantity: self.cart[product_id]['quantity'] = quantity else: self.cart[product_id]['quantity'] += quantity self.save() def save(self): self.session[settings.CART_SESSION_ID] = self.cart self.session.modified = True def remove(self, product): product_id = str(product.id) if product_id in self.cart: del self.cart[product_id] self.save() def __iter__(self): product_ids = self.cart.keys() products = Product.objects.filter(id__in=product_ids) for product in products: self.cart[str(product.id)]['product'] = product for item in self.cart.values(): item['price'] = Decimal(item['price']) item['total_price'] = item['price'] * item['quantity'] yield item def __len__(self): return sum(item['quantity'] for item in self.cart.values()) def get_total_price(self): return sum(Decimal(item['price']) * item['quantity'] for item in self.cart.values()) def clear(self): del self.session[settings.CART_SESSION_ID] self.session.modified = True This is my cart.py file... {% load static %} {% block title %} Your Shopping Cart {% endblock %} {% block content %} <div class="container"> <div class="row" style="margin-top: 6%"> <h2>Your Shopping Cart <span class="badge pull-right"> {% with totail_items=cart|length %} {% if cart|length > 0 %} My Shopping Order: <a href="{% url "cart:cart_detail" %}" style="color: #ffffff"> {{ totail_items }} item {{ totail_items|pluralize }}, Kshs. {{ cart.get_total_price }} </a> {% else %} Your cart is empty. … -
Serializer - Django REST Framework - The serializer field might be named incorrectly and not match any attribute or key on the `str` instance
I want to populate a chartJs exactly like the example: https://www.chartjs.org/docs/latest/charts/bar.html I obtain this error: AttributeError at /timesheet/json-month/ Got AttributeError when attempting to get a value for field `working_hour` on serializer `TimesheetSerializer`. The serializer field might be named incorrectly and not match any attribute or key on the `str` instance. Original exception text was: 'str' object has no attribute 'working_hour'. With this model: class Timesheet(models.Model): owner = models.ForeignKey(User, on_delete = models.CASCADE) title = models.CharField(max_length = 64, verbose_name = _("Title")) date = models.DateField(default=datetime.datetime.now()) working_hour = models.FloatField(verbose_name = _("Working time")) week = models.IntegerField(verbose_name = "working week") def __str__(self): return "{}".format(self.title) def save(self, *args, **kwargs): if not self.pk: self.week = datetime.datetime.strptime("{}".format(self.date), "%Y-%m-%d").isocalendar()[1] super(Timesheet, self).save(*args, **kwargs) I serialize my data like that (into my view): def get_month_hours(self): cursor = connection.cursor() cursor.execute(""" SELECT MONTH(date), SUM(working_hour) FROM timesheet_timesheet WHERE owner_id = %s AND date >= MONTH(CURRENT_TIMESTAMP) - 12 GROUP BY MONTH(date) """, [self.user]) row = cursor.fetchone()[0] return str(row) @api_view(['GET']) def timesheet_total_per_month(request): hours = ReturnHour(request.user.pk, datetime.datetime.now().isocalendar()[1]) timesheets = hours.get_month_hours() serializer = TimesheetSerializer(timesheets, many=True, read_only = True) return Response(serializer.data) Into my serializers.py: class TimesheetSerializer(serializers.ModelSerializer): class Meta: model = Timesheet fields ='__all__' def create(self, validated_data): """ Create and return a new `Snippet` instance, given the validated data. """ return … -
Setting Initial Field in Django
I have a model form and I am trying to pass an initial value to one of the fields when I call the form from the view. My view has the following: threadform = ThreadForm(text="hello") The model form is as below: class ThreadForm(ModelForm): class Meta: model = Thread fields = ['title'] def __init__ (self,*args, **kwargs): self.fields['title'].initial = kwargs.pop("text") super (ThreadForm, self).__init__(*args, **kwargs) This will give the error "ThreadForm" has no attribute 'fields'. If I reverse the super call then get "init() got an unexpected keyword argument 'text'". Please can someone help as I can't find any information on the correct way to do this as others seem to be setting a hard coded initial value, but mine is dynamic as I want to replace the literal "hello" with data from a model. -
Add GET parameter to the url name - Django
Currently I can pass a GET parameter from my html template like this. <a href="display-associations/players/?association={{ association.user.username }}">View Players</a> But can I do it through a url name parameter? I want something like following. <a href="{% url 'player-registration' %}">Add Player</a> I cannot figure out how to add GET parameter to the url-name. -
405 “Method POST is not allowed” in Django REST framework
I'm using Django REST framework to implement Get, Post api methods, and I got GET to work properly. However, when sending a post request, it's showing 405 error below. What am I missing here? 405 Method Not Allowed {"detail":"Method \"POST\" not allowed."} Sending this body via post method { "title": "abc" "artist": "abc" } I have api/urls.py from django.contrib import admin from django.urls import path, re_path, include urlpatterns = [ path('admin/', admin.site.urls), re_path('api/(?P<version>(v1|v2))/', include('music.urls')) ] music/urls.py from django.urls import path from .views import ListSongsView urlpatterns = [ path('songs/', ListSongsView.as_view(), name="songs-all") ] music/views.py from rest_framework import generics from .models import Songs from .serializers import SongsSerializer class ListSongsView(generics.ListAPIView): """ Provides a get method handler. """ queryset = Songs.objects.all() serializer_class = SongsSerializer music/serializers.py from rest_framework import serializers from .models import Songs class SongsSerializer(serializers.ModelSerializer): class Meta: model = Songs fields = ("title", "artist") models.py from django.db import models class Songs(models.Model): # song title title = models.CharField(max_length=255, null=False) # name of artist or group/band artist = models.CharField(max_length=255, null=False) def __str__(self): return "{} - {}".format(self.title, self.artist) -
How to sent FCM token to django application
I have django web application and Android WebView application which simply open url of my web site. I would like to sent notification to users. I know that i need to use django-fcm. But there is problem how to sent FCM token from Android App to my django app and bind it to user. There is one idea to sent FCM token to server during user auth sent GET or POST request to server, then put it to the model like token and request.user. But i don't have any knowladge in Android development. Please if you have some ready examples provide it. -
django.core.exceptions.ImproperlyConfigured: Requested setting DEFAULT_INDEX_TABLESPACE
Help me fix error - django_celery/ - my_app/ - __init__.py - task.py - proj/ - __Init__.py - celery.py - settings.py - manage.py proj/init.py : from __future__ import absolute_import, unicode_literals from .celery import app as celery_app __all__ = ('celery_app',) proj/celery.py : from __future__ import absolute_import,unicode_literals import os from celery import Celery from django.conf import settings from django_celery_beat.models import PeriodicTasks os.environ.setdefault('DJANGO_SETTINGS_MODULE','proj.settings') app = Celery('proj') app.config_from_object('django.conf:settings') app.autodiscover_tasks(lambda: settings.INSTALLED_APPS) proj/settings.py : import os os.urandom(24) SECRET_KEY = os.urandom(24) BROKER_URL = 'redis://localhost:6379/0' CELERY_RESULT_BACKEND = 'redis://localhost:6379/0' CELERY_ACCEPT_CONTENT = ['application/json'] CELERY_RESULT_SERIALIZER = 'json' CELERY_TIMEZONE = 'Asia/Seoul' CELERY_BEAT_SCHEDULE = { 'task-number-one': { 'task': 'my_app.tasks.add', 'schedule': 10, 'args': (10,5) }, } INSTALLED_APPS = ( 'django_celery_beat', ) my_app/task.py from __future__ import absolute_import,unicode_literals from celery import shared_task,task @task def add(x, y): return x + y I am getting error: django.core.exceptions.ImproperlyConfigured: Requested setting DEFAULT_INDEX_TABLESPACE, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings.