Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
__str__() method in django not callable
I wrote the following code in my model in django. When I try to use the str() method, I get an error that the method isn't callable. Is there something I am missing? from django.db import models from organizer.models import Startup, Tag # Create your models here. class Post(models.Model): title = models.CharField(max_length=63) slug = models.SlugField( max_length=63, help_text='A label for URL config', unique_for_month='pub_date') text = models.TextField() pub_date = models.DateField('date published', auto_now_add=True) tags = models.ManyToManyField( Tag, related_name='blog_posts') startups = models.ManyToManyField( Startup, related_name='blog_posts') def __str__(self): return "{} on {}" (self.title, self.pub_date.strftime('%Y-%m_%d')) class Meta: verbose_name = 'blog post' ordering = ['-pub_date', 'title'] get_latest_by = 'pub_date' -
how can i resolve this error in executing test.py?
ERROR: test_register (login.tests.LoginTestCase) ---------------------------------------------------------------------- Traceback (most recent call last): File "/home/asif/Desktop/project/playlist/login/tests.py", line 19, in setUp self.selenium = webdriver.Firefox() File "/home/asif/Desktop/genv/local/lib/python2.7/site-packages/selenium/webdriver/firefox/webdriver.py", line 144, in __init__ self.service.start() File "/home/asif/Desktop/genv/local/lib/python2.7/site-packages/selenium/webdriver/common/service.py", line 74, in start stdout=self.log_file, stderr=self.log_file) File "/usr/lib/python2.7/subprocess.py", line 711, in __init__ errread, errwrite) File "/usr/lib/python2.7/subprocess.py", line 1343, in _execute_child raise child_exception OSError: [Errno 20] Not a directory ---------------------------------------------------------------------- Ran 1 test in 0.512s FAILED (errors=1) Destroying test database for alias 'default'... I tried running this command: $ ./manage.py test Below is my test.py: from django.test import LiveServerTestCase from selenium import webdriver from selenium.webdriver.common.keys import Keys def views_login_user(): pass def test_login(): views_login_user() class LoginTestCase(LiveServerTestCase): def setUp(self): self.selenium = webdriver.Firefox() super(LoginTestCase, self).setUp() def tearDown(self): self.selenium.quit() super(LoginTestCase, self).tearDown() def test_register(self): selenium = self.selenium #Opening the link we want to test selenium.get('http://127.0.0.1:8000/login/register/') #find the form element username = selenium.find_element_by_id('id_username') email_address= selenium.find_element_by_id('id_email_address') password = selenium.find_element_by_id('id_password') submit = selenium.find_element_by_name('register') #Fill the form with data username.send_keys('gouthami') email_address.send_keys('gouth@gmail.com') password.send_keys('gouthu') #submitting the form submit.send_keys(Keys.RETURN) #check the returned result assert 'Check your email' in selenium.page_source -
Internal Server Error for Django with uwsgi / nginx on Debian8.7
I'm pretty beginner in server technologies and I'm struggling to deploy a Django app to Debian8 server. I've been following : this tutorial but I couldn't start uWSGI service so I followed this recommendation and switched to systemd. Then I've been able to run my app in development mode on port :8000 but couldn't load it in browser. The logs say: no python application found, check your startup logs for errors Above this note in logs it complains on not being able load whitenoise module: File "./testdjango/wsgi.py", line 35, in <module> from whitenoise.django import DjangoWhiteNoise which means (if I'm not mistaken) it doesn't load virtual environment. But if I run uwsgi terminal command uwsgi --http :8000 --chdir /home/djangouser/testdjango --module testdjango.wsgi:application --env DJANGO_SETTINGS_MODULE=testdjango.settings --home=/home/djangouser/Env/myapp_env the app works. I have no ideas why it happens and I'd appreciate any help or guide. I did search before I posted this question here and in fact I've been trying many different solutions without success for the last three days. Because of that my files seems to be messy now. My apologies for that. I use django 1.8, virtualenvvrapper, sudo user named djangouser and the folder structure on the server looks like this: -home | … -
Azure Django deployment failure
I am trying to deploy a Django web app to Azure app service. I have set up the continuous deployment with a Github repo for the project. The project is functuioning locally. The deployment is failing with the following logs: Command: deploy.cmd Handling python deployment. KuduSync.NET from: 'D:\home\site\repository' to: 'D:\home\site\wwwroot' Copying file: 'web.2.7.config' Detected requirements.txt. Creating virtual environment. The system cannot find the path specified. An error has occurred during web site deployment. The system cannot find the path specified. The system cannot find the path specified.\r\nThe system cannot find the path specified.\r\nD:\Program Files(x86)\SiteExtensions\Kudu\61.60316.2745\bin\Scripts\starter.cmd deploy.cmd I have included the following deployment files at the project root level: .deployment, deploy.cmd, ptvs_virtualenv_proxy.py, requiremnts.txt, web.2.7.config I tried deploying the project from a local git repo. Which returned the following logs: git push azure Counting objects: 198, done. Delta compression using up to 4 threads. Compressing objects: 100% (118/118), done. Writing objects: 100% (198/198), 47.36 KiB | 0 bytes/s, done. Total 198 (delta 94), reused 120 (delta 65) remote: Updating branch 'master'. remote: Updating submodules. remote: Preparing deployment for commit id 'a68e71809f'. remote: Running custom deployment command... remote: Running deployment command... remote: Handling python deployment. remote: KuduSync.NET from: 'D:\home\site\repository' to: 'D:\home\site\wwwroot' remote: Copying file: … -
No module named import_export although it is in site-packages
I am beginner in Django and I am using this by installing with pip on my server. https://github.com/django-import-export/django-import-export My python version is 2.7. This is m PYTHONPATH, -bash-4.2$ echo $PYTHONPATH /home/khantthulinn/lib/python2.7:/home/khantthulinn/.local/lib/python2.7/site-packages This is my sys.path. /home/khantthulinn/webapps/mmspeaker/lib/python2.7/Django-1.8.14-py2.7.egg /home/khantthulinn/webapps/mmspeaker/lib/python2.7 /home/khantthulinn/webapps/mmspeaker/lib/python2.7/site-packages /home/khantthulinn/lib/python2.7/pip-8.1.2-py2.7.egg /home/khantthulinn/lib/python2.7 /home/khantthulinn/webapps/mmspeaker/myproject /usr/lib64/python27.zip /usr/lib64/python2.7 /usr/lib64/python2.7/plat-linux2 /usr/lib64/python2.7/lib-tk /usr/lib64/python2.7/lib-old /usr/lib64/python2.7/lib-dynload /home/khantthulinn/.local/lib/python2.7/site-packages /usr/lib64/python2.7/site-packages /usr/lib64/python2.7/site-packages/PIL /usr/lib64/python2.7/site-packages/geos /usr/lib/python2.7/site-packages I really saw import_export here like this. But when I import in my settings.py like this, it say no module named import_export. INSTALLED_APPS = ( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'provider', 'provider.oauth2', 'push_notifications', 'import_export', ) How shall I do? -
How to cache user.groups in a request so db isn't hit every time you call request.user.groups.all()?
I'm using Django with Django REST and have a user permission system based on user groups. As a result I have to check assigned user groups a few times inside views to see if a user belongs to a certain group using request.user.groups.all(). It works but every such call results in an extra query to db to retrieve groups. I wish I could override some method that pulls a user from a db during authentication before attaching it to a request, so I can add something like User.objects.get(pk=userid).prefetch_related('groups') so no extra calls would be made whenever I access groups further down. -
django-environ and raven.fetch_git_sha
I am developing a cookiecutter-django project. I am trying to get the release value from my repository for the purposes of using it with Sentry.io In common.py the root directory is set via this line: ROOT_DIR = environ.Path(__file__) - 3 This creates a Path object pointing to the directory with the git HEAD information. In production.py, there is the following: RAVEN_CONFIG = { 'CELERY_LOGLEVEL': env.int('DJANGO_SENTRY_LOG_LEVEL', logging.INFO), 'DSN': SENTRY_DSN, 'release': **fetch_git_sha(ROOT_DIR)**, } This is not working. The error is: Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/home/bucket/Envs/bprod/lib/python3.5/site-packages/raven/versioning.py", line 22, in fetch_git_sha head_path = os.path.join(path, '.git', 'HEAD') File "/home/bucket/Envs/bprod/lib/python3.5/posixpath.py", line 89, in join genericpath._check_arg_types('join', a, *p) File "/home/bucket/Envs/bprod/lib/python3.5/genericpath.py", line 143, in _check_arg_types (funcname, s.__class__.__name__)) from None TypeError: join() argument must be str or bytes, not 'Path' So I tried to create a string via os.path.realpath() and I get this: Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/home/bucket/Envs/bprod/lib/python3.5/posixpath.py", line 373, in realpath path, ok = _joinrealpath(filename[:0], filename, {}) File "/home/bucket/Envs/bprod/lib/python3.5/posixpath.py", line 388, in _joinrealpath if isabs(rest): File "/home/bucket/Envs/bprod/lib/python3.5/posixpath.py", line 64, in isabs return s.startswith(sep) AttributeError: 'Path' object has no attribute 'startswith' I have looked around the django-environ docs and cannot find a string … -
Customizing RESTful response in django
i'm using iframely to generate a JSON response from a given URL, the URL i'm passing redirects to a page containing a 3d component made with threejs but iframely seem do not support threejs so it does not return a response at all and not an empty response. i had the idea of actually creating a customized response when i call the iframely api. the response is supposed to contain a field called html in which i call the threejs script, and then when i consume this response in the front end, the browser will upload the threejs file and creating the 3d component. so my response should look something like this { "html": "<script src="path/jquery-2.0.3.js"></script> <script src="path/three.js"></script>" } and my code so far is r = requests.get('http://iframe.ly/api/oembed?url=' + url + '&api_key=' + settings.IFRAMELY_KEY) my problem is idon't know how to customize the response -
Append file upload form element using JavaScript in Django
I have a file upload form in my edit_file.html template which opens when I want to edit an already uploaded file, and it looks like this in the browser window: I want to add file's thumbnail beside the file_name.jpg (Remove) links without any other label/grey-panel, below/above it: and on clicking the (Remove) link should bring back the select the file to upload label and the grey panel and hide the thumbnail, as shown in the first image. The file_name.jpg and (Remove) links show because of {{ form.file }} object in my form.html file which looks like this: <div id="form_body" class="form-group {% if form.file.errors %} has-error {% endif %}"> <label class="form_well" class="control-label required" for="{{ form.file.id_for_label }}"> {% trans "Select the file to upload" %} </label> <div class="form_well well file-well"> --> {{ form.file }} //this is the object which stores the "file_name, (Remove) links" if file is present, else it shows an "upload button" <p class="help-block"> {% trans "Accepted file types: pdf, mp3, mp4, doc, docx, jpg, png, gpx, csv, xls, xlsx, gif, tiff" %} </p> </div> <div class="error-block">{{ form.file.errors }}</div> </div> So, to accomplish what I want, I used JQuery to first dynamically hide that Select the file to upload label … -
How to hide charField widget and show only label of field in django forms?
I'm developing an application with django framework. I have a model that has these fields : class Post(models.Model): author = models.ForeignKey('auth.User') title = models.CharField(max_length=1, null=True, blank=True) text = models.TextField() created_date = models.DateTimeField( default=timezone.now) published_date = models.DateTimeField( blank=True, null=True) #forms.py class PostForm(forms.ModelForm): class Meta: model = Post fields = ('title', 'text',) def __init__(self, *args, **kwargs): super(PostForm, self).__init__(*args, **kwargs) self.fields['title'].widget = #what to put here ? For title field I want only to show the help_text in Italics and not the CharField Input. Do Django permit doing something like that ? -
Navigation links not working in navbar (Bootstrap)(Django)
I'm creating a website using django 1.10 and python 3.6. My web app is called 'profiles' and project is called 'firstsite'. I used a template from bootstrap which is saved as 'base.html'. I have two pages in my webapp which use template 'home.html' and 'about.html'. Navigation bar is another html file called 'navbar.html'. I'm trying to link 'home' and 'about' in navigation bar. After linking, when i runserver and open 'http://127.0.0.1:8000/' I get 'NoReverseMatch at/' error. firstsite/firstsite/urls.py from django.conf import settings from django.conf.urls.static import static from django.conf.urls import url, include from django.contrib import admin urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^', include('profiles.urls')), ] if settings.DEBUG: urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) firstsite/profiles/urls.py from django.conf.urls import url from profiles import views app_name = 'profiles' urlpatterns = [ url(r'^$', views.home, name='home'), url(r'^about/$', views.about, name='about'), ] firstsite/profiles/views.py from django.shortcuts import render def home(request): context = locals() template = 'home.html' return render(request, template, context) def about(request): context = locals() template = 'about.html' return render(request, template, context) firstsite/profiles/templates/base.html {% load staticfiles %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <!-- The above 3 meta tags *must* come first in the head; any other head content must come … -
How to share a session (in Redis) between two web servers running the same django application?
I have this: Server1: runs django server runs redis server (used as cache and session store) Server2: runs django server (same application as above) connects to redis on Server1 and uses it for cache and session store Server1 and Server2 are meant to be load balanced web servers that run the same application, so ideally one should log in to only one of them (and automatically the session would be shared with the other). I am not getting this result now. This is what I have on Server1: CACHES = { 'default': { 'BACKEND': 'redis_cache.RedisCache', 'LOCATION': '127.0.0.1:6379', 'OPTIONS': { 'DB': 1, }, }, } CACHE_TTL = 60 * 15 SESSION_ENGINE = "django.contrib.sessions.backends.cached_db" This is what I have on Server2: CACHES = { 'default': { 'BACKEND': 'redis_cache.RedisCache', 'LOCATION': '<hostname of Server1>:6379', 'OPTIONS': { 'DB': 1, }, }, } CACHE_TTL = 60 * 15 SESSION_ENGINE = "django.contrib.sessions.backends.cached_db" What am I missing? -
Django Rest-Framework Serializer: keyerror thrown on field that certainly exists
In the process of building a django-based web application, I came across an error, which I cannot figure how to solve. In the application, my Angular2 front-end sends a post request, which passes to the back-end a JSON object of the following form: { "variable": { "name": "testVar" } } Upon receiving the request the flow of the program goes to the post function, which is defined in the following view, which inherits from django rest-framework's APIView. class VariableAPIView(APIView): permission_classes = (AllowAny, ) renderer_classes = (VariableJSONRenderer, ) serializer_class = VariableNameSerializer def post(self, request): variable = request.data.get('variable', {}) serializer = self.serializer_class(data=variable) serializer.is_valid(raise_exception=True) return Response(serializer.data, status=status.HTTP_200_OK) The serializer's main logic happens in this snippet of code. class VariableNameSerializer(serializers.Serializer): name = serializers.CharField(max_length=255) def validate(self, data): name = data.get('name', None) if name is None: raise serializers.ValidationError('A variable name is required.') try: value = server.ReadVariable(name) except Exception: raise serializers.ValidationError('A variable with this name could not be found') return { 'value': value, } When the django-server receives a request, I get the following exception: KeyError: 'name' During handling of the above exception, another exception occurred: KeyError: "Got KeyError when attempting to get a value for field name on serializer VariableNameSerializer. The serializer field might be named … -
Configuring Django/Wagtail media to use S3
I'm using the following guide: https://www.caktusgroup.com/blog/2014/11/10/Using-Amazon-S3-to-store-your-Django-sites-static-and-media-files/ At the section that instructs you on how to "Configuring Django media to use S3". I'm using this for Wagtail. I'm unclear on where to put the "custom_storages.py" settings. Everywhere I'm putting it doesn't seem to work. I reverted back to Whitenoise for now. Thanks! -
AWS Elastic Beanstalk throws error when collecting appdirs from requirements.txt
I'm currently deploying a fairly simple Django site to AWS Elastic Beanstalk, but my most recent deployment failed with CalledProcessError: Command '/opt/python/run/venv/bin/pip install -r /opt/python/ondeck/app/requirements.txt' returned non-zero exit status 1 Digging deeper into the logs upon creating a new environment and using the new build as the initial deployment, I found: File "/usr/lib64/python2.7/subprocess.py", line 541, in check_call raise CalledProcessError(retcode, cmd) CalledProcessError: Command '/opt/python/run/venv/bin/pip install -r /opt/python/ondeck/app/requirements.txt' returned non-zero exit status 1 (ElasticBeanstalk::ExternalInvocationError) caused by: Collecting appdirs==1.4.3 (from -r /opt/python/ondeck/app/requirements.txt (line 1)) Downloading appdirs-1.4.3-py2.py3-none-any.whl My Requirements.txt: appdirs==1.4.3 beautifulsoup4==4.5.3 boto==2.46.1 Django==1.10.6 django-ses==0.8.2 DoubleMetaphone==0.1 future==0.16.0 html5lib==0.999 nameparser==0.4.0 packaging==16.8 probableparsing==0.0.1 probablepeople==0.5.2 pyparsing==2.2.0 python-crfsuite==0.9.1 requests==2.4.3 six==1.10.0 I'm not sure why AWS would have an issue collecting appdirs but if anyone has any idea, I'd appreciate it. -
Reading strings from file vs reading them from redis cache?
In a django app, I need to check frequently user posts to determine whether they contain any spam words. I can put the list of spam words either in a list and fetch them from file or I can put them in a database table, cache the table in redis and iterate over redis keys. I'm wondering what would be the difference of these method in terms of application performance? And what is generally considered a better approach? -
Django how to copy and instance of an app which use same models but need to direct to different tables
I have a Django Application that I created but I would like to add another copy of that same application with a couple modifications. I was thinking I can just copy the directory and add it to the install applications and modify the urls so that they don't have any similar urls. Is there another way that would be more effective? I also would still like to use the same models to the same database but direct them to another set of tables, is this possible? Thanks -
Django: Bootstrap button link doesn't work
I created a link in my polls application of Django and it looks like my Button links doesn't work. What is the mistake I am doing here? My urls.py is from django.conf.urls import url from . import views app_name = 'polls' urlpatterns = [ # ex: /polls/ #url(r'^$', views.index, name='index'), url(r'^$', views.IndexView.as_view(), name='index'), url(r'^login/$', views.LoginView.as_view(), name='login'), # ex: /polls/5/ # the 'name' value as called by the {$ url $} template tag #url(r'^(?P<question_id>[0-9]+)/$', views.detail, name='detail'), url(r'^(?P<pk>[0-9]+)/$', views.DetailView.as_view(), name='detail'), # ex: /polls/5/results/ #url(r'^(?P<question_id>[0-9]+)/results/$', views.results, name='results'), url(r'^(?P<pk>[0-9]+)/results/$', views.ResultsView.as_view(), name='results'), # ex: /polls/5/vote/ url(r'^(?P<ballot_id>[0-9]+)/vote/$', views.vote, name='vote'), ] And I create buttons and links like this <button type="submit" class="btn btn-primary"><a href="{% url 'polls:index' %}"></a> {% bootstrap_icon "home" %} </button> <button type="submit" class="btn btn-primary"><a href="{% url 'polls:login' %}"></a> {% bootstrap_icon "user" %} User Login </button> -
upgrade from django 1.10.6 to 1.11 runserver giving exception
After upgrading django from 1.10.6 to 1.11 while runserver I am getting following exception. models.Q is inherited from tree.Node and there is no significant change around this in both the versions that could break usage of Q. class LimitTagAssociations(): def __init__(self, criteria): self.criteria = criteria def add_to_query(self, query, aliases): query.add_q(models.Q(id__in=[1, 2, 3])) query.distinct = True class Cat(models.Model): new_and_now_reco_base = fields.IntegerRangeField(min_value=500, max_value=10000, default=1000) auto_taggroups = models.ManyToManyField(TagGroup, null=True, blank=True, limit_choices_to=LimitTagAssociations('1')) manual_taggroups = models.ManyToManyField(TagGroup, null=True, blank=True, limit_choices_to=LimitTagAssociations('2')) abs_url = models.CharField(max_length=255, blank=True, null=True) primary_filter_select = models.ManyToManyField(TagGroup, null=True, blank=True, limit_choices_to=LimitTagAssociations('3')) Traceback (most recent call last): File "/srv/webapps/bigbasket.com/virtualenvs/bigbasket1.9/local/lib/python2.7/site-packages/django/utils/autoreload.py", line 227, in wrapper fn(*args, **kwargs) File "/srv/webapps/bigbasket.com/virtualenvs/bigbasket1.9/local/lib/python2.7/site-packages/django/core/management/commands/runserver.py", line 117, in inner_run autoreload.raise_last_exception() File "/srv/webapps/bigbasket.com/virtualenvs/bigbasket1.9/local/lib/python2.7/site-packages/django/utils/autoreload.py", line 250, in raise_last_exception six.reraise(*_exception) File "/srv/webapps/bigbasket.com/virtualenvs/bigbasket1.9/local/lib/python2.7/site-packages/django/utils/autoreload.py", line 227, in wrapper fn(*args, **kwargs) File "/srv/webapps/bigbasket.com/virtualenvs/bigbasket1.9/local/lib/python2.7/site-packages/django/__init__.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) File "/srv/webapps/bigbasket.com/virtualenvs/bigbasket1.9/local/lib/python2.7/site-packages/django/apps/registry.py", line 116, in populate app_config.ready() File "/srv/webapps/bigbasket.com/virtualenvs/bigbasket1.9/local/lib/python2.7/site-packages/django/contrib/admin/apps.py", line 23, in ready self.module.autodiscover() File "/srv/webapps/bigbasket.com/virtualenvs/bigbasket1.9/local/lib/python2.7/site-packages/django/contrib/admin/__init__.py", line 26, in autodiscover autodiscover_modules('admin', register_to=site) File "/srv/webapps/bigbasket.com/virtualenvs/bigbasket1.9/local/lib/python2.7/site-packages/django/utils/module_loading.py", line 50, in autodiscover_modules import_module('%s.%s' % (app_config.name, module_to_search)) File "/usr/lib/python2.7/importlib/__init__.py", line 38, in import_module __import__(name) File "/srv/webapps/bigbasket.com/BigBasket/product/admin.py", line 6, in <module> from product.forms import ProductChangeLogFilterForm, PopularBrandAdminForm File "/srv/webapps/bigbasket.com/BigBasket/product/forms.py", line 124, in <module> class CategoryAdminForm(forms.ModelForm): File "/srv/webapps/bigbasket.com/virtualenvs/bigbasket1.9/local/lib/python2.7/site-packages/django/forms/models.py", line 252, in __new__ opts.field_classes) File "/srv/webapps/bigbasket.com/virtualenvs/bigbasket1.9/local/lib/python2.7/site-packages/django/forms/models.py", line 177, in fields_for_model formfield.queryset = … -
'social' is not a registered namespace
I'm trying to implement a facebook authentication into my project. However after installation of social_django and proper configurations I've got: NoReverseMatch at /account/login/ 'social' is not a registered namespace Don't have an idea why it isn't working, maybe because I'm pretty new to Django. I'm using Django v1.10.6 and social-django v1.1.0. Any help will be very appreciated! urls.py: urlpatterns = [ url(r'^login/$', login, {'template_name': 'accounts/login.html'}, name='login'), url(r'^oauth/', include('social_django.urls', namespace='social')), ] template.html: <a href="{% url 'social:begin' 'facebook' %}">Login with Facebook</a> -
Upload a file in python/Django
I have an issue, I'm using django rest framework and I need to submit a image to server using a webservice, however I don't find anything like I actually need, I would like just to provide the location of the file and let the service do the work uploading it, is there a way I can achieve that?, ofc I will only will save the filepath on DB class AdvertisementData(EmbeddedDocument): id = ObjectIdField(null=False, primary_key=True) brand = StringField(max_length=200, required=False) name = StringField(max_length=200, required=False) description = StringField(max_length=200, required=False) image = StringField(required=False)//HERE THE FILEPATH active = BooleanField(required=True) target = EmbeddedDocumentField('TargetData') -
Saving the form while there are two ForeignKeys,
I have two models as shown below class college(models.Model): name = models.CharField(max_length=256) class education(models.Model): author = models.ForeignKey('auth.User') school = ForeignKey(college) field = models.CharField(max_length=200) startyear = models.IntegerField(blank =True,null = True) endyear = models.IntegerField(blank =True,null = True) Views as shown below class EducationListView(ListView): template_name = 'dupeducation.html' def get_queryset(self): return education.objects.filter(author__username=self.request.user.username).order_by('-startyear') class EducationCreate(CreateView): model = dupeducation fields = ('school','field','startyear','endyear') template_name = 'education_form.html' def form_valid(self, form): form.instance.author = self.request.user obj,created = college.objects.get_or_create(name=form['school']) obj.save() form.instance.school = obj return super(EducationCreate, self).form_valid(form) class EducationUpdate(UpdateView): model = education fields = ('school','field','startyear','endyear') template_name = 'education_form.html' def form_valid(self, form): form.instance.author = self.request.user return super(EducationUpdate, self).form_valid(form) class EducationDelete(DeleteView): model = education success_url = reverse_lazy('education') I am unable to save the form. It's throwing an error to the school field like this "Select a valid choice. That choice is not one of the available choices.". My goal is to take input for the school field and check that field with get_object_or_create . If that object does not exist, create it and attach it to the school field. -
How to customize html of one form field in a form?
I need the user to enter data into a form in my django app. I am currently doing this like so: forms.py: (using model form) class BabysittingForm(forms.ModelForm): class Meta: model = models.Babysitting fields = [ 'title', 'pay', 'start_date', 'end_date', 'num_children', 'babysitting_address', 'babysitting_day_of_week', 'babysitting_start_time_of_day', 'babysitting_session_length_hours', 'description', ] Here is my models.py: class Job(models.Model): employer = models.ForeignKey(settings.AUTH_USER_MODEL, related_name="jobs") hired_user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=True) created_at = models.DateTimeField(auto_now_add=True) start_date = models.DateTimeField(default=datetime.now()) end_date = models.DateTimeField(default=datetime.now()) location = models.CharField(default="None", max_length=40) title = models.CharField(max_length=30) description = models.TextField() category = models.CharField(max_length=3, choices=JOB_CATEGORY_CHOICES) pay = models.FloatField() hourly_pay = models.BooleanField(default=True) complete = models.BooleanField(default=False) def __str__(self): return self.title def get_absolute_url(self): return reverse('jobs:detail', kwargs={ 'job_pk': self.id } ) class Babysitting(Job): num_children = models.PositiveSmallIntegerField() babysitting_address = models.CharField(default="None", max_length=40) babysitting_day_of_week = models.CharField(max_length=2, choices=DAYS_OF_WEEK_CHOICES) babysitting_start_time_of_day = models.CharField(max_length=8) babysitting_session_length_hours = models.FloatField() Here is my layout: {% extends 'layout.html' %} {% load bootstrap3 %} {% block title %}{{ form.instance.title|default:"New Job" }}{% endblock %} {% block content %} <div class="container"> <h1>{{ form.instance.title|default:"New Job" }}</h1> <form action="" method="POST"> {% bootstrap_form form %} {% csrf_token %} <input type="submit" value="Post Job" class="btn btn-default"/> </form> </div> {% endblock %} I need to change the appearance of the pay form field to this: I know how to style it this way but I … -
django.db.utils.ProgrammingError: relation "locations_location" does not exist during migrate
I created a custom app, locations, for my project. I don't know what, but something got messed up along the way in setup. I removed all migrations and deleted everything from the db for this app to start fresh and I'm still getting an error when I try to do the initial migrate after creating the tables. Is something wrong with my model? I don't understand the error. class Staff(models.Model): first_name = models.CharField(max_length=255) last_name = models.CharField(max_length=255) about = models.CharField(max_length=255) class Map(models.Model): image = models.ImageField() class Location(models.Model): name = models.CharField(max_length=255) phone = models.CharField(max_length=20, verbose_name="Phone Number") email = models.CharField(max_length=255, verbose_name="Email Address") # manager = models.ForeignKey(Staff,related_name='+') staff = models.ManyToManyField(Staff) map = models.ForeignKey(Map, null=True) -
Django use model field's validators for client-side validation
I have some example model with field: class Task(models.Model): priority = models.IntegerField(default=30, validators=[MinValueValidator(0), MaxValueValidator(300)]) When I create a ModelForm object by modelform_factory() function and generate html with .as_table() function then for this field I get something like: <input type="number" name="priority" value="30" required="" id="id_priority"> But I would like the output to look like this: <input type="number" name="priority" value="30" required="" id="id_priority" min="0" max="300"> What is the best way to do that?