Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How do I display time since creation instead of time created in Django
I am working on displaying a post in django and currently to display when the post was created, I am using {{ instance.post_created }}. I was wondering if there was anyway I could get it to say "2 days ago" if the post was made on the 28th of Jan and the person was viewing it on the 30th of Jan as an example. Thanks for any help, Will -
Django: How to refresh table after filtering without refreshing the whole page?
The root of the issue is how to refresh the filtered table dynamically, without refreshing the whole page. I am almost novice in python/html/css, so please make some comments like for a newbie [Thanks]. After some research on StackOverFlow, I found that it could be made with js, but I have almost no experience with js and I don't know how to use it in Django. Is there any possibility using only Django tools? And how efficient it would be? Maybe you can provide some examples of resolving the issue. Here is the model: class Player(models.Model): last_name = models.CharField( null=True, blank=True, max_length=255, verbose_name="прізвище" ) first_name = models.CharField( null=True, blank=True, max_length=255, verbose_name="ім'я" ) city = models.ForeignKey( City, on_delete=models.SET_NULL, null=True, blank=True, verbose_name="місто" ) rating = models.PositiveIntegerField( null=True, blank=True, verbose_name="рейтинг" ) rank = models.ForeignKey( Rank, on_delete=models.SET_NULL, null=True, blank=True, verbose_name="ранг" ) local_rank = models.ForeignKey( LocalRank, null=True, blank=True, on_delete=models.SET_NULL, verbose_name="розряд" ) def __str__(self): if self.last_name and self.first_name: return self.last_name + ' ' + self.first_name elif self.egd_last_name and self.egd_first_name: return self.egd_last_name + ' ' + self.egd_first_name else: return self.id I am using django-tables2 to render the table: class PlayerTable(tables.Table): full_name = tables.LinkColumn( accessor="__str__", verbose_name="Прізвище та ім'я", order_by="last_name", viewname='UGD:player_info', empty_values=(), args=[A('pk')] ) local_rank = tables.Column( accessor="local_rank.abbreviate", order_by="id" … -
Rendering and post that data JQuery
I am a bit stuck here and would like to get some input from the community. So I have a HTML page that contains a table, one of the columns is solely populated with checkboxes, underneath this table is my pseudo 'submit' button, when this is clicked it will scan the table and get the keys of any checked checkboxes this is all fine. The part I cannot get to work is with this rendered data I wish to post (move it) to another page/template. What I have tried: To do this I have tried posting the data to a view using AJAX (which worked) but I then realised and read that I could not redirect and render a new template in my AJAX call. A form with an invisible field. I set the button to an actual submit button and when the data was rendered I plugged it into the forms field. The logic was all fine however I couldn't get it to redirect, 'action="myurl/"' just changed the URL but kept the same template, it ignored the urls.py file telling it to load a new view+template I also tried to post through JQuery but this gave me a CSRF … -
Django - callback whenever data has changed in admin
I'm working on a project where I use Django's admin "power" to manage a few models, which are to be displayed in a visualization (made with JavaScript). Javascript can read the data in json, so I need a way to convert the data for my models to json. I'll use Django's serialization tools. I figure it makes more sense to generate a json file only when a create / edit / delete action has been performed on the admin side. How can I make sure a callback (to do the serialization) is triggered every time the data changes in the admin side ? -
Django profile model : Strange Error
Unexplained results due to OneToOne field ( I suppose ) See the bottom for my problems Output in terminal : In [21]: profile = User.objects.get(email='jlennon@beatles.com') In [22]: profile Out[22]: <User: jlennon@beatles.com> In [23]: profile = User.objects.get(email='jlennon@beatles.com').profile In [24]: profile Out[24]: <Users: Aniket> In [25]: profile = User.objects.get(id=2).profile In [26]: profile Out[26]: <Users: Aniket> In [27]: User.objects.get(id=2) Out[27]: <User: jlennon@beatles.com> In [28]: User.objects.get(id=4) Out[28]: <User: AniketYadav> models.py : class Users(models.Model): user = models.OneToOneField(User, related_name='profile') user_Id = models.BigAutoField(primary_key=True) user_name = models.CharField(max_length=25) user_fname = models.CharField(max_length=40, blank=True, null=True) user_lname = models.CharField(max_length=40, blank=True, null=True) user_email = models.CharField(max_length=60) user_password = models.CharField(max_length=255) joining_date = models.DateTimeField() user_dob = models.DateField() user_country = models.CharField(max_length=3, blank=True, null=True) user_gender = models.CharField(max_length=1) user_pic = models.CharField(max_length=255, blank=True, null=True) user_about = models.CharField(max_length=512, blank=True, null=True) class Meta: verbose_name = 'Users' verbose_name_plural = 'Users' managed = False db_table = 'tbl_users' def __unicode__(self): return self.user_name def __str__(self): return self.user_name settings.py AUTH_PROFILE_MODULE = 'myWebsite.Users' my database : mysql> select id, username, email from auth_user where id=1 or id=2 or id=4; +----+---------------------+---------------------+ | id | username | email | +----+---------------------+---------------------+ | 1 | admin | admin@admin.com | | 2 | jlennon@beatles.com | jlennon@beatles.com | | 4 | AniketYadav | aniket@gmail.com | +----+---------------------+---------------------+ 3 rows in set (0.00 sec) My Users … -
Wagtail ModelAdmin with list_filter error: FieldDoesNotExist: Region has no field named 'p'
I've got a model I'm exposing through Wagtail's modeladmin that works until I try to apply a list_filter including a ForeignKey. I've got a self-referencing model (to store Counties, Cities, and Towns) called Region that I'd like to be able to create a filter on by the Parent level. I'm running Wagtail 1.8.1 on Django 1.10. Here's the model: class Region(models.Model): """ Tree of regions and sub-regions. """ name = models.CharField(max_length=255) parent = models.ForeignKey( 'Region', blank=True, null=True, ) class Meta: unique_together = ('name', 'parent') def __str__(self): return '{0}'.format( self.name, ) And the ModelAdmin from wagtail_hooks.py: class RegionAdmin(ModelAdmin): model = Region menu_icon = 'doc-full-inverse' empty_value_display = 'ROOT' list_display = ('parent', 'name') list_filter = ('parent') modeladmin_register(RegionAdmin) It works fine if I comment out the list_filter line in the class RegionAdmin. The documentation says it can take a ForeignKey in the list. Am I missing something obvious? Stack trace is here: Traceback (most recent call last): File "/home/vagrant/.virtualenvs/sepia/lib/python3.5/site-packages/django/core/handlers/exception.py", line 39, in inner response = get_response(request) File "/home/vagrant/.virtualenvs/sepia/lib/python3.5/site-packages/django/core/handlers/base.py", line 187, in _get_response response = self.process_exception_by_middleware(e, request) File "/home/vagrant/.virtualenvs/sepia/lib/python3.5/site-packages/django/core/handlers/base.py", line 185, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/vagrant/.virtualenvs/sepia/lib/python3.5/site-packages/django/views/decorators/cache.py", line 43, in _cache_controlled response = viewfunc(request, *args, **kw) File "/home/vagrant/.virtualenvs/sepia/lib/python3.5/site-packages/wagtail/wagtailadmin/decorators.py", line 24, in decorated_view … -
Can I configure Django project within pydev project in eclipse?
I have a python project, with a django project whitin it. That means the root of the django project is a directory inside my project. I previously worked with pycharm, and could define the django root as a django project- and then enjoy the benefits of django whitin my project. I am now using eclipse neon, and it seems the only thing i can do is define the project root as django project. This results in 'errors' eclipse think i have- since the imports from django (which works on production mode) are not recognized by eclipse. Example: project_root dir1 dir2 files django_root django_app_modules django_sub_module Now, if I have in my code imports from: django_app_modules.django_sub_module, eclipse won't recognize them since it doesn't find them inside the project root, unlike pycharm where it knew to look for them inside the django_root. I can't believe eclipse doesn't support this as well, but I just can't find how to do it. Thanks -
Lets Encrypt multiple nginxconf
I have some questions regarding the use of Let's Encrypt with multiple nginxconf files. .well-known location block Do I need to put this location block in every nginxconf file, or just in the default nginxconf? location ~ /.well-known { allow all; } My default config file is used for showing the "Nginx is working" page. My other serverblocks, which are in seperate nginxconf files, are used for binding a specific application to a specific domain. What is my document root? I serve multiple Django applications on my server. In the Let's Encrypt tutorial they are talking about a document root. Should this be a single document root for all my applications/certificates (for example /var/www/html) or does each application have it's own document root (for example the root folder of my Django application)? Note: my Django application are NOT in /var/www/html, but in a directory WITHIN my home directory. -
Django is downloading file instead of displaying it
I am trying to display an HTML file from my Django code. but my file is getting downloaded instead of displaying. Can anybody please help me out? Following is my code: @api_view(['GET']) def download_y9cfile1(request, file_name): filePath = CommonUtils.get_absolute_file_path('app', 'static', 'generated', 'HTML' , file_name) return render(request, file_name) -
Django REST Framework Import Error
I'm trying to install Django REST framework and I keep getting: No module named 'rest_framework' I've added: 'rest_framework' to my INSTALLED_APPS = [] I installed through pip3 and it still doesn't seem to be working. -
I want to make two sort of tags in one picture by using django-taggit
What I want to make(picture) Dear, all. I want to make two sort of tags in one picture by using django-taggit I can't understand the document. please help me this is my model. from taggit.managers import TaggableManager from taggit.models import TaggedItemBase class Taggedperson(TaggedItemBase): content_object= models.ForeignKey('person') class Admin: pass class Taggedplace(TaggedItemBase): content_object= models.ForeignKey('place') class Admin: pass class Photo(models.Model): user = models.ForeignKey(User) image_file = ProcessedImageField(upload_to='static_files/uploaded/%Y', format='JPEG', options={'quality': 100 }) person = TaggableManager(through=Taggedperson) place = TaggableManager(through=Taggedplace) description = models.TextField(max_length=500, blank=True) Comments = models.PositiveSmallIntegerField(default=0, null=True) posted_on = models.DateTimeField(default=datetime.now) def get_absolute_url(self): return reverse_lazy('index') class Admin: pass def delete(self, *args, **kwargs): self.image_file.delete() super(Photo, self).delete(*args, **kwargs) def get_number_of_likes(self): return self.like_set.count() def get_number_of_comments(self): return self.comment_set.count() could you help me how to work it? -
Customizing BoundField django 1.10 documentation
I've just been reading django documentation in customizing BoundField, it said that we have to override "get_bound_field()", can someone explain how it works some example maybe, where i have to put those subclass (BoundField and Field) is it in my forms.py...? thank you for the explanation -
Django model choices using other models
Schedule is my model that holds all my events in one place (Meetings, vacation, birthdays, etc) but i also want each of these events to be models so that they can be viewed in their own space. How would i put the events as choices so that when I add a specific event to my schedule, in this case - a reminder, it adds the reminder to my schedule AND reminders but not to vacation or birthdays. This is what i have so far, I believe I would put the individual events into SCHED_CHOICES but i do not know how I would call the models inside of this to make it update and save the event to the specific model and not only the schedule model. class Schedule(models.Model): SCHED_CHOICES = ( ) user = models.ForeignKey(User) time = models.DateTimeField() -
Get Celery logs in the same place as 'normal' Django logs and formatted by a Django formatter
I try to find a way to gather the logs generatd from inside async functions called through Celery, inside the same handler that I use to log 'non-celery' django functions. I have created a dummy function send a log each 3 seconds: from celery.decorators import periodic_task from datetime import timedelta @periodic_task(run_every=timedelta(seconds=3)) def every_3_seconds(): logr.debug("Hello world: Running (debug) periodic task!") logr.info("Hello world: Running (info) periodic task!") I have tried also something like this: clogger = get_task_logger(__name__) # Celery logger @periodic_task(run_every=timedelta(seconds=3)) def every_3_seconds(): clogger.debug("HelloCelery: Running (debug) periodic task!") clogger.info("HelloCelery: Running (info) periodic task!") The log settings are (commented are my previous attempts): CELERYD_HIJACK_ROOT_LOGGER = False LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'handlers': { 'console': { 'class': 'logging.StreamHandler', 'formatter': 'verbose', }, }, 'formatters': { 'verbose': { 'format': 'HOPLA123 %(levelname)s %(asctime)s %(module)s %(process)d %(thread)d %(message)s' } }, 'loggers': { '': { 'handlers': ['console'], 'level': os.getenv('DJANGO_LOG_LEVEL', 'DEBUG'), }, # 'django': { # 'handlers': ['console'], # 'level': os.getenv('DJANGO_LOG_LEVEL', 'DEBUG'), # }, # # Logger for the myappApp # # Use: logr = logging.getLogger(__name__) in myappApp # # logr.debug("....") # 'myappApp': { # 'handlers': ['console'], # 'level': os.getenv('DJANGO_LOG_LEVEL', 'DEBUG'), # 'propagate': False, # To fix duplicate log issue. # }, # # Default Python Logger # … -
Mocking time issue in django test: time seems not to be frozen using freezegun
I'm writing here a functional test to check if my API throttling is working as expected (will be rest at the beginning of every month). Testing Class: class ApiThrottlingTest(ThrottlingBaseTest): def test_throttling_purchaser_case(self): now = datetime.datetime(year=2015, month=1, day=10, hour=6, minute=6, second=3) last_day_of_current_month = datetime.datetime(year=2015, month=1, day=31, hour=23, minute=59, second=59) first_day_of_next_month = datetime.datetime(year=2015, month=2, day=1, hour=0, minute=0, second=0) with freeze_time(now) as frozen_datetime: for i in xrange(3): resp = self._project_details_request() self.assertEqual(resp.status_code, 200) resp = self._project_details_request() self.assertEqual(resp.status_code, 429) frozen_datetime.move_to(last_day_of_current_month) resp = self._project_details_request() # the test fails at this level self.assertEqual(resp.status_code, 429) frozen_datetime.move_to(first_day_of_next_month) resp = self._project_details_request() self.assertEqual(resp.status_code, 200) The test works fine if: last_day_of_current_month = datetime.datetime(... second=0) but will fail if: last_day_of_current_month = datetime.datetime(... second=59) After debugging it seems like the time module used in DjangoRestFramework throttling.UserRateThrottle is in somehow giving a value that's always ahead of the fronzen time in my test, which is causing a precision issue of some seconds. Based on FreezeGun Doc: Once the decorator or context manager have been invoked, all calls to datetime.datetime.now(), datetime.datetime.utcnow(), datetime.date.today(), time.time(), time.localtime(), time.gmtime(), and time.strftime() will return the time that has been frozen. But it looks like im my case time.time takes correctly the start time of the mocked datetime but then keep changing over … -
Variables (fields?) Won't Display in Django Generic Detail View
I have been loosely following a tutorial and can't seam to get a generic detail view to work properly. I am calling with a pk and the page displays but the variable {{publisher.name}} doesn't show up. I have deleted some of the code from views and the model which I consider peripheral but if there error isnt obvious I can repost. All files are in the poll directory except the HTML file is in poll/template/poll Thanks The URL.py is from django.conf.urls import url from poll.views import PublisherList from . import views app_name = "poll" urlpatterns = [ url(r'^publishers/$', PublisherList.as_view(), name = "publisherlist"), url(r'^start/', views.PublisherCreate.as_view(), name = 'make-publisher'), url(r'^(?P<pk>[0-9]+)/$', views.PublisherDetail.as_view(), name = 'detail-publisher'), ] The View.py from django.shortcuts import render from django.views.generic.edit import CreateView from django.views import generic from django.views.generic import ListView from poll.models import Publisher ... class PublisherDetail(generic.DetailView): model = Publisher template_name = 'Poll/publisher_details.html' and the HTML file {% extends "personal/header.html" %} {% block content %} <h1>{{ Publisher.name }}</h1> <h1>Options</h1> {%endblock%} and the models.py from django.db import models from django.core.urlresolvers import reverse # Create your models here. class Publisher(models.Model): name = models.CharField(max_length=30) address = models.CharField(max_length=50) city = models.CharField(max_length=60) state_province = models.CharField(max_length=30) country = models.CharField(max_length=50) website = models.URLField() class Meta: ordering … -
Django rest framework browsable api with pre-filled post forms
I need to redefine json objects each time I make post requests using django rest framework browsable api. is there any configuration to enable pre-filled forms ? -
Transactional type writes in memcached
I'm setting three variables in memcache in my Django app like so: cache.set('list_of_dictionaries',list_of_dictionaries) cache.set('link_ids',link_ids) cache.set('photo_ids',photo_ids) These are conceptually different, yet produced and consumed together. Is there any way to roll those three separate set calls into a single, atomic transaction? For instance, in redis, I'd have used a pipeline. -
How to use search with Elasticsearch
I using python 2.7.11 and djnago 1.10.2. I created product models and saved 1000 products in my database.(postgrelsql) Actually, I used Django elasticsearch but its not working. its search only base on product name, i required if search category, colour, etc. Then show releated product. I tryed example. from haystack import indexes from product.models import Product class ProductIndex(indexes.SearchIndex, indexes.Indexable): text = indexes.CharField(document=True, use_template=True) product_name = indexes.CharField(model_attr='product_name') product_colour = indexes.CharField(model_attr='product_colour') def get_model(self): return Product def index_queryset(self, using=None): return self.get_model().objects.all() I created ProductColour models and used product_colour foreignkey in product moedls. If i search product_colour then display all releated data. -
Django : Foreign Key column from formulary not working
I'm working with Django 1.10.5 and I get an error that I am not finding a solution. I have a models file from my first app : Identity models.py #-*- coding: utf-8 -*- class Identity(models.Model): title = models.CharField(max_length=12,choices=TITLE_CHOICES, verbose_name='Civilité') lastname = models.CharField(max_length=30, verbose_name='Nom de famille') firstname = models.CharField(max_length=30, verbose_name='Prénom(s)') sex = models.CharField(max_length=8, choices=SEX_CHOICES, verbose_name='Sexe') birthday = models.DateField(verbose_name='Date de naissance') birthcity = models.CharField(max_length=30, verbose_name='Ville de naissance') birthcountry = CountryField(blank_label='Sélectionner un pays', verbose_name='Pays de naissance') nationality = models.CharField(max_length=30, verbose_name='Nationalité') job = models.CharField(max_length=30, verbose_name='Profession') adress = models.CharField(max_length=30, verbose_name='Adresse') city = models.CharField(max_length=30, verbose_name='Ville') zip = models.IntegerField(verbose_name='Code Postal') country = CountryField(blank_label='Sélectionner un pays', verbose_name='Pays') mail = models.CharField(max_length=30, verbose_name='Email', blank=True) phone = models.CharField(max_length=20, verbose_name='Téléphone', blank=True) def __unicode__(self): return '%s %s %s %s %s %s %s %s %s %s %s %s %s %s %s %s' % (self.id, self.title, self.lastname, self.firstname, self.sex, self.birthday, self.birthcity, self.birthcountry, self.nationality, self.job, self.adress, self.city, self.zip, self.country, self.mail, self.phone) Then I have another models from my second app : BirthCertificate models.py which takes two Foreign Keys from Identity models : #-*- coding: utf-8 -*- class BirthCertificate(models.Model): lastname = models.CharField(max_length=30, null=False, verbose_name='Nom de famille') firstname = models.CharField(max_length=30, null=False, verbose_name='Prénom(s)') sex = models.CharField(max_length=8, choices=SEX_CHOICES, verbose_name='Sexe') birthday = models.DateField(null=False, verbose_name='Date de naissance') birthhour = models.TimeField(null=True, verbose_name='Heure de … -
Wagtail ModelAdmin > how to set initial data for an InlinePanel?
I have created a Planning and a Meeting model. I use Wagtail's ModelAdmin to administer them. Planning has a planning_panels which is an InlinePanel. For other models I can set initial data using the form's __init__ method. But I can't figure out how to implement this for the formsets used by the InlinePanel. Does anyone have any ideas? Here is the code: class Planning(ClusterableModel): base_form_class = PlanningForm planning_panels = [ InlinePanel( 'planning_meetings', min_num = 2, max_num = 8, label = 'meetings' ) ) edit_handler = TabbedInterface([ ObjectList(planning_panels, heading=_('meetings')), ]) class PlanningMeeting(models.Model): planning = ParentalKey( 'cms.Planning', related_name='planning_meetings', ) start = models.DateTimeField( 'start' ) finish = models.DateTimeField( 'finish' ) panels = [ FieldPanel('start'), FieldPanel('finish') ] class Meta: verbose_name = 'Planned meeting' class PlanningForm(WagtailAdminModelForm): class Meta: fields = '__all__' def __init__(self, *args, **kwargs): instance = kwargs.get('instance') if not instance or not instance.pk: initial = kwargs.get('initial', {}) initial.update({ 'some_fiel': 'some_value' }) kwargs['initial'] = initial super().__init__(*args, **kwargs) class CreatePlanningView(CreateView): pass class PlanningAdmin(ModelAdmin): model = Planning create_view_class = CreatePlanningView -
Use pip python-django instead apt
I have installed python-django in a ubuntu 14.04, unfortunately I need to use exactly that distribution, but it is unsupported now, to update django I used the pip, how do I use the newer version instead of the apt version? -
Gunicorn & django: connect() to unix:/home/ubuntu/webapps/kenyabuzz/kb.sock failed (2: No such file or directory) while connecting to upstream
Setting up a django site with gunicorn & nginx I can run it with gunicorn --bind 0.0.0.0:8000 myproject.wsgi:application however gunicorn instance with nginx fails with an error can't connect to sock file (and doesn't create it also). The error log is: 2017/02/01 11:43:47 [crit] 30225#30225: *9 connect() to unix:/home/ubuntu/webapps/kenyabuzz/kb.sock failed (2: No such file or directory) while connecting to upstream, client: 197.232.12.165, server: kenyabuzz.nation.news, request: "GET / HTTP/1.1", upstream: "http://unix:/home/ubuntu/webapps/kenyabuzz/kb.sock:/", host: "kenyabuzz.nation.news" 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 -
How to assign id attribute to BooleanField in ModelForm for jsonresponse
I have a ModelForm where I have assigned ids to widgets which are used in a jsonresponse to save without a page refresh. I have recently changed a field to a Boolean Field because I just want a checkbox on the form to assign True, and the default is set to False. How do i assign an id to the Boolean field? class PersonForm(forms.ModelForm): make_person_coach = forms.BooleanField() class Meta: model = Person fields = [ 'id', 'first_name', 'surname', 'email', 'make_person_coach', 'position', 'contract_type', 'mentor'] labels = { 'first_name': _('First Name'), 'surname': _('Surname'), 'email': _('Email'), 'coach_id': _('Select Coach'), 'make_person_coach': _('Make person a coach?'), 'position': _('Position'), 'contract_type': _('Contract Type'), 'mentor': _('Mentor'), } widgets = { 'first_name': forms.TextInput( attrs={'placeholder': 'First Name', 'id': 'person-first-name'} ), 'surname': forms.TextInput( attrs={'placeholder': 'Surname', 'id': 'person-surname'} ), 'email': forms.TextInput( attrs={'placeholder': 'Email Address', 'id': 'person-email'} ), 'position': forms.TextInput( attrs={'placeholder': 'Current position', 'id': 'person-position'} ), 'contract_type': forms.Select( attrs={'placeholder': 'Select Contract Type', 'id': 'person-contract'} ), 'mentor': forms.Select( attrs={'placeholder': 'Coach name', 'id': 'person-mentor'} ), } def __init__(self, *args, **kwargs): super(PersonForm, self).__init__(*args, **kwargs) all_coaches = Person.objects.filter(make_person_coach="Person is a coach") all_people = Person.objects.all() self.fields['mentor'].empty_label = "Select Coach" self.fields['mentor'].queryset = Person.objects.filter(make_person_coach=True) Here is where I get the data: function create_person() { console.log("create person is working!") $.ajax({ url … -
Django choice field default value and readonly
I try to set my field in form readonly and put any default value. This is a part of my form: category = forms.CharField(widget=forms.TextInput(attrs={'readonly': 'readonly'}), initial=Category.objects.get(name='Fitness')) class Meta: model = Site fields = ('url', 'name', 'description', 'keywords', 'group', 'category', 'subcategory', 'category1', 'subcategory1') I get an error: Cannot assign "'Fitness'": "Site.category" must be a "Category" instance. This is my site model: class Site(models.Model): category = models.ForeignKey('Category') subcategory = ChainedForeignKey( 'SubCategory', chained_field='category', chained_model_field='category', show_all=False, auto_choose=True) name = models.CharField(max_length=70) description = models.TextField() # importuje zmienione TextFields widgets.py keywords = MyTextField() date = models.DateTimeField(default=datetime.now, editable=False) url = models.URLField() is_active = models.BooleanField(default=False) category1 = models.ForeignKey('Category', related_name='category', blank=True, null=True, default=None) subcategory1 = ChainedForeignKey( 'SubCategory', chained_field='category1', chained_model_field='category', related_name='subcategory', show_all=False, auto_choose=True, blank=True, null=True, default=None) group = models.CharField(max_length=10, choices=(('podstawowy', 'podstawowy'), ('premium', 'premium')), default='podstawowy') def get_absolute_url(self): return reverse('site', args=[str(self.category.slug), str(self.subcategory.slug), str(self.id)]) def get_thumb(self): host = urlparse(self.url).hostname if host.startswith('www.'): host = host[4:] thumb = 'http://free4.pagepeeker.com/v2/thumbs.php?size=s&url=' + host return thumb class Meta: verbose_name_plural = "Strony" def __str__(self): return self.name I can't deal with it. Any clues?