Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django 1.8 linking to existing MySQL Database
I'm currently trying to link my django app so an existing MySQL db (To qualify, the database is linked in settings and django can see the db and inspect) Im working on a dev version of the db before lining to the operational db. I have run ./manage.py inspectdb > models.pyand fixed the models created by django to match the schema. From my undderstanding of the docs (I normaly create new postgres dbs. Not link to existing) I still have to run migrate before running runserver. From what I can see in the SQL django recreates all the tables (along with its own) but prefixed with the app name. I am assuming that the data from django will be used in the tables created by django rather than the exisiting tables. I have read that you can fake migration with --fake-initial but I am unsure if this will resolve my issue or cause more problems once in production. Any help with understaning this would be appreciated. -
TemplateDoesNotExist when using Django package
I followed this Django tutorial: https://docs.djangoproject.com/en/1.10/intro/reusable-apps/. I have a project called oldcity and an app called oldantwerp. The app is located in a parent directory called django-oldantwerp and the app directory itself has a subdirectory templates. The index.html file that my project is looking for is situated like so: django-oldantwerp>oldantwerp>templates>oldantwerp>index.html I tried to use this app with my project by including it in settings.py: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'oldantwerp' ] and in urls.py (in the projec), like so: urlpatterns = [ url(r'^oldantwerp/', include('oldantwerp.urls')), url(r'^admin/', admin.site.urls), ] When I go to the admin page, everything works, but when I try to open the index page I get this error: TemplateDoesNotExist at /oldantwerp/ It says it tried to locate the index.html file like so: Template loader postmortem Django tried loading these templates, in this order: Using engine django: * django.template.loaders.filesystem.Loader: /Users/Vincent/Apps/oldcity/templates/oldantwerp/index.html (Source does not exist) * django.template.loaders.app_directories.Loader: /Users/Vincent/Apps/oldcity/venv/lib/python3.4/site-packages/django/contrib/admin/templates/oldantwerp/index.html (Source does not exist) * django.template.loaders.app_directories.Loader: /Users/Vincent/Apps/oldcity/venv/lib/python3.4/site-packages/django/contrib/auth/templates/oldantwerp/index.html (Source does not exist) And it also tried searching for another file: place_list.html, which is strange because I don't think I have such a file. What could be wrong? -
Include a Foreign Key in the Django GeoJSON serializer
When I serialize an object with geojson, I would need to add a field containing a reverse Foreign Key. I use Django 1.9 and have the following models: class NaturalEarthProvince(models.Model): adm1_code = models.CharField(max_length=10, primary_key=True) name = models.CharField(max_length=100) geom = models.MultiPolygonField(srid=4326) objects = models.GeoManager() class NaturalEarthMerged(models.Model): basicname = models.CharField(max_length=200, blank=True) fkprovince = models.OneToOneField(NaturalEarthProvince, blank=True, null=True) fktouristicarea = models.ForeignKey(TouristicArea, blank=True, null=True, related_name='relatednatmerged', on_delete=models.SET_NULL) class TouristicArea(models.Model): areaname = models.CharField(max_length=200, blank=True) fkcountry = models.ForeignKey(NaturalEarthCountry, blank=True, null=True) What I would like to do is: location = NaturalEarthProvince.objects.filter(adm0_a3=code) locationserialized = serialize('geojson', location, geometry_field='geom', fields=('name', 'adm1_cod_1', 'touristicarea') with touristicarea being location.naturalearthmerged.fktouristicarea Any clue? -
How to Remove this error try different solutions but can't
ImportError at / No module named forms Request Method: GET Request URL: http://127.0.0.1:8000/ Django Version: 1.6.11 Exception Type: ImportError Exception Value: No module named forms Exception Location: /home/zaheer/django-user/login/myapp/views.py in , line 11 Python Executable: /usr/bin/python Python Version: 2.7.6 Python Path: ['/home/zaheer/django-user/login', '/usr/local/lib/python2.7/dist-packages/virtualenv-15.1.0-py2.7.egg', '/usr/lib/python2.7', '/usr/lib/python2.7/plat-x86_64-linux-gnu', '/usr/lib/python2.7/lib-tk', '/usr/lib/python2.7/lib-old', '/usr/lib/python2.7/lib-dynload', '/usr/local/lib/python2.7/dist-packages', '/usr/lib/python2.7/dist-packages', '/usr/lib/python2.7/dist-packages/PILcompat', '/usr/lib/python2.7/dist-packages/gtk-2.0', '/usr/lib/python2.7/dist-packages/ubuntu-sso-client'] Server time: Fri, 10 Feb 2017 12:11:20 +0000 -
Delete Member of Many To Many Relationship Django Rest Framework
Given the following system # Models class Team(models.Model): name = models.CharField(max_length=128) class Player(models.Model): name = models.CharField(max_length=128) teams = models.ManyToManyField(Team) # Serializers class PlayerSerializer(serializers.ModelSerializer): teams = serializers.PrimaryKeyRelatedField(many=True, queryset=League.objects.all(), required=False) class Meta: model = Team fields = ('id', 'name', 'teams') # Views class TeamViewSet(viewsets.ModelViewSet): queryset = Team.objects.all() serializer_class = TeamSerializer Basically a player can be in many teams So the question is, how do I implement endpoints to manage the player-team relationship. Say we have two teams with ids 1, and 2 I create a player with POST /players/ {'name': 'player1'} this player will have Id 1 I want to add player to teams 1 and 2, and then remove player from team 2 With this setup I can do PATCH /players/1/ {'teams': [1, 2]} How do I now remove player1 from team 2? Also, is using a patch request to add player1 to teams 1 and 2 the correct way to do this? -
Tango With Django 1.9 Ch.7 TypeError at /rango/add_page/
I am currently at the end of the Tango With Django 1.9's Chapter 7 and working on the exercises. Upon clicking my "Add a New Page" link on the index.html, I am getting the following error: TypeError at /rango/add_page/ add_page() takes exactly 2 arguments (1 given) Request Method: GET Request URL: http://127.0.0.1:8000/rango/add_page/ Django Version: 1.10.5 Exception Type: TypeError Exception Value: add_page() takes exactly 2 arguments (1 given) Here are my relevant files: views.py . . . def add_category(request): form = CategoryForm(request.POST) # A HTTP POST? if request.method == 'POST': form = CategoryForm(request.POST) # Have we been provided with a valid form? if form.is_valid(): # Save the new category to the database form.save(commit=True) # Now that the category is saved # We could give a confirmation message # But since the most recent category added is on the index page # then we can direct the user back to the index page return index(request) else: # The supplied form contained errors - # just print them to the terminal print(form.errors) # Will handle the bad form, new form, or no form supplied cases. # Render the form with error messages (if any). return render(request, 'rango/add_category.html', {'form':form}) def add_page(request, category_name_slug): try: category … -
Django - ModelForm does not save because of missing user id
I get: IntegrityError at /category/ NOT NULL constraint failed: transactions_category.user_id here in my view: elif "create" in request.POST: createform = CategoryForm(data=request.POST) createform.save(commit=False) createform.user = request.user createform.save() <--- specifically here, the .save with commit=False goes through and I can also set the user I checked with the debugger and createform.user has a User, that User also has an id. forms.py: class CategoryForm(ModelForm): class Meta: model = Category exclude = ["subcategory", "user"] models.py: class Category(models.Model): title = models.CharField(max_length = 100) subcategory = models.ManyToManyField("self", blank=True, symmetrical=False) user = models.ForeignKey(User) User import is: from django.contrib.auth.models import User Why will it not save? I set the user before calling .save(), the user is set (and has an id) as far as I can tell with the debugger? I have run both manage.py migrate and manage.py makemigrations and everything is up to date. -
Django instance.id always = 'None' when trying to set an upload location
Ive been trying to get my post form to allow users to upload a picture and then save it in a folder relative to the post id. However the post id is always == None. Here in my models.py: from django.db import models from django.core.urlresolvers import reverse # Create your models here. def upload_location(instance, filename): return "{}/{}".format(form.id, filename) class Post(models.Model): post_title = models.CharField(max_length = 120) post_content = models.TextField() last_updated = models.DateTimeField(auto_now=True, auto_now_add=False) post_date = models.DateTimeField(auto_now=False, auto_now_add=True) post_image = models.FileField(upload_to=upload_location, null=True, blank=True) def __unicode__(self): return self.post_title def __str__(self): return self.post_title def get_absolute_url(self): return reverse("posts:post_display", kwargs= {'post_id': self.id}) My views.py: from django.shortcuts import render, get_object_or_404, redirect from django.contrib import messages from django.http import HttpResponse, HttpResponseRedirect from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger # Create your views here. from .forms import PostForm from .models import Post #create def post_create(request): if not request.user.is_authenticated: return(redirect("posts:post_timeline")) form = PostForm(request.POST or None, request.FILES or None) if form.is_valid() and request.POST: instance = form.save(commit=False) instance.save() return(HttpResponseRedirect(instance.get_absolute_url())) context = { "form": form, } return render(request, "post_form.html", context) def post_edit(request, post_id = None): instance = get_object_or_404(Post, id = post_id) form = PostForm(request.POST or None, request.FILES or None, instance = instance) if form.is_valid and request.POST and request.user.is_authenticated: instance = form.save(commit=False) instance.save() #messages.success(request, "Post … -
Django nested serializer allow_null=True
I have a nested serializer and I want to activate the allow_null to true, but it doesn't work. TOP object have a nested Down object, the related_name must be present in the TOP object but with a null value. If the down object is not null all down object fields are required. Example request with all fields in down object (this one works fine) : { "title": "Titre new rgfdgfdgthtrh", "downs": { "type": "Type example", "is_external": true, }, } Example that i tryed to do : request when down object is null (this one doesn't work) { "title": "Titre new ", "topic_type": "Test top type", "downs": {}, } I have tryed with "downs": None or Null without success. My views : # My Views.py class Top(models.Model): class Meta: verbose_name = _('Top') verbose_name_plural = _('Tops') top_guid = models.UUIDField( primary_key=True, unique=True, default=uuid.uuid4, editable=False) title = models.CharField( help_text=_('Title'), verbose_name=_('title'), max_length=100, blank=False ) class Down(models.Model): top = models.OneToOneField( Top, on_delete=models.CASCADE, help_text=_('Top'), verbose_name="top", related_name="downs" ) type = models.CharField( help_text=_('Type'), verbose_name=_('type'), max_length=30, blank=False ) is_external = models.BooleanField( help_text=_('external (default = false)'), verbose_name=_('external'), blank=False, default=False ) and my serializers # My serializers.py class DownSerializer(serializers.ModelSerializer): class Meta: model = Down fields = '__all__' class TopSerializer(serializers.ModelSerializer): downs = DownSerializer(many=False, … -
django simple debugging gives strange result
I experience something interesting in my project, I'm using Oracle as db. Inside js when I call home view function strange things happen. How can it happen? js setInterval(function() { var div = document.querySelector("#counter"); var count = div.textContent * 1 - 1; div.textContent = count; if (count <= 0) { window.location.href="{% url 'home' %}"; } }, 1000); home def home(request): # First check IP address if request.user == AnonymousUser(): ip_address = get_ip_address(request) user_logged = login_ip_address(request,ip_address,request.user) if request.user.is_authenticated: print "1" getNotifications(request) print "2" requests = getRequests(request) print "3" user_categories_names = getUserCategories(request) print "4" chart = [] if requests: print "5" openR = requests.filter(status="open").count() print "6" closedR = requests.filter(status="closed").count() print "7" lockedR = requests.filter(status__contains="lock").count() print "8" if openR>0 or closedR>0 or lockedR>0: print "9" chart=[openR,closedR,lockedR] print "10" else: print "11" deletedR = requests.filter(status="deleted").count() chart=[deletedR] #allCategoryRequests = getAllCategoryRequests(request,user_categories_requests) #requests = list(chain(sentRequestResult, tagRequests, parentRequestResult)) print "12" data = {'requests':requests,'catNames':user_categories_names,'chart':chart,'activeCategory':'taggedRequests'} template = "home.html" print "13" #pdb.set_trace() return render(request,template,data) print "14" else: print "15" return HttpResponseRedirect('accounts/login') Output 1 1 1 1 1 1 1 1 1 1 1 1 2 3 1 1 4 5 2 3 6 7 4 8 5 9 10 12 13 6 1 7 8 9 10 12 13 2 3 … -
Synchronizing different Web-Services (Django) and their DBs through RESTful interfaces with push/pull mechanism, like with GIT
I am looking for a way to maintain the DBs of multiple web-services in synchronization. I have a system made of: Multiple Local web-services, with their own private DBs Own Central web-service, with its own DB A subset of the Local DBs can be pushed to the Central DB in order to update it. On a regular basis the Local DBs shall be able to pull the latest update from the Central DB. The idea is to have something very similar to what git VCS does: Push/Pull mechanism Conflicts management from the the 'sender/fetcher' point of view. This is depicted in the following diagram: ________ _.-----._ |==|=====| .- -.| | | |-_ _-|| | | | ~-----~ || | |--------Push/Pull----------. | Local DB || | | | `._ _.'| |====°| | "-----" |__|_____| | .--. |_ -( )- _ ________ .--,| ),--. _.-----._ |==|=====| _.-( | INTERNET )-._ .- -.| | | ( ____v___ ) |-_ _-|| | | '-.|==|=====| )_.-' | ~-----~ || | |------Push/Pull------>| | | _.-----._ ' | Local DB || | | | | |.- -. `._ _.'| |====°| | | ||-_ _-| "-----" |__|_____| | | || ~-----~ | | |====°|| CENTRAL DB| ________ |__|_____|`._ … -
Select2 + Django: set preferred list items
I use select2]1 with django-countries in order to give the user a dropdown of possible countries. I now would like to either (1) split the dropdown or (2) rearrange the order of the items/countries, i.e.: Currently I get an alphabetically ordered list: - select country - Afghanistan - Albania - Algeria ... - Kenya ... - Zimbabwe What I would like is: (1) - select country - Germany - Austria - Switzerland --------------------------- - Afghanistan - Albania - Algeria ... - Kenya ... - Zimbabwe or (2) - select country - Germany - Austria - Switzerland - Afghanistan - Albania - Algeria ... - Kenya ... - Zimbabwe This is my js: $(document).ready(function () { $("#id_nationality").select2({ default: 'Germany', placeholder: 'select country' }); }); I use crispy-forms for form rendering -
How to use one Slack Application in more than one website using python and django
I am using slack application in one website no problem occur if i use in more than website then problem will be occur how can resolve this problem. I want to use one slack app in more than one website how is it possible. if any possibilities are there please quick resolve this problem -
Displaying trending blog posts on homepage
I have a website (www.irenovate.in) on Django 1.9 and a blog (www.blog.irenovate.in) on word-press. The blog is linked in the website's navigation bar. However, i want to add a section of trending blogs on my website's homepage. How can i do it? I don't have any knowledge of javascript. I want it to be dynamic so that i don't have to change it weekly. could it be done without using javascript. if not then could you give some guidelines in terms of javascript. Help is highly anticipated and would be highly appreciated. Thanks in advance. -
How to jango customize admin page
I'm a new Django dev. Hope you help. I have some groups: A, B, C. In create user page of Django admin (admin/auth/user/add/), I only want show Group B and C when creating User is belong to Group B. And if creating User is belong Group C, only show group C in list group. How can I do that. Thanks in advance. -
Django - How to change value of forms.ModelChoiceField
I want to output the value from my Models Name column using forms.ModelChoiceField. I have read a lot of documentation on the subject but its proving difficult to achieve the desired results! Here is my code. I have this form: forms.py from django import forms from asset_db.models import Profiles class SubmitJob(forms.Form): material_id = forms.CharField(max_length=8) workflow = forms.ModelChoiceField(queryset=Profiles.objects.distinct('name')) start_datepicker = forms.CharField(max_length=12) end_datepicker = forms.CharField(max_length=12) This model: class Profiles(models.Model): id = models.DecimalField(6).auto_creation_counter name = models.CharField(max_length=256, default='null') target_path = models.CharField(max_length=256, default='null') target_profile = models.TextField(max_length=1024, default='null') package_type = models.CharField(max_length=256, default='null') video_naming_convention = models.CharField(max_length=256, default='null') image_naming_convention = models.CharField(max_length=256, default='null') package_naming_convention = models.CharField(max_length=256, default='null') def __str__(self): return self.name Here is the HTML output: <p><label for="id_workflow">Workflow:</label> <select id="id_workflow" name="workflow" required> <option value="" selected="selected">---------</option> <option value="2">Amazon</option> <option value="1">Test</option> </select></p> I want to know how to change the value of "value" to the column "name" in my model, for example: <p><label for="id_workflow">Workflow:</label> <select id="id_workflow" name="workflow" required> <option value="" selected="selected">---------</option> <option value="Amazon">Amazon</option> <option value="Test">Test</option> </select></p> Thanks in advance. -
Filtered Nested Relationships Django Rest Framework
I have two models which look like the following: class Subject(models.Model): subject_code = models.CharField(max_length=12, unique=True) name = models.CharField(max_length=100) dept_code = models.CharField(max_length=6) and... class Subject_assessment(models.Model): subject_code = models.ForeignKey(Subject, related_name='sub_assessments') year = models.CharField(max_length=4) name = models.CharField(max_length=50) I have created my serializes in such a way that when I retrieve a subject, I also retrieve the assessments associated with that subject. I am using the following serializers to accomplish this: class AssessmentsSerializer(serializers.ModelSerializer): class Meta: model = Subject_assessment fields = ( "subject_code", "year", "name" ) class SubjectSerializer(serializers.ModelSerializer): sub_assessments = AssessmentsSerializer(many=True) class Meta: model = Subject fields = ( "subject_code", "name", "dept_code", "sub_assessments" ) This code works perfectly as anticipated as it gives me a result like this: { "subject_code":"ECR2243", "name":"Statistics", "dept_code":"Stats", "sub_assessments":[ { "subject_code":"ECR2243", "year":"2017", "name":"Test 1" }, { "subject_code":"ECR2243", "year":"2016", "name":"Test 1" } ] } My problem is that I wish to retrieve assessments only for a specific year. For example, If I pass 2017 as the year of interest, I do not wish to retrieve assessments for 2016 like I am currently getting. Can anyone please assist on how I can structure my code in order to accomplish this. Thank you in advance. -
Writing several fields in one row in a csv with python
I'm working on improving some open-source code for a psychological test. For an output of data I'm using python's CSV module, which works fine in itself. The data output is dependent on the django model (trials) and the respective database entry and I want to add the data from another model (participant) to the csv. So far I only managed to add the required entries in a new row but this basically renders the csv unusable for further use in statistics programs. In short what I get: headers of database entry 1 headers of database entry 2 values of database entry 1 values of database entry 2 But what I want is the output to look like this: headers of database entry 1 followed by 2 values of database entry 1 followed by 2 This is what the important part of the export looks like. for participant in queryset: rows = [headers_participant] + [headers] participants = Participant.objects.filter(id=participant.id) trials = Trial.objects.filter(participant=participant.id) for participant_value_list in participants.values_list(*fields_participant): rows.append([unicode(v) for v in participant_value_list]) for trial_value_list in trials.values_list(*fields): rows.append([unicode(v) for v in trial_value_list]) I do understand that the output as it is now is caused by me calling rows.append twice but right now I don't … -
Setup multiple django gunicorn instances with nginx
Got one django site running with gunicorn & nginx need to setup another site also with the same. Nginx settings is straight forward, how to rework below to add another site /home/ubuntu/webapps/uganda_buzz/ relevant settings are /etc/init/gunicorn.conf description "Gunicorn application server handling all projects" start on runlevel [2345] stop on runlevel [!2345] respawn setuid user setgid www-data chdir /home/ubuntu/webapps/kenyabuzz exec /home/ubuntu/webapps/djangoenv/bin/gunicorn --workers 3 --bind unix:/home/ubuntu/webapps/kenyabuzz/kb.sock kb.wsgi:application and /etc/systemd/system/gunicorn.service [Unit] Description=gunicorn daemon After=network.target [Service] User=ubuntu Group=nginx WorkingDirectory=/home/ubuntu/webapps/kenyabuzz ExecStart=/home/ubuntu/webapps/djangoenv/bin/gunicorn --workers 3 --bind unix:/home/ubuntu/webapps/kenyabuzz/kb.sock kb.wsgi:application [Install] WantedBy=multi-user.target -
falcon python oauthlib example
I am using http://oauthlib.readthedocs.io/en/latest/oauth2/server.html to create server in falcon it has an example of django how do i convert this in falcon python project.I am a new programmer in falcon please help. class AuthorizationView(View): def __init__(self): # Using the server from previous section self._authorization_endpoint = server def get(self, request): # You need to define extract_params and make sure it does not # include file like objects waiting for input. In Django this # is request.META['wsgi.input'] and request.META['wsgi.errors'] uri, http_method, body, headers = extract_params(request) try: scopes, credentials = self._authorization_endpoint.validate_authorization_request( uri, http_method, body, headers) # Not necessarily in session but they need to be # accessible in the POST view after form submit. request.session['oauth2_credentials'] = credentials # You probably want to render a template instead. response = HttpResponse() response.write('<h1> Authorize access to %s </h1>' % client_id) response.write('<form method="POST" action="/authorize">') for scope in scopes or []: response.write('<input type="checkbox" name="scopes" ' + 'value="%s"/> %s' % (scope, scope)) response.write('<input type="submit" value="Authorize"/>') return response # Errors that should be shown to the user on the provider website except errors.FatalClientError as e: return response_from_error(e) # Errors embedded in the redirect URI back to the client except errors.OAuth2Error as e: return HttpResponseRedirect(e.in_uri(e.redirect_uri)) @csrf_exempt def post(self, request): uri, http_method, … -
Django schedule task in rea ltime application
I have a Django webservice and i want to schedule to run a function every 1 hour. I try to use 'Cron' or i use i simple timer but is didn't work. My Cron code: tab = CronTab() cron_job = tab.new(function) cron_job.hour().every(1) job.hour.every(1) -
Django pagination doesn't display all pages
I'm improving my Django project with pagination in order to display the query result page by page. Thanks to @neverwalkaloner for helping me : Create several pages from array But I get an insoluble error. I can display the first page and it works pretty well, but when I select the next page, it doesn't display it with next results. As you can see : First page Second page This is my view : @login_required def Table_annuelle_BirthCertificate(request) : query_naissance = request.GET.get('q1') request.session['query_naissance'] = query_naissance if query_naissance : query_naissance_list = BirthCertificate.objects.filter(created__icontains=query_naissance).order_by('lastname') else : query_naissance_list = BirthCertificate.objects.none() # == [] paginator = Paginator(query_naissance_list, 3) page = request.GET.get('page', 1) try: query_naissance_list = paginator.page(page) except PageNotAnInteger: query_naissance_list = paginator.page(1) except EmptyPage: query_naissance_list = paginator.page(paginator.num_pages) context = { "BirthCertificate":BirthCertificate, "query_naissance" : query_naissance, "query_naissance_list" : query_naissance_list, "PageNotAnInteger":PageNotAnInteger, } return render(request, 'annuel.html', context) And my template : <h4 class = "col-sm-10"> <b><font color="#0083A2"> <span class="glyphicon glyphicon-user"></span> Prévisualisation de la table annuelle des naissances </b></font></h4> <form class = "col-sm-10" method="GET" action=""> <input type="text" name="q1" placeholder="Entrer une année" value="{{ request.GET.q1 }}"> &nbsp; <input class="button" type="submit" value="Rechercher"> </form> <br></br> <br></br> <table style="width:50%"> <tbody> <tr> <th>Nom & prénom(s)</th> <th>Lieux de Naissance</th> <th>Date des actes</th> <th>Numéro de l'acte</th> </tr> {% for item … -
Saving formset saves a bunch of blank forms
So I have a view where I can add as many forms as the user wants with an add row function and then click save. The page displays existing forms and allows you to add new ones. When I save the first one it all works fine. Then as I continue to save, it saves the new record PLUS a number of blank records, the number being equal to the number of forms we see on the page (existing + the number you are trying to add). I have allowed fields to be blank because I needed to populate some fields in the view. Without this I was getting validation errors when i ran a False commit to then populate fields and save. Here is my view - well two views because I didn't want to Redirect to another page. @login_required def timesheet(request, timesheet_id): timesheet = TimeSheet.objects.get(pk=timesheet_id) timesheet_object = request.session.get('timesheet') if timesheet_object: del request.session['timesheet'] request.session['timesheet'] = timesheet_id # This displays the existing records TimeInlineFormSet = inlineformset_factory(TimeSheet, Time, exclude=('timesheet_id',), extra=0, formset=CustomInlineFormSet) # This allows addition of new records # Looks messy - it was the only way I managed to generate any number of new forms with jquery blahblahblah NewTimeFormSet = … -
Database returned an invalid datetime value. Are time zone definitions for your database and pytz installed?
python version : 3.6 OS : windows 10 mysql version : 5.7 I have a Django app. Now i am getting those errors: Environment: Environment: Request Method: GET Request URL: http://localhost:8000/blog/archive/ Django Version: 1.10.5 Python Version: 3.6.0 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'bookmark.apps.BookmarkConfig', 'blog.apps.BlogConfig'] 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: File "C:\Users\ikks0\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\handlers\exception.py" in inner 39. response = get_response(request) File "C:\Users\ikks0\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\handlers\base.py" in _get_response 187. response = self.process_exception_by_middleware(e, request) File "C:\Users\ikks0\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\handlers\base.py" in _get_response 185. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\ikks0\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\views\generic\base.py" in view 68. return self.dispatch(request, *args, **kwargs) File "C:\Users\ikks0\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\views\generic\base.py" in dispatch 88. return handler(request, *args, **kwargs) File "C:\Users\ikks0\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\views\generic\dates.py" in get 339. self.date_list, self.object_list, extra_context = self.get_dated_items() File "C:\Users\ikks0\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\views\generic\dates.py" in get_dated_items 425. date_list = self.get_date_list(qs, ordering='DESC') File "C:\Users\ikks0\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\views\generic\dates.py" in get_date_list 404. if date_list is not None and not date_list and not allow_empty: File "C:\Users\ikks0\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\models\query.py" in __bool__ 260. self._fetch_all() File "C:\Users\ikks0\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\models\query.py" in _fetch_all 1087. self._result_cache = list(self.iterator()) File "C:\Users\ikks0\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\models\query.py" in __iter__ 155. for row in compiler.results_iter(): File "C:\Users\ikks0\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\models\sql\compiler.py" in results_iter 795. row = self.apply_converters(row, converters) File "C:\Users\ikks0\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\models\sql\compiler.py" in apply_converters 779. value = converter(value, expression, self.connection, self.query.context) File "C:\Users\ikks0\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\models\functions\datetime.py" in convert_value 181. "Database returned an invalid datetime value. " Exception Type: ValueError at /blog/archive/ Exception Value: Database … -
Authentication Backends file
I wish to customize my authentication backends, i'm a beginner in django and i want to practice, but i am alittle confused. I red the documentation but for their example and for each example i found, no one says where you should write the class. Do you have to add your class in the default django backends.py? or do you have to create your own backends.py and add it after to Settings.py? Another thing, i want to know if the authorizations and permissions have to be written in the same customized backends.py.