Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How do I link to Django static assets from my JavaScript files?
I'm trying to load a specific file but failing due to the way Django manages relative paths. Here's the structure of my app: mysite |-- manage.py |-- mysite |-- __init__.py |-- settings.py |-- urls.py |-- wsgi.py |-- app |-- __init__.py |-- models.py |-- tests.py |-- views.py |-- static |-- JS |-- myScript.js |-- data |-- myData.geojson |-- templates |-- app |-- index.html In other words, pretty standard. The two key parts are that I load myScript.js in to my index.html like so: <script type='text/javascript' src="{% static '/JS/myScript.js' %}"></script> The issue is that, within myScript.js, I want to load in myData.geojson. This doesn't work: ... 'url': '/static/data/myData.geojson' ... nor does 'url': '{% static /data/myData.geojson %}' #this throws an error I just want a project setup where I can use relative path to do this: 'url': '../data/myData.geojson' Is that possible? My current settings are this: STATIC_URL = '/static/' STATIC_ROOT = '/var/www/mysite/static' -
Turn off django 2.0 admin responsive behavior
This behaviour is not friendly for me and my team, we need a full view. Is there a way to disable this: <meta name="viewport" content="user-scalable=no, width=device-width, initial-scale=1.0, maximum-scale=1.0"> <link rel="stylesheet" type="text/css" href="/static/admin/css/responsive.css" /> -
insert an element into a list of dictionaries
I have declared an empty list and I want to append dictionaries through a for loop by using the extend() method, but I end with a list with the same content in all its positions (the same dictionary) This is the code: def get_tasks(self, actor, task_state): tasks = Task.objects.filter(actor=actor.id, state=task_state) tasks_to_return = [] task_data = {} for task in tasks: task_data['name'] = getattr(task, 'name') task_data['description'] = getattr(task, 'description') task_data['start_date'] = getattr(task, 'start_date') task_data['finish_date'] = getattr(task, 'finish_date') task_data['situation'] = task.get_situation() tasks_to_return.extend(task_data) return tasks_to_return If I change extend() for append(), the result is even worst. -
How to use hset with django-redis-cache?
I am new in django/redis and i'm starting to familiarize with heroku redis addon. However, i can only use set and get. When i'm trying to use other methods like hset , i get this error : 'RedisCache' object has no attribute cache.hset('key', 'value') How can i manage this ? -
relation "cms_urlconfrevision" does not exist
ProgrammingError at / relation "cms_urlconfrevision" does not exist LINE 1: ...sion"."id", "cms_urlconfrevision"."revision" FROM "cms_urlco... ^ Request Method: GET Request URL: http://192.168.99.100:8000/ Django Version: 1.8.18 Exception Type: ProgrammingError Exception Value: relation "cms_urlconfrevision" does not exist LINE 1: ...sion"."id", "cms_urlconfrevision"."revision" FROM "cms_urlco... ^ Exception Location: /virtualenv/lib/python3.5/site-packages/django/db/backends/utils.py in execute, line 64 Python Executable: /virtualenv/bin/python Python Version: 3.5.2 Python Path: ['/app', '/virtualenv/lib/python35.zip', '/virtualenv/lib/python3.5', '/virtualenv/lib/python3.5/plat-linux', '/virtualenv/lib/python3.5/lib-dynload', '/usr/local/lib/python3.5', '/usr/local/lib/python3.5/plat-linux', '/virtualenv/lib/python3.5/site-packages'] Server time: Wed, 31 Jan 2018 14:38:53 -0600 I am using Divio when I click on open local site icon the browser shows the above error Thanks -
querying in django multiselectcheckbox
from django.db import models from multiselectfield import MultiSelectField from django.core.urlresolvers import reverse SEX_CHOICES = ( ('MALE', 'Male'), ('FEMALE', 'Female'), ) BRANCH_CHOICES = ( ('CSE', 'B.Tech CSE'), ('IT', 'B.Tech IT'), ('ECE', 'B.Tech ECE'), ('ME', 'B.Tech ME'), ('BBA', 'BBA'), ('BCA', 'BCA'), ('BCOM', 'B.Com'), ('MBA', 'MBA'), ) SEMESTER_CHOICES = ( ('SEM2', 'Sem 2nd'), ('SEM4', 'Sem 4th'), ('SEM6', 'Sem 6th'), ('SEM8', 'Sem 8th'), ) TRACK_EVENTS_CHOICES = ( ('100M', '100 Meter'), ('200M', '200 Meter'), ('400M', '400 Meter'), ('800M', '800 Meter'), ('1500M', '1500 Meter'), ('5000M', '5000 Meter'), ) FIELD_EVENTS_CHOICES = ( ('JAVELINE', 'Javeline Throw'), ('DISCUS', 'Discus Throw'), ('SHOTPUT', 'Shotput Throw'), ('HIGH', 'High Jump'), ('LONG', 'Long Jump'), ('TRIPLE', 'Triple Jump'), ) class Particiepents(models.Model): roll_no = models.IntegerField() Full_name = models.CharField(max_length=40) father_name = models.CharField(max_length=40) sex = models.CharField(max_length=10, choices=SEX_CHOICES) branch = models.CharField(max_length=20, choices=BRANCH_CHOICES) semester = models.CharField(max_length=10, choices=SEMESTER_CHOICES) track_events = MultiSelectField(max_length=30, null=True, blank=True, choices=TRACK_EVENTS_CHOICES, default="track_events") field_events = MultiSelectField(max_length=30, null=True, blank=True, choices=FIELD_EVENTS_CHOICES, default="track_events") def __str__(self): return self.Full_name This is my model.py, I want to retrieve individual lists of Full_name participating in different track_events(100m, 200m, 300m, 400m....). I am not able to set query in views.py. I want to create a query_set such that i can retrieve list of full_name participating in any event as query_set.Full_name -
map/import data from spreadsheet in django models for a particicular field
I have a django model in which i have my data- class School(): school = models.CharField(blank=True, null=True) contact = models.CharField(blank=True, null=True) roll_no = models.CharField(blank=True, null=True) parking_no = models.CharField(blank=True, null=True) The parking_no does not have any data, I have an excel (spreadsheet) document(.xlsx) from which i want to map my django models and wants to import the entry of parking_no only. (models already have other data) The excel document have the data like follow- SCHOOL ROLLNO PARKING_NO sch1 u101 p101 sch2 u102 p102 The roll_no is unique in my django models and excel document, based on the roll_no, How can I map / import to fill the parking_no alone in my models. Any help would be appriciated. -
Getting Null Value vilates integrity error when registering user or trying to migrate
Recently migrated database to RDS. Using django 2.0 Now when I try to register a user I get a: ProgrammingError at /accounts/register/ relation "auth_user" does not exist LINE 1: SELECT (1) AS "a" FROM "auth_user" WHERE "auth_user"."userna... ^ If I try to manage.py migrate I get the following response: (boxtrucks-Dleh71wm) bash-3.2$ python manage.py migrate Operations to perform: Apply all migrations: accounts, admin, auth, contenttypes, saferdb, sessions Running migrations: Applying accounts.0002_auto_20180131_0135...Traceback (most recent call last): File "/Users/Dev/.local/share/virtualenvs/boxtrucks-Dleh71wm/lib/python3.6/site-packages/django/db/backends/utils.py", line 85, in _execute return self.cursor.execute(sql, params) psycopg2.IntegrityError: null value in column "id" violates not-null constraint DETAIL: Failing row contains (null, accounts, 0002_auto_20180131_0135, 2018-01-31 20:01:35.801905+00). The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/Users/Dev/.local/share/virtualenvs/boxtrucks-Dleh71wm/lib/python3.6/site-packages/django/core/management/__init__.py", line 371, in execute_from_command_line utility.execute() return self.cursor.execute(sql, params) File "/Users/Dev/.local/share/virtualenvs/boxtrucks-Dleh71wm/lib/python3.6/site-packages/django/db/utils.py", line 89, in __exit__ raise dj_exc_value.with_traceback(traceback) from exc_value File "/Users/Dev/.local/share/virtualenvs/boxtrucks-Dleh71wm/lib/python3.6/site-packages/django/db/backends/utils.py", line 85, in _execute return self.cursor.execute(sql, params) django.db.utils.IntegrityError: null value in column "id" violates not-null constraint DETAIL: Failing row contains (null, accounts, 0002_auto_20180131_0135, 2018-01-31 20:01:35.801905+00). -
Django: confused by manytomany relationship
I have been trying figure out the working of pre_fetch and manytomany relationship. It is confusing for me. I don't get it. I have these models: class Clinic(models.Model): name = models.CharField(max_length=100) address = models.CharField(max_length=200) class Doctor(models.Model): name = models.CharField(max_length=100) clinics = models.ManyToManyField(Clinic, through='ClinicDoctor', related_name='doctors') patients = models.ManyToManyField('Patient', through='DoctorPatientAppointment', related_name='doctors_appointment') class ClinicDoctor(models.Model): doctor = models.ForeignKey(Doctor, related_name='doctorsF') clinic = models.ForeignKey(Clinic, related_name='clinicsF') class Patient(models.Model): name = models.CharField(max_length=100) mobile = models.CharField(max_length=20) class DoctorPatientAppointment(models.Model): patient = models.ForeignKey(Patient, related_name='patient_appointments') doctor = models.ForeignKey(Doctor, related_name='doctor_appointments') clinic = models.ForeignKey(Clinic, related_name='clinic_appointments') I went through the documentation and many SO quetions/answers. Also, searched Google. But I think I am not getting it how should I do this. Here is what I want to achieve. I want to find Patients that have a given mobile number and then I want to get which doctors and clinics they have appointments with. I tried many solutions found on SO. It is not working. Doc = Doctor.objects.all().prefetch_related('patients','clinics') for doc in Doc: docString = ..... for pat in doc.patients.filter(mobile=12345): patientString = ..... for cli in doc.clinics.all(): clinicString = ..... I feel this is not right. I tried few other ways as well. I don't even remember what I have tried all day from the internet. All … -
QuerySets after login using simple login form doesn't display
I have such a small problem. I created a model that displays posts. Everything is ok when I go to index.html Then I created a simple login form from the AuthUser module and the login runs without any problem directing me to the destination page. And here the stairs start because: - After logging in through the admin panel as admin, I can manage the content and display it in html correctly - If I login as an admin via the login form, he does not show me my posts anymore Where can the problem lie? Unfortunately, now I can not paste the code because I write on the mobile -
does debug level INFO also show error too? django
I have such LOGGING setup for my django, but I realized using DEBUG level, it shows TOO much especially the template variableDoesNotExist debug is quite annoying. I have this as my current setup LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'simple_time': { # simple_time, that just outputs the log level name (e.g., DEBUG) plus time and the log message. 'format': '%(levelname)s %(asctime)s %(message)s' }, }, 'handlers': { 'debug_file': { 'class': 'logging.FileHandler', 'filename': os.path.join(BASE_DIR) + '/debug.log', 'formatter': 'simple_time' }, }, 'loggers': { 'django': { 'handlers': ['debug_file'], 'level': 'DEBUG', 'propagate': True, }, }, } I am wondering if I change the level to INFO will it just show INFO and not show ERROR level if any? Else, is it possible to split different levels into different files? I tried something like this, but not sure if it'll work properly 'handlers': { 'debug_file': { 'class': 'logging.FileHandler', 'filename': os.path.join(BASE_DIR) + '/debug.log', 'formatter': 'simple_time' }, 'info_file': { 'class': 'logging.FileHandler', 'filename': os.path.join(BASE_DIR) + '/info.log', 'formatter': 'simple_time' }, }, 'loggers': { 'django_debug': { 'handlers': ['debug_file'], 'level': 'DEBUG', 'propagate': True, }, 'django_info': { 'handlers': ['info_file'], 'level': 'INFO', 'propagate': True, }, }, Thanks in advance for any suggestions -
Plus Minus Buttons in Django app
I'm new to Django and my first assignment is to create a model which is Inventory based. So far I have created a login page, after logging I am redirected to home page which is a basic template printing the Name, Code and Stocks left. I need to create two working buttons(+ and -) which increment and decrement the stocks left on my home page which update the values of my Model too. I have made it through JS but I can't seem to find my way around with Django! My app's models.py: from django.db import models import uuid class Inventory(models.Model): """ Model representing a the inventory. """ id = models.UUIDField(primary_key=True, default=uuid.uuid4) inventory_name = models.CharField("INVENTORY NAME" ,max_length=200, help_text="This contains the Inventory name:") short_name = models.CharField(max_length=20, help_text="This contains an abbreviation:") inventory_code = models.IntegerField("INVENTORY CODE" ,default = '0', help_text="This contains the Inventory code:") price = models.IntegerField(default = '0') stocks_left = models.IntegerField("STOCKS LEFT",default = '0') def __str__(self): """ String for representing the Model object (in Admin site etc.) """ return '{0} ({1}) ({2})'.format(self.inventory_name,self.inventory_code,self.stocks_left) My app's views.py : from django.shortcuts import render from django.contrib import auth from django.views import generic from myapp.models import Inventory def home(request): names = Inventory.objects.all() return render(request, 'myapp/home.html', { "names": … -
Django AJAX to keep single element static
I have a site with a ticker bar at the top that is fetching JSON from my server based on stations current status (running, off etc). This part of the site needs to be in my base.html file, and I need it to last everywhere in the site. Im using AJAX to fetch the JSON, however when I switch to another page it resets unless I use AJAX for literally all of my links and pages. I feel like I am going about this wrong and really would like some input on how to better manage this. This green tiles in the top of the image below is the ticker im talking about, they change every 10 seconds and the data is constantly changing. Is there a better way to keep this in my base.html and not have it reload when switching template views? Example Page -
Django dynamic model for existing table "doesn't exist"
I'm trying to take data from an existing MySQL table and place it into a model using the code from this solution: def getModel(table_name): class MyClassMetaclass(models.base.ModelBase): def __new__(cls, name, bases, attrs): name += table_name return models.base.ModelBase.__new__(cls, name, bases, attrs) class MyClass(models.Model): __metaclass__ = MyClassMetaclass time_stamp = models.DateTimeField(db_column='Time_stamp', blank=True, null=True) # Field name made lowercase. price = models.DecimalField(db_column='Price', max_digits=8, decimal_places=3, blank=True, null=True) # Field name made lowercase. class Meta: db_table = table_name managed = False return MyClass I then call the class as follows: MyModel = getModel('test_table') MyModel._meta.db_table = 'test_table' and pass it into a DataPool (to create a chart using Django's Chartit): pricedata = \ DataPool( series= [{'options': { 'source': MyModel.objects.all()}, 'terms': [ 'time_stamp', 'price']} ]) At this point it throws an error (1146, "Table 'meowdb.test_table' doesn't exist"). Note that meowdb is the database name. Should it be prepending this? I also don't actively pass the database into the model anywhere. According to this, it seems like once the model is created Django automatically links it based on the name? Lastly, how do I get around this error? The table most certainly exists and is populated with many rows. -
wagtail 2.0 beta 'wagtaildocuments.Document' has not been loaded yet
I have installed the beta version of wagtail 2. Below is a code snippet from my project. When I try to makemigrations I get an error saying: ValueError: Cannot create form field for 'link_document' yet, because its related model 'wagtaildocuments.Document' has not been loaded yet class LinkFields(models.Model): link_document = models.ForeignKey( 'wagtaildocuments.Document', null=True, blank=True, related_name='+', on_delete=models.SET_NULL, ) @property def link(self): return self.link_document.url panels = [ DocumentChooserPanel('link_document'), ] class Meta: abstract = True class CarouselItem(LinkFields): embed_url = models.URLField("Embed URL", blank=True) caption = models.CharField(max_length=255, blank=True) panels = [ FieldPanel('embed_url'), FieldPanel('caption'), MultiFieldPanel(LinkFields.panels, "Link"), ] class Meta: abstract = True I am using Django 2, Python 3.6, Wagtail 2.0b1 -
How do I make django secrets available inside docker containers
My Environment docker 17.12-ce python 3.6.3 django 1.10.8 I have a django application that I want to containerise. Trying to maintain best practice I have followed the advice to split the settings.py file into a base file and then a file per stage so my base.py file where it loads the secret settings looks like this # Settings imported from a json file with open(os.environ.get('SECRET_CONFIG')) as f: configs = json.loads(f.read()) def get_secret(setting, configs=configs): try: val = configs[setting] if val == 'True': val = True elif val == 'False': val = False return val except KeyError: error_msg = "ImproperlyConfigured: Set {0} environment variable".format(setting) raise ImproperlyConfigured(error_msg) And it gets the file path from the SECRET_CONFIG environment variable. This works well when running the application locally without docker. I have created a dockerfile that uses the python3 onbuild image. My Dockerfile looks like this # Dockerfile # FROM directive instructing base image to build upon FROM python:3.6.4-onbuild MAINTAINER Lance Haig RUN mkdir media static logs VOLUME ["$WORKDIR/logs/"] # COPY startup script into known file location in container COPY docker-entrypoint.sh /docker-entrypoint.sh # EXPOSE port 8000 to allow communication to/from server EXPOSE 8000 # CMD specifcies the command to execute to start the server running. … -
Making calculator in html with django and python
I have two text box on my HTML page and now for example i want to type 2 numbers in two different boxes and now i have a button calculate. For example i want to add those two numbers and redirect the result to the third page called "result.html". My question is how should i get those 2 numbers from HTML text box and make them add together and proced to the result.html page with the result. -
How work with two models and one form?
I've got two models ('Student', 'Instructor') and one form 'RegisterForm' with two selectors (for types). How can i save data from form in corresponding model if in class Meta field 'model' just for the only one model? I guess, my way is wrong, but so i asking. class Student(models.Model): username = models.CharField(max_length=30) first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) password = models.CharField(max_length=30) email = models.EmailField() passed_tests = models.IntegerField(default=0) available_tests = models.IntegerField(default=0) def __str__(self): return self.username class Instructor(models.Model): username = models.CharField(max_length=30) first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) password = models.CharField(max_length=30) email = models.EmailField() written_tests = models.IntegerField(default=0) def __str__(self): return self.username -
Django-Import-Export is not showing up in Admin interface GUI
I have been following the instructions to get the django-import-export http://django-import-export.readthedocs.io/en/latest/ library to work with my models (for importing Products into my Product model). The import/export commands don't to appear on the admin GUI. from import_export import resources from django.contrib import admin from .models import Product, Category from import_export.admin import ImportExportModelAdmin, ImportMixin, ExportMixin, ImportExportMixin class ProductResource(resources.ModelResource): class Meta: model = Product # Register your models here. admin.site.register(Product) class ProductAdmin(ImportExportModelAdmin): resource_class = ProductResource admin.site.register(Category) -
Django Channels not sending reply message
Let me preface this by saying: I am a beginner at RabbitMQ and the concepts around it. I think I am starting to understand though. I currently have a problem with Django Channels. I had a setup where I was using the 'asgiref.inmemory.ChannelLayer' and I am currently switching to 'asgi_rabbitmq.RabbitmqChannelLayer' This all seems to work fine until I try to connect to the websocket from the browser. Nothing happens for a while (7 or 8 seconds) and then all of a sudden the websocket.receive gets triggered and the websocket disconnects. I think it is because the reply channel is not receiving my accept message.(or perhaps too late). routing: lobby_routing = [ route('websocket.connect', ws_test_add, path=r"^/testadd/$"), ] Consumer: def ws_test_add(message): print "TEST" message.reply_channel.send({'accept': True}) Group("testadd").add(message.reply_channel) Settings: CHANNEL_LAYERS = { "default": { "BACKEND": "asgi_rabbitmq.RabbitmqChannelLayer", "ROUTING": 'CouchGames_Backend.routing.lobby_routing', "CONFIG": { 'url': 'amqp://guest:guest@localhost:5672/%2F', }, }, } Log: 2018-01-31 20:00:21,141 - INFO - worker - Listening on channels http.request, websocket.connect, websocket.disconnect, websocket.receive 2018-01-31 20:00:21,144 - INFO - worker - Listening on channels http.request, websocket.connect, websocket.disconnect, websocket.receive 2018-01-31 20:00:21,157 - INFO - worker - Listening on channels http.request, websocket.connect, websocket.disconnect, websocket.receive 2018-01-31 20:00:21,157 - INFO - worker - Listening on channels http.request, websocket.connect, websocket.disconnect, websocket.receive 2018-01-31 20:00:21,163 - … -
django-python3-ldap Search Users belonging to Specific Group in Active Directory
I have django-python3-ldap included in my Django project, and I have it pointed at an Active Directory server. It connects to the AD server and returns a the username, first name, and hashed password to the auth_user table. How do I limit the search to only users in a specific AD group? Here are the relevant settings: LDAP_AUTH_SEARCH_BASE = "OU=******,DC=ad,DC=******,DC=org" LDAP_AUTH_USER_FIELDS = { "username": "samaccountname", "first_name": "givenname", "last_name": "surname", "email": "EmailAddress", } LDAP_AUTH_OBJECT_CLASS = "User" LDAP_AUTH_USER_LOOKUP_FIELDS = ("username",) LDAP_AUTH_FORMAT_USERNAME = "django_python3_ldap.utils.format_username_active_directory" LDAP_AUTH_ACTIVE_DIRECTORY_DOMAIN = "AD" LDAP_AUTH_FORMAT_SEARCH_FILTERS = "django_python3_ldap.utils.format_search_filters" I believe I need to use LDAP_AUTH_FORMAT_SEARCH_FILTERS to "and" conditions to the original search base, but I'm not sure exactly how to do so. I assume I need to write a custom format_search_filter, but I don't intuitively understand how it would cross-check with AD groups. -
Multiplying the value of two django integer fields
I am having trouble multiplying the values of two IntegerFields in Django. I am new to Django so I am probably missing something obvious. Here is the error I am getting: NameError at /multiplication/multiplied name 'multiply_two_integers' is not defined Request Method: POST Request URL: http://127.0.0.1:8000/multiplication/multiplied Django Version: 2.0.1 Exception Type: NameError Exception Value: name 'multiply_two_integers' is not defined Here is my code: from django import forms class HomeForm(forms.Form): quantity1 = forms.IntegerField(required = False) quantity2 = forms.IntegerField(required = False) def multiply_two_integers(x,y): return x*y def return_product(self): return multiply_two_integers(quantity1,quantity2) And: from django.shortcuts import render,get_object_or_404 from django.shortcuts import render_to_response from django.template import RequestContext from django.views.generic import TemplateView from multiplication.forms import HomeForm # Create your views here. # def startPage(request): # return render(request, 'multiplication/detail.html') template_name1 = 'multiplication/detail.html' template_name2 = 'multiplication/multiplied.html' def get(request): form = HomeForm() return render(request,template_name1,{'form': form} ) def post(request): form = HomeForm(request.POST) if (form.is_valid()): product = form.return_product() return render(request, template_name2, {'form': form, 'product': product }) And template_name1: <h1>Multiplication Function</h1> <form action = "{% url 'multiplication:post' %}" method = "post"> {{ form.as_p }} {% csrf_token %} <input type = "submit" value ="Multiply"> <!--<button type="submit"> Multiply </button>--> <h1>{{product}}</h1> </form> template_name2: <h1>{{product}}</h1> -
is it wrong in Django SQLITE?
class M_Post(models.Model): '''' CODE '''' class M_File(models.Model): .... CODE .... class M_Post_File(models.Model): post = models.ForeignKey(M_Post,on_delete=models.CASCADE) file = models.ForeignKey(M_File,on_delete=models.CASCADE,null=True) error: django.db.utils.NotSupportedError: Renaming the 'posts_file' table while in a transaction is not supported on SQLite because it would break referential integrity. Try adding atomic = False to the Migration class. is it something wrong in SQLite? -
psycopg2.DataError: invalid input syntax for integer: "test" Getting error when moving code to test server
I'm running Django 1.11 with Python 3.4 on Ubuntu 14.04.5 Moving my development code to the test server and running into some strange errors. Can anyone see what is wrong from the traceback? I'm very new to linux and have made the mistake of developing on a Windows machine on this first go around. I have since created a virtualbox copy of the test and production servers to develop on, but I'm hoping I can salvage what's up on the test server now. I think my app is looking in the correct directory for this environment, but I am a Django, Python and linux noob. Any direction would be very helpful. Thanks! Operations to perform: Apply all migrations: admin, auth, contenttypes, csvimport, sessions, staff_manager Running migrations: Applying staff_manager.0003_auto_20180131_1756...Traceback (most recent call l ast): File "/home/www-root/envs/django_env_1/lib/python3.4/site-packages/django/db/b ackends/utils.py", line 65, in execute return self.cursor.execute(sql, params) psycopg2.DataError: invalid input syntax for integer: "test" The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/home/www-root/envs/django_env_1/lib/python3.4/site-packages/django/core /management/__init__.py", line 364, in execute_from_command_line utility.execute() File "/home/www-root/envs/django_env_1/lib/python3.4/site-packages/django/core /management/__init__.py", line 356, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/www-root/envs/django_env_1/lib/python3.4/site-packages/django/core /management/base.py", line 283, in run_from_argv self.execute(*args, **cmd_options) File "/home/www-root/envs/django_env_1/lib/python3.4/site-packages/django/core … -
what the Django form.is_valid() always false
I'm writing a login code. but form.is_valid() always false I don't know why? model.py class User(models.Model): Man = 'M' Woman = 'W' GENDER_CHOICES=( (Man, 'M'), (Woman, 'W'), ) user_no = models.AutoField(primary_key=True) user_email = models.EmailField(max_length=254) user_pw = models.CharField(max_length=50) user_gender = models.CharField( max_length=1, choices=GENDER_CHOICES, default=Man, ) user_birthday = models.DateField(blank=True) user_jdate = models.DateTimeField(auto_now_add=True) signin.html <form method="post" action="{% url 'signin' %}"> {% csrf_token %} <h3>ID : {{form.user_email}} </h3> <h3>PASSWORD : {{form.user_pw}} </h3> <input type="submit" class="btn_submit" value="로그인" /> views.py def signin(request): if request.method == 'POST': form = Form(request.POST) if form.is_valid(): print("success") else: print("false") else: form = Form() return render(request,'signin.html',{'form':form}) 1) What's wrong? 2)The other signups are true because the signup_bails are true, but why is the signin always false? 3)How do I fix it?