Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
ModuleNotFound error when trying to do a RequestFactory()
I'm trying to create a python script that runs in the background and periodically runs a view (Celery can't be installed on Azure, django-cron doesn't work). I found that you can use RequestFactory() to generate a request, but I get the following error: ModuleNotFoundError: No module named 'pcbuilder' Here is my external script: from django.contrib.auth.models import AnonymousUser, User from django.test import RequestFactory, TestCase from .views import update factory = RequestFactory() factory = RequestFactory() user = User.objects.get(username='user') request = factory.get('/update') request.user = user response = update(request) As a side question: I had to set my DJANGO_SETTINGS_MODULE environment variable in CMD, is there a way to do it from the .py file itself? -
Restricting one like per post in Django
I am a beginner in Django currently. I want to restrict one like per post in my so Posting kind of app, where you can post a text and user can like or dislike the same. Now I enabled Login and I want a logged in user to like a post only once and I am unsuccessfull in doing so. from django.db import models from django.contrib.auth.models import User # Create your models here. class Todo(models.Model): text = models.CharField(max_length=100) complete = models.BooleanField(default=False) like=models.IntegerField(default=0) user = models.ForeignKey(User) def __str__(self): return self.text ------------------------------views.py---------------------------- def like(request,todo_id): if Todo.objects.filter(todo_id = todo_id, user_id=request.user.id).exists(): return redirect('index') else: todo = Todo.objects.get(pk=todo_id) todo.like += 1 todo.save() return redirect('index') -
How to solve Django 'ModuleNotFoundError' ___main___.models
I would like to import a module into my views.py file. I tried different SO solutions like checking for ___init.py___ available in my app and for installed_apps in the settings. Everything seems to be set up properly. Still I get the error. What's happening? Here I would like to import the module: from django.shortcuts import render from .models.py import ratesEUR import json import requests response = requests.get("http://data.fixer.io/api/latest?access_key=XXX&base=EUR") rates_EUR = json.loads(response.content.decode('utf-8')) timestamp = rates_EUR['timestamp'] base = rates_EUR['base'] date = rates_EUR['date'] rates = rates_EUR['rates'] id = 1 rates_new = ratesEUR(id=id, timestamp=timestamp, base=base, date=date, rates=rates) rates_new.save() def render_Quotes_app(request, template="Quotes_app/templates/Quotes_app/Quotes_app.html"): return render(request, template) This is the error occuring: Traceback (most recent call last): File "C:\Users\Jonas\Desktop\dashex\Quotes_app\views.py", line 2, in <module> from .models.py import ratesEUR ModuleNotFoundError: No module named '__main__.models'; '__main__' is not a package [Finished in 0.373s] My settings: import os.path import os BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/2.2/howto/static-files/ STATIC_ROOT = '' STATIC_URL = '/static/' STATICFILES_DIRS = (os.path.join('static'), ) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.2/howto/deployment/checklist/ # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'Quotes_app', … -
Django : Systemd Startup Script Not Running
I am running a custom service (skybot.service) that starts a Django server on PC bootup. The service code is below Description=SkybotService [Service] WorkingDirectory=/home/saurabh/Software/skybot/skybot ExecStart=/usr/bin/python3 manage.py runserver 0.0.0.0:8000 Type=simple StandardOutput=syslog StandardError=syslog SyslogIdentifier=skybot-api [Install] WantedBy=multi-user.target I can see that my service is active and running as given below skybot.service - SkybotService Loaded: loaded (/etc/systemd/system/skybot.service; enabled; vendor preset: enabled) Active: active (running) since Mon 2019-11-11 23:49:55 IST; 14min ago Main PID: 4708 (python3) Tasks: 2 (limit: 4569) CGroup: /system.slice/skybot.service ├─4708 /usr/bin/python3 manage.py runserver 0.0.0.0:8000 └─4710 /usr/bin/python3 manage.py runserver 0.0.0.0:8000 But I am not able to open http://system_ip:8000 in the browser. Though, Server link works when I execute runserver command directly in the WorkingDirectory on the terminal. Please help. -
problem installing django-heroku on macos
While installing django-heroku on macOS catalina 10.15.1, I get the following error: ld: library not found for -lssl clang: error: linker command failed with exit code 1 (use -v to see invocation) error: command 'xcrun' failed with exit status 1 At first, it was giving the following error: The error is pg_config is required to build psycopg2 from source. So I searched on StackOverflow and I installed PostgreSQL with homebrew: brew install postgresql as they described and linked it with brew link postgresql and this seemed to installed fine. But now clang cannot link the lssl. I don't understand if this is a problem related to path or permissions. Any help will be really appreciated! -
How to save the user input in the django-filter form field to database (equivalent of form.save())?
I am using django-filter to filter my results according to the user input of a few fields. It works great.I have a "Search" button which filters the result according to the user input and now I want to add another button which should save the user input in some fields to a particular database (I have 2 databases). How would I achieve this? If it was a normal form I usually to form.save() to save the data. But here it is a form generated by django-filter <form method="post" id="info-form"> {% csrf_token %} <div class="well"> <h4 style="margin-top: 0">Filter</h4> <div class="row"> <div class="form-group col-sm-4 col-md-3"> {{ filter.form.title.label }} {% render_field filter.form.title class="form-control" %} </div> <div class="form-group col-sm-4 col-md-3"> {{ filter.form.id.label }} {% render_field filter.form.id class="form-control" %} </div> <button type="submit" class="btn btn-primary" name="display" value="Display"> <span class="glyphicon glyphicon-search"></span> Search </button> All of this works great. Now I'm adding a new button like so: <button type="submit" action="update" class="btn btn-primary" form="info-form" name="save" value="Save">Add</button> This is the views.py: def a_view(request) a_list = ARecords.objects.select_related(‘bid’).filter(…) filter = ItemFilter(request.POST, queryset=a_list) return render(..) Here I would have to change it to the following to take different actions according to the button clicked def a_view(request) a_list = ARecords.objects.select_related(‘bid’).filter(…) filter = ItemFilter(request.POST, queryset=a_list) … -
Django On-Click Event Not Triggering
I have this web application that I'm creating that tracks the projects that a user is working on or has completed in the past. I'm trying to use the tags in the template in order to ask for a confirmation before they create a new project only when they have inputted a name that already exists in another category. The problem with what I have so far is that it never triggers the on-click event even though the conditions are fulfilled. models.py CATEGORY_CHOICES = ( ('ongoing','Ongoing'), ('done','Done'), ) class Project(models.Model): user=models.ForeignKey(User, null=True, blank=True, on_delete=models.CASCADE) category = models.CharField(max_length=7, choices=CATEGORY_CHOICES, default='ongoing') name = models.CharField(max_length=100) views.py @login_required def projects(request): context = { 'projects' : Project.objects.all(), 'profiles' : Profile.objects.all() } if request.method == 'POST': ongoing_list = Project.objects.filter(Q(category="Ongoing")).values('name') done_list = Project.objects.filter(Q(category="Done")).values('name') ong = [] don = [] for i in ongoing_list: for k, v in i.items(): if v not in ong: ong.append(v) for i in done_list: for k, v in i.items(): if v not in don: don.append(v) form = ProjectForm(request.POST) if form.is_valid(): name = form.cleaned_data.get('name') category = form.cleaned_data.get('category') user=request.user Project.objects.create( user=user, name=name, category=category, ).save() return render(request, 'users/projects.html', context) projects.html <form method = "POST"> {% csrf_token %} <div class="form-group"> <label for="name">Name</label> <input name="name" class="form-control" id="name"> </div> … -
Django "NoReverseMatch" error when trying to call a function in views from html
I am trying to display a User's name on top of a box where they enter their Employee # in a form, without having to refresh the page. For example, they enter their # and then after they click/tab onto the next field, it renders their name on top, which comes from the database, so the user knows they've entered the correct info. This name is stored in a separate model, so I try to retrieve it using the "id/number". I am not too familiar with AJAX but after reading a few similar questions it seems like an AJAX request would be the most appropriate way to achieve this. I tried to make a function get_employee_name that returns the name of the person based on the way I saw another ajax request worked, but I'm not sure how to implement this so it displays after the # is entered. I get this error when trying to see the page now, I'm not sure where I'm passing the "id/employee_number" incorrectly which is causing this to show: django.urls.exceptions.NoReverseMatch: Reverse for 'ajax_get_employee_name' with no arguments not found. 1 pattern(s) tried: ['operations/ajax\\/get\\-employee\\-name\\/(?P<id>[0-9]+)\\/$'] models.py class EmployeeWorkAreaLog(TimeStampedModel, SoftDeleteModel, models.Model): employee_number = models.ForeignKey(Salesman, on_delete=models.SET_NULL, help_text="Employee #", null=True, … -
why are prefix-TOTAL_FORMS, prefix-INITIAL_FORMS, prefix-MIN_NUM_FORMS, prefix-MAX_NUM_FORMS of management_form lists?
Below is the POST data being sent from my form back to the view. This is resulting in Validation Error ['ManagementForm data is missing or has been tampered with'] <QueryDict: { "csrfmiddlewaretoken": ["..."], "project_title": ["project test"], "project_number": ["543219876"], "project_status": ["Active"], "project_initiation_date": ["2019-10-10"], "project_alias": ["alias"], "project_description": ["description"], "estimated_total_cost": ["100"], "project_type": ["Capital"], "project_start_date": ["2019-09-16"], "project_end_date": ["2019-10-10"], "city_department": ["CDD"], "fundingsource_set-TOTAL_FORMS": ["2", ""], "fundingsource_set-INITIAL_FORMS": ["0", ""], "fundingsource_set-MIN_NUM_FORMS": ["0", ""], "fundingsource_set-MAX_NUM_FORMS": ["1000", ""], "fundingsource_set-0-funding_source_number": ["876543"], "fundingsource_set-0-funder": ["cve"], "fundingsource_set-0-funder_contact": ["scott"], "fundingsource_set-0-contract_number": ["876543"], "fundingsource_set-0-phone_0": ["123456789"], "fundingsource_set-0-phone_1": [""], "fundingsource_set-0-email": ["mar@gmail.com"], "fundingsource_set-0-funds_type": ["Loan"], "fundingsource_set-0-funding_amount": ["30"], "fundingsource_set-0-percentage_of_funding": ["30"], "fundingsource_set-0-funding_agency_type": ["Federal"], "fundingsource_set-0-is_awarded": ["on"], "fundingsource_set-0-is_being_leveraged": ["on"], "fundingsource_set-0-funding_doc_type": ["MOU"], "fundingsource_set-0-date_funding_doc_submitted": ["2019-10-10"], "fundingsource_set-0-date_project_budget_docs_submitted": ["2019-10-10"], "fundingsource_set-0-have_funding_reimbursement_requests": ["true"], "fundingsource_set-0-date_funding_reimbursement_request_docs_submitted": ["2019-10-10"], "fundingsource_set-1-funding_source_number": ["987123"], "fundingsource_set-1-funder": ["observian"], "fundingsource_set-1-funder_contact": ["aravind"], "fundingsource_set-1-contract_number": ["987123"], "fundingsource_set-1-phone_0": ["123456678"], "fundingsource_set-1-phone_1": [""], "fundingsource_set-1-email": ["mar@gmail.com"], "fundingsource_set-1-funds_type": ["Loan"], "fundingsource_set-1-funding_amount": ["33"], "fundingsource_set-1-percentage_of_funding": ["33"], "fundingsource_set-1-funding_agency_type": ["Federal"], "fundingsource_set-1-is_awarded": ["on"], "fundingsource_set-1-is_being_leveraged": ["on"], "fundingsource_set-1-funding_doc_type": ["MOU"], "fundingsource_set-1-date_funding_doc_submitted": ["2019-10-10"], "fundingsource_set-1-date_project_budget_docs_submitted": ["2019-10-10"], "fundingsource_set-1-have_funding_reimbursement_requests": ["true"], "fundingsource_set-1-date_funding_reimbursement_request_docs_submitted": ["2019-10-10"], } > This form has 1 instance of the parent form and 2 instances of the child form in Inline formset. 'fundingsource_set-TOTAL_FORMS': ['2', ''], 'fundingsource_set-INITIAL_FORMS': ['0', ''], 'fundingsource_set-MIN_NUM_FORMS': ['0', ''], 'fundingsource_set-MAX_NUM_FORMS': ['1000', ''] are they supposed to be lists? and if so, what does each item in the list indicate? -
How to display options as modal instead of select dropdown?
i'm newbie and want to use React as front end and django as back end ( + axios to get data from api ) i want that when a user click on a input/div react displays my data from back end as a select option to select that axio api data and put em into that input/div div, i don't know that i mean well or not, but anyone knows how this codes look like? -
Django rest framework: Foreign key instance is not being passed to validated_data
I'm trying to save data to my database using ModelSerializer but when I pass a ForeignKey instance, it gets converted to the field value after calling is_valid(). I need to pass the instance instead of the value because my Model contains an attribute with a Foreign key and that same attribute is included in unique_together set in the model. My problem is basically the same as this question I checked with the Pycharm Debugger that the foreign key I pass into the serializer remains a Model instance only until the is_valid() is called. As soon as the is_valid() method is called, the foreign key converts to the PK or to the value of a field(if to_field is defined in the model) which ultimately results in the following kind of error: ValueError at /app/core/create-trip Cannot assign "'ChIJTWE_0BtawokRVJNGH5RS448'": "CityAttrRtTb.attr_nm" must be a "CityAttrn" instance. The error above shows that the CityAttrn instance was converted to its respective field value after calling is_valid(). The question I linked to above has an answer that I need to pass the foreign key as an argument to the save() method of the serializer. I can do that if I only have one data. However, I am … -
Aggregation for query items with the same field value
One of my querysets returns list of items with several fields: <QuerySet [{'name': 'John', 'products': 4}, {'name': 'John', 'products': 6}, {'name': 'Sam', 'products': 7}, ...]> How do I aggregate this data to get combined Sum() of products value for elements with the same name field to avoid duplicates in queryset, so as a result I'll have something like this: <QuerySet [{'name': 'John', 'products': 10}, {'name': 'Sam', 'products': 7}, ...]> I understand this should be done using .annotate() or .aggregate() queries but I can't figure out how. -
Django: Extracting the value from a Queryset and store in a variable for filtering later on
I would like to extract a value from a queryset and then store it in a variable so that I can use it as a filter criterion later on. How may I do this? This userprofile model is linked to the User model hence the User.id would be the same as the user_id in userprofile model: class userprofile(models.Model): user=models.OneToOneField(User, ...) age=.... user_race=models.Charfield(.....) I want to get the race of this user and store it as a variable "x", so when I query the following way: x = userprofile.objects.filter(user_id=request.user.id).user_race #doesn't seem to get the race of this user...how to get it? Question: is "x" now a string variable or still a queryset in the form of a list of dictionary? Then I want to use "x" as the criterion when filtering for another queryset using the following model: class cuisines(models.Model): portion=.... race=models.Charfield(.....) Query: y = cuisines.objects.filter(race='x') #This is to get all the results as long as the race of the user matches the race value in the cuisines model. Please help me in better understanding where I have gone wrong in this logic/process. thank you. -
How to run a function in views.py from another Python file
So I'm trying to create a script which will run a function in a views.py, but because the function in views.py involves a request argument which needs a user attribute to work, I'm getting an error. Here is my external Python code: import django import time from django.http import request import os, sys PACKAGE_PARENT = '..' SCRIPT_DIR = os.path.dirname(os.path.realpath(os.path.join(os.getcwd(), os.path.expanduser(__file__)))) sys.path.append(os.path.normpath(os.path.join(SCRIPT_DIR, PACKAGE_PARENT))) if __name__ == '__main__' and __package__ is None: from os import sys, path os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'pcbuilder.settings') django.setup() sys.path.append(path.dirname(path.dirname(path.abspath(__file__)))) from cpu.views import update update(request) And here is an excerpt of my views.py: def update(request): current_user = request.user #... Here is the error I'm getting: AttributeError: module 'django.http.request' has no attribute 'user' -
How To Set Permission Class Based On Request Type In Django Rest Framework?
I have a DRF ModelViewSet where all requests should have the IsAuthenticated permission class with the exception of POST requests, which I want to have the AllowAny permission class. Is there a way to do that? Here's what I have so far: from rest_framework.permissions import IsAuthenticated, AllowAny, BasePermission from rest_framework.viewsets import ModelViewSet from .serializers import CustomerSerializer from .models import Customer class CustomerViewSet(ModelViewSet, BasePermission): queryset = Customer.objects.all() serializer_class = CustomerSerializer permissions = [AllowAny, IsAuthenticated] def has_permission(self, request, view): if request.method == "POST": return True else: return False This only works when credentials are provided, for all request types including POST. Thanks in advance! -
django datetime filter not working in template
i can't filter models.DateTimeField(default=timezone.now) in the template in my template i used |date:"F d, Y" to filter date. it's showing raw string instead of filtering, however if i remove :"F d, Y" then it's working models.py from django.db import models from django.utils import timezone from django.contrib.auth.models import User # Create your models here. class Post(models.Model): title = models.CharField(max_length=100) content = models.TextField() date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.title template {% extends 'blog/base.html' %} {% block content %} {% for post in posts %} <article class="media content-section"> <div class="media-body"> <div class="article-metadata"> <a class="mr-2" href="#">{{ post.author }}</a> <small class="text-muted">{{ post.date_posted | date: "F d, Y" }}</small> </div> <h2> <a class="article-title" href="#">{{ post.title }}</a> </h2> <p class="article-content">{{ post.content }}</p> </div> </article> {% endfor %} {% endblock content %} what is the possible reason for this and how to fix this ? -
Next Page / Previous Page not working for Django pagination
I was hoping someone could help me with a pagination question. I am trying to use Django pagination following the information on this page (https://docs.djangoproject.com/en/2.2/topics/pagination/). Whilst I have successfully displayed the correct number of items on the first page and the last page works, the next and previous pages keep taking me to the first page. I think the issue may revolve around the ‘request’ element and I’m not sure if I am picking up an incorrect version. The example states:- def listing(request): contact_list = Contacts.objects.all() paginator = Paginator(contact_list, 25) # Show 25 contacts per page page = request.GET.get('page') contacts = paginator.get_page(page) return render(request, 'list.html', {'contacts': contacts}) The command: page = request.GET.get(‘page’) returns “AttributeError: 'Request' object has no attribute 'GET'” By replacing this code with: page = request.args.get('page', type=int) the code successfully renders the first (and last) page but next and previous do not work. As background I built my system on the Flask megatutorial but I have been unable to use that pagination, I understand because I haven’t used the Flask SQL Alchemy for creating and updating databases. My routes file has from flask import request Should I replace this with another utility's “request” and if so, which? -
Filtering out null values from a table in django
so I'm trying to create a view of a table on a different page which removes all the records where dep_time=' ' views.py: from postlog.models import Flight, DepartureTime def HomePageView(request): val = DepartureTime.objects.exclude(dep_time__exact='') val = val.values('fl_no') links = [None]*val.count() for i in range(val.count()): links = Flight.objects.filter(fl_no=int(val[i].get('fl_no'))) args = { 'links' : links } return render(request, 'base_home.html', args) HTML file: {%extends 'base_template1.html' %} {% load static from staticfiles %} {% load crispy_forms_tags %} <!DOCTYPE html> {% block title %} Home {% endblock %} {% block content %} <table class="table table-bordered" id="departures"> <thead> <tr> <th class="text-center" scope="col">Flight Number</th> <th class="text-center" scope="col">Departure Time</th> <th class="text-center" scope="col">Destination</th> </tr> </thead> <tbody> {% for link in links %} <tr> <td class="text-center">{{link.fl_no}}</td> <td class="text-center">{{link.dep_time}}</td> <td class="text-center">{{link.dest}}</td> </tr> {%endfor%} </tbody> </table> {% endblock %} using the function HomePageView prints only one record I know its because of the for loop but I'm not sure how to fix it would really appreciate if someone could help -
How to display/render a field stored in an external model without refreshing?
I am trying to display a User's name on top of a box where they enter their Employee # in a form, without having to refresh the page. For example, they enter their # and then after they click/tab onto the next field, it renders their name on top, which comes from the database, so the user knows they've entered the correct info. This name is stored in a separate model, so I try to retrieve it using the "id/number". I am not too familiar with AJAX but after reading a few similar questions it seems like an AJAX request would be the most appropriate way to achieve this. I tried to make a function get_employee_name that returns the name of the person based on the way I saw another ajax request worked, but I'm not sure how to implement this so it displays after the # is entered. models.py class EmployeeWorkAreaLog(TimeStampedModel, SoftDeleteModel, models.Model): employee_number = models.ForeignKey(Salesman, on_delete=models.SET_NULL, help_text="Employee #", null=True, blank=False) work_area = models.ForeignKey(WorkArea, on_delete=models.SET_NULL, null=True, blank=False) station_number = models.ForeignKey(StationNumber, on_delete=models.SET_NULL, null=True, blank=True) def __str__(self): return self.employee_number This is the model where the name is stored alldata/models.py class Salesman(models.Model): slsmn_name = models.CharField(max_length=25) id = models.IntegerField(db_column='number', primary_key=True) I was reading … -
Django include URLconf module multiple times under different root urls
I want to be able to add optional url parts before all urls (e.g. a version). I could use re_path to do this, but I wonder if it is possible using path as well, since that would offer some other advantages. My current approach looks like this: urls = path("", include('test.urls'), namespace='test') urlpatters = [ path('<version:version>/', include(urls)) path('', include(urls)) ] Implementing it like this, calling the urls works but reversing does not work anymore. Django tells me that the namespaces are not unique: ?: (urls.W005) URL namespace 'test' isn't unique. You may not be able to reverse all URLs in this namespace Why is that? Using re_path with optional url parameters, reverse works as intended and selects the url depending on which parameters are given: reverse('test') # '/' reverse('test', version=1.0) # '/1.0/' -
Filter queryset by field with multiple options
Having some abstract model with field date: class MyModel(models.Model): date = models.DateField(null=True) ... How do I compose a filter query that returns all records where date field is either Null or is in range of given dates? This is what I've tried so far but I'm always getting empty queryset: _ = MyModel.objects.filter(Q(date__isnull=True) & Q(date__range=[...]) -
'choices' must be an iterable containing (actual value, human readable name) tuples
Having an error when trying to set choices on model field. Here's the code: TICKET = 'TICKET', TICKET_HISTORY = 'TH' TICKET_RATE = 'TR' PASSWORD_CHANGE = 'PASS' CONTENT = 'CN' TYPE_CHOICES = [ (TICKET, 'Ticket created'), (TICKET_HISTORY, 'Ticket changed'), (TICKET_RATE, 'Ticket rated'), (PASSWORD_CHANGE, 'Password changed'), (CONTENT, 'Added content') ] type = models.CharField(max_length=6, choices=TYPE_CHOICES, default=TICKET) TYPE_CHOICES seems to be correct, can't understand where's the issue with it Exception: Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x7f8acad18bf8> Traceback (most recent call last): File "/home/userwoozer/work/tickets/env/lib/python3.6/site-packages/django/utils/autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "/home/userwoozer/work/tickets/env/lib/python3.6/site-packages/django/core/management/commands/runserver.py", line 117, in inner_run self.check(display_num_errors=True) File "/home/userwoozer/work/tickets/env/lib/python3.6/site-packages/django/core/management/base.py", line 425, in check raise SystemCheckError(msg) django.core.management.base.SystemCheckError: SystemCheckError: System check identified some issues: ERRORS: main.Activity.type: (fields.E005) 'choices' must be an iterable containing (actual value, human readable name) tuples. -
Why am I getting "Enter a hole number" for a FloatField in Django
I'm setting from JavaScript ( inside Django template ) "timezone_offset" field like this: document.getElementById( 'id_timezone_offset' ).value = date.getTimezoneOffset()/60; When I'm retrieving the date in Django view, the form is not valid: timezone_offset = form.cleaned_data['timezone_offset'] with this error: <ul class="errorlist"><li>timezone_offset<ul class="errorlist"><li>Enter a whole number.</li></ul></li></ul> In my model the field is declared as float: timezone_offset = models.FloatField(null=True) For the record, If I'm setting a timezone with whole offset the code is working as expected. Tried already cleaning the database, restarting server, even deleting and recreating database. -
MDL Tabs loading blank, but active, until manually clicked on
MDL Tabs showing blank until manually clicked. The problem I have a set of MDL Tabs on an account page, the tabs that show are dependent on the current user's groups. If the User is a member of group X, Y, and or Z different tabs will be shown for them. That's all working fine but when the page loads, the tab area is completely blank until the user manually clicks on Tab X where Tab X should automatically load. What I've Tried so far setting 'is-active' on the class - This will make the tab "active" and underlined but the contents still show blank until the tab is manually clicked. jQuery to click the "#messages" tab on document.ready <script type="text/javascript"> $(document).ready(function(){ $("#messages").click(); }); </script> Read through the MDL Documentation at MDL Components Tabs info Searched for Solutions to the specific problem on Google and StackOverflow This is the code for the actual tabs themselves. <div class="mdl-cell mdl-cell--6-col mdl-card mdl-shadow--4dp" style="padding-left: 1rem;"> <div class = "mdl-tabs mdl-js-tabs" id="tabs"> <div class = "mdl-tabs__tab-bar"> <a class="mdl-tabs__tab is-active" href="#messages">Messages</a> {% if request.user|has_group:"Customer Service" %} <a class="mdl-tabs__tab" href="#call_center">CSR</a> {% endif %} {% if request.user|has_group:"HR" %} <a class="mdl-tabs__tab" href="#hr">HR Tools</a> {% endif %} {% if … -
Adding none DB fields model to the django serialized JSON
my question may be silly , and am no expert,what am trying to do is to manipulate the JSON from django.core.serializers.serialize . I'v searched the web and find to to serialize some picked fields in my Model there is a an argument fields that takes an array of what i want to serialize ,but if i want to add some thing that i could calculate without storing it on the DB? searched a lot with no results ,may be there is something like a method or a class i don't know of yet may solve it ? please help and thanks in advance .