Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
WSGI Django 403 Forbidden
When I run sudo service apache2 restart I get an error unable to resolve host hostname When I look at the error.txt it says it's my WSGI configuration. Here is my WSGI script. import os import sys from django.core.handlers.wsgi import WSGIHandler import django os.environ['DJANGO_SETTINGS_MODULE'] = 'app.settings' sys.executable = '/usr/lib/python2.7/dist-packages' application = WSGIHandler() django.setup() -
get_absolute_url and reverse outside of templates
"...If you need to use something similar to the url template tag in your code, Django provides the following function: reverse()...." I looked at the docs for get_absolute_url() and reverse, as well as the example given: a href="{{ object.get_absolute_url }}">{{ object.name }} /a> What I am not seeing, or understanding, is how are we passing the kwargs (name, self, ID, whatever) to the model method so it knows which one of 100 instances to return the url for, particularly where I need to use it in text, outside the template system? a href="name_of_object.get_absolute_url ">text name of object Do I have to put the full name of the object in the href? How would I use a variable like self or object or modelname instead? Can I rewrite gau to take kwargs as well as self? If I do that, can I put the () on the end of gau to take in the kwargs? We can’t do that in the template. Can I use: a href="self.get_absolute_url(**kwargs) ">text name of object ? or a href="object.get_absolute_url(self, **kwargs) ">text name of object ? And if so, do I need to add anything to the definition of gau on my model to make sure … -
Django - Tag inside a Templete tag
So I'm using the django-jcrop plugin to crop an image. Inside my HTML file I have this line: <img src="{% cropped_thumbnail order 'cropping' max_size='{{ ratio }}' %}"> When this is passed, I get the following error: TemplateSyntaxError: max_size must match INTxINT {{ ratio }} is passed correctly outside of the tag, and gives the correct intended value, 400x400. When I remove the single quotes from the max_size='{{ ratio }}' I then get the following error: TemplateSyntaxError: Could not parse the remainder: '{{' from '{{' So I am pretty sure ratio is not parsing correctly within the tag. Any ideas why? -
Django - download file without reloading the page
The flow looks like that: 1. user is filling the form 2. form is passed to the server by ajax 3. form is saved to db, then the pdf with the form data is created and saved in the app folder (probably a bad move here...) ajax success causes the page to append a button 'Download' with value equal to current pdf's name so button 'Download' appears to the user If user presses the button the very pdf that was just saved is gonna download. Refreshing the page makes the button disappear. I've got stuck on point 5. I have created another ajax (to avoid reloading the page) bound to the Download button. It correctly asks the server to look for the file, creates a django File object: pdf_file = File(open(file_path, 'rb')) and creates a HttpResponse with file, and content_type='application/pdf' or 'application/download'. response['Content-Disposition'] is 'attachment'. Then the ajax returns response - only it does not. Server raises no error but ajax error function is called. I've read that downloading with ajax is not possible. Could you help me a bit to get it straight? If above snippets are not clear, I shall provide more code. Python 3.5, Django 1.10 -
How to run django application on google app engine without using gunicorn
I have gone through all the documentation provided for the running Django Application on app engine. I have a Django Application where I am using Vision and Storage clients and my app name is pvd. I have been constantly getting below errors in error logs. A [2017-03-30 22:08:07 +0000] [1] [CRITICAL] WORKER TIMEOUT (pid:7) A [2017-03-30 22:08:07 +0000] [7] [INFO] Worker exiting (pid: 7) A [2017-03-30 22:08:07 +0000] [9] [INFO] Booting worker with pid: 9 A [2017-03-30 22:12:35 +0000] [1] [CRITICAL] WORKER TIMEOUT (pid:9) A [2017-03-30 22:12:35 +0000] [9] [INFO] Worker exiting (pid: 9) A [2017-03-30 22:12:36 +0000] [11] [INFO] Booting worker with pid: 11 A [2017-03-30 22:13:03 +0000] [1] [INFO] Handling signal: term A [2017-03-30 22:13:03 +0000] [7] [INFO] Worker exiting (pid: 7) A [2017-03-30 22:13:03 +0000] [1] [INFO] Shutting down: Master* Below is my app.yaml runtime: python env: flex entrypoint: gunicorn -b :$PORT pythonvision.wsgi runtime_config: python_version: 3 Below is my requirement.txt Django==1.10.6 google-cloud-storage==0.23.1 google-cloud-vision==0.23.1 gunicorn==19.7.0 For deploying I am using: gcloud app deploy What am I doing wrong? -
Django Smart Selects with Many to Many chained in other Many to Many field
state = models.ManyToManyField(State, verbose_name=_('State'),) city = ChainedManyToManyField( City, verbose_name=_('City'), chained_field="state", chained_model_field="states", ) Is that possible ? I've tried and it's doesn't working. Ideas? -
How to simulate a django form submission with a button click on a different page?
I am running in a situation where I want to simulate a form behaviour when a button is clicked on a different page. For example by default a url '/add_user/' has a form where a user provides his name, email address, etc. When he clicks submit button on this form it creates an entry in database using django's form.save() method. Which essentially is depended on modelform functionality. Now I have added a new url called '/subscribe/' where one can subscribe to a newsletter of his interest. I want to add all the name, email etc details from subscribe form and save it to database table which add_user link accesses. I am aware that I can invoke a sql statement on a button click or using python library I can get the same result, however, I am wondering if there is any other way to simulate this because I want to keep my code decoupled from underlying database. In other words if in future if someone changes the database I don't want this code to fail. Can you advise on how to do this? Thanks. Have a great day. -
What is the proper way to have a django 1.10 API serve static HTML content in DEBUG?
I am attempting to build a simple single-page web app where a web server just serves static content, unless a route begins with "/api" - in which case requests are routed to django. File structure like so: ROOT - manage.py - static/ (static content) - index.html - app.min.js - ...etc - djangoapp/ (django "project") - __init__.py - settings.py - urls.py - wsgi.py - api/ (django "app") - __init__.py - admin.py - apps.py - models.py - tests.py - views.py In development (DEBUG=true), I would like django to serve the static content as a traditional web server would. That means content not under /api should just be served from /static, and a GET for '/' should return index.html. I have taken these steps: created the root django "project" with django-admin createproject djangoapp created a django "app" with ./manage.py createapp api created a folder, static, with a dummy index.html and dummy.html. altered the django "app" to create a simple "hello I am the api" endpoint, at /api/hello, and created the appropriate routes From this point, I can successfully set up a docker-compose cluster to perform as expected - calls to the nginx edge for '/' load the static index.html in ROOT/static/index.html, calls to … -
Internal Server Error Django/apache
My Django app was working fine, but now I'm getting a server error, the last thing I did was a reboot to my Centos7 Server and now I'm getting this error: and this are my logs I'm using apache: [Thu Mar 30 14:04:10.571843 2017] [:error] [pid 11335] [remote 10.221.50.100:24] mod_wsgi (pid=11335): Target WSGI script '/opt/btsystem/BTSystem/wsgi.py' cannot be loaded as Python module. [Thu Mar 30 14:04:10.571991 2017] [:error] [pid 11335] [remote 10.221.50.100:24] mod_wsgi (pid=11335): Exception occurred processing WSGI script '/opt/btsystem/BTSystem/wsgi.py'. [Thu Mar 30 14:04:10.572263 2017] [:error] [pid 11335] [remote 10.221.50.100:24] Traceback (most recent call last): [Thu Mar 30 14:04:10.572544 2017] [:error] [pid 11335] [remote 10.221.50.100:24] File "/opt/btsystem/BTSystem/wsgi.py", line 16, in <module> [Thu Mar 30 14:04:10.572795 2017] [:error] [pid 11335] [remote 10.221.50.100:24] application = get_wsgi_application() [Thu Mar 30 14:04:10.572919 2017] [:error] [pid 11335] [remote 10.221.50.100:24] File "/usr/lib64/python2.7/site-packages/django/core/wsgi.py", line 13, in get_wsgi_application [Thu Mar 30 14:04:10.573054 2017] [:error] [pid 11335] [remote 10.221.50.100:24] django.setup(set_prefix=False) [Thu Mar 30 14:04:10.573107 2017] [:error] [pid 11335] [remote 10.221.50.100:24] File "/usr/lib64/python2.7/site-packages/django/__init__.py", line 22, in setup [Thu Mar 30 14:04:10.573170 2017] [:error] [pid 11335] [remote 10.221.50.100:24] configure_logging(settings.LOGGING_CONFIG, settings.LOGGING) [Thu Mar 30 14:04:10.573261 2017] [:error] [pid 11335] [remote 10.221.50.100:24] File "/usr/lib64/python2.7/site-packages/django/utils/log.py", line 75, in configure_logging [Thu Mar 30 14:04:10.573312 2017] [:error] … -
Why aren't new objects added to django model not using the framework not recognized by modelform when trying to load form by id?
I am using a legacy database in my django app, and have created a model from one of the tables as well as a modelform to make edits. The table itself is also modified by other applications, and I notice after new records are added not using the django or the modelform, when I then load the modelform and try to load the new objects, they are not recognized. Why is this? I made migrations to the app, and am wondering what else I need to do so that my app will see those records? -
Django object not saving all iterations of a recursive save method
I have a recursive save method in my Django project to create multiple instances of calendar events; the problem is only the last event actually seems to get saved. I'm either missing something obvious, or there's an obscure bit of Django wizardy I'm not familiar with. ETA: As an example, if I have an event on the first Friday of a month for three months, only the third month will actually save to the database. Save method is below: def save(self, *args, **kwargs): if not self.orig_title: self.orig_title = self.title if self.end_date is None: self.end_date = self.start_date tempSlug = slugify("%s %s %s" % (self.orig_title, self.start_date.strftime("%b %d %Y"), self.branch)) self.slug = tempSlug if not self.pk: self.is_repeating = repeating_event_check(self) super(MonthlyRepeatingEvent, self).save(*args,**kwargs) if self.number_of_repetitions > 1: temp_start_date = move_to_next_month(self.start_date) temp_end_date = move_to_next_month(self.end_date) next_repetition = self next_repetition.pk = None next_repetition.end_date = temp_end_date next_repetition.start_date = temp_start_date next_repetition.number_of_repetitions = self.number_of_repetitions - 1 while not date_checker(next_repetition.start_date,next_repetition.day_of_week,next_repetition.week_of_month): next_repetition.start_date = next_repetition.start_date.replace(tzinfo=None) + datetime.timedelta(days=1) while not date_checker(next_repetition.end_date,next_repetition.day_of_week,next_repetition.week_of_month): next_repetition.end_date = next_repetition.end_date.replace(tzinfo=None) + datetime.timedelta(days=1) next_slug = slugify("%s %s %s" % (next_repetition.orig_title, next_repetition.start_date.strftime("%b %d %Y"), next_repetition.branch)) try: next = MonthlyRepeatingEvent.objects.get(slug=next_slug) next_repetition.pk = next.pk next.delete() next_repetition.save() except: next_repetition.slug = next_slug next_repetition.save() else: super(MonthlyRepeatingEvent, self).save(*args,**kwargs) if self.number_of_repetitions > 1: temp_start_date = move_to_next_month(self.start_date) temp_end_date = move_to_next_month(self.end_date) next_repetition … -
django, accessing meta properties outside of the page that generates them
So basically, I'm using the PersistentRemoteUser middelware in django to handle authentication requests through a login page that is monitored by apache using pubcookie I can do the basic user.is_authenticated bit's fine, but my problem comes from the fact that I have 2 types of users that require two different kinds of authentication. I have my admin users that require authenticating with 2 factor authentication, and standard users that use only user/password, The authentication type can easily be viewed on the login page itself by accessing: self.request.META['AUTH_TYPE'] which will read as either "SecureID" or "NetID" depending on theauthtype`. But I need to be able to perform a check on different pages to see if the user authenticated with secureid or netid to determine what parts of a page are viewable, or if they are allowed to see the page at all. But the meta data does not exist outside of the initial login page, only the request.user data, which does not, unless i'm missing something, contain any type of auth_type. is it possible to either access the metadata from another page, or save the users authtype to some kind of post or session variable that gets carried around for the … -
APACHE-DJANGO-WSGI Deployment
I have a django app located at /home/user/myapp I'm trying to run the app with apache2 and WSGI. Currently, the apache2 configuration is at /etc/apache2/apache2.conf and has this directory relating to my webiste <VirtualHost website.com:80> ServerName website.com ServerAlias www.website.com ServerAdmin email@website.com DocumentRoot /home/user/myapp/static WSGIScriptAlias / /var/www/website-directory/django.wsgi <Directory /home/user/myapp/static> Order allow,deny Allow from all </Directory> Alias /robots.txt /var/www/webisite-directory/robots.txt Alias /favicon.ico /var/www/webisite-directory/favicon.ico Alias /images /home/user/myapp/images Alias /static /home/user/myapp/static ErrorLog /var/www/webisite-directory/error.log CustomLog /var/www/webisite-directory/access.log combined </VirtualHost> My django.wsgi is import os import sys sys.path.append('/home/user/myapp') os.environ['DJANGO_SETTINGS_MODULE'] = '/myapp_directory/settings' sys.executable = '/usr/lib/python2.7/dist-packages' import django.core.handlers.wsgi application = django.core.handlers.wsgi.WSGIHandler() Here is my error log user@ubuntu:/var/www/website-directory$ vim error.log [Thu Mar 30 01:25:10.060478 2017] [wsgi:error] [pid 7235:tid 139856399259392] [client 98.16.70.181:51796] self.load_middleware(), referer: http://www.mywebsite [Thu Mar 30 01:25:10.060490 2017] [wsgi:error] [pid 7235:tid 139856399259392] [client 98.16.70.181:51796] File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py", line 48, in load_middleware, referer: http://www.mywebsite [Thu Mar 30 01:25:10.060509 2017] [wsgi:error] [pid 7235:tid 139856399259392] [client 98.16.70.181:51796] if settings.MIDDLEWARE is None:, referer: http://www.mywebsite [Thu Mar 30 01:25:10.060521 2017] [wsgi:error] [pid 7235:tid 139856399259392] [client 98.16.70.181:51796] File "/usr/local/lib/python2.7/dist-packages/django/conf/__init__.py", line 53, in __getattr__, referer: http://www.mywebsite [Thu Mar 30 01:25:10.060558 2017] [wsgi:error] [pid 7235:tid 139856399259392] [client 98.16.70.181:51796] self._setup(name), referer: http://www.mywebsite [Thu Mar 30 01:25:10.060570 2017] [wsgi:error] [pid 7235:tid 139856399259392] [client 98.16.70.181:51796] File "/usr/local/lib/python2.7/dist-packages/django/conf/__init__.py", line 41, in _setup, referer: … -
Django - Return none object if record not found given the queried list
I've a list of ids [1,2,3,4,5,6,7,8,9,10] Now I want to query a model with the above list of ids. This is how I perform the operation. ModelA.objects.filter(id__in=ids) This returns objects of ModelA which match the given id list. Now consider ids [2,3,5] were not present. Can I get a queryset of same length as that of the input list, including all the non-found objects as well.?? For eg:- if [2,3,5] are not found, it should return [1,None,None,4,None,6,7,8,9,10] How can I achieve it? -
Django object filter not recognizing related name
This console log demonstrates the problem. The 'Positions' related field is not recognized. x = Person.objects.get(PersonSk=452) x.Positions <django.db.models.fields.related.RelatedManager object at 0x0000000005B4A358> x.Associations <django.db.models.fields.related.RelatedManager object at 0x0000000005AEDC18> Person.objects.filter(Associations__isnull=True) [lots of peeps] Person.objects.filter(Positions__isnull=True) raise_field_error "Choices are: %s" % (name, ", ".join(available))) FieldError: Cannot resolve keyword 'Positions' into field. Here are the model classes for Person, PersonAssociation, and Position. Why does it work for PersonAssociation but not Position? class Person(models.Model): class Meta: managed = False db_table = 'PERSON].[Person' ordering = ('LastName', 'FirstName') PersonSk = models.AutoField(primary_key=True, editable=False) FirstName = CharNullField('First Name', max_length=30, blank=True) LastName = CharNullField('Last Name', max_length=30, blank=True) Email = CharNullField(max_length=50, blank=True) PhoneWork = CharNullField('Work Phone', max_length=20, blank=True) PhoneMobile = CharNullField('Mobile Phone', max_length=20, blank=True) class PersonAssociation(models.Model): class Meta: managed = False db_table ='CLIENT].[PersonAssociation' PersonAssociationSk = models.AutoField(primary_key=True, editable=False) Client = models.ForeignKey(Client, db_column='ClientCode', related_name='Associations') Person = models.ForeignKey(Person, db_column='PersonSk', related_name='Associations') class Position(models.Model): class Meta: managed = False db_table = 'PERSON].[Position' PositionSk = models.AutoField(primary_key=True, editable=False) Person = models.ForeignKey(Person, db_column='PersonSk', related_name='Positions') ConsumerClient = models.ForeignKey(Client, db_column='ClientCode', related_name='Positions') ProviderClient = models.ForeignKey(Client, db_column='ProviderClientCode', related_name='ProviderPositions', blank=True, null=True) Role = models.ForeignKey(ContactRole, db_column='ContactRoleSk', related_name='Positions') Facility = models.ForeignKey(Facility, db_column='FacilitySk', blank=True, null=True) Notes = models.TextField(blank=True, null=True) StartDate = models.DateField() EndDate = models.DateField(blank=True, null=True) As far as I can tell, the related_name field is setup in the … -
ManifestStaticFilesStorage Internal Server Error
I'm trying to get static file versioning/caching up and running on my Wagtail site by way of ManifestStaticFilesStorage. When I upload to my stage server I get an Internal Server Error. Any idea what may be happening? My base.py is my base settings, and stage.py is my stage settings. The traceback is included below as well. base.py PROJECT_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) BASE_DIR = os.path.dirname(PROJECT_DIR) STATICFILES_FINDERS = [ 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', ] STATICFILES_DIRS = [ os.path.join(PROJECT_DIR, 'static'), ] STATICFILES_STORAGE = 'django.contrib.staticfiles.storage.StaticFilesStorage' STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATIC_URL = '/static/' stage.py DEBUG = False STATICFILES_STORAGE = 'django.contrib.staticfiles.storage.ManifestStaticFilesStorage' Traceback: File “/data/virtualenv/sitename/lib/python2.7/site-packages/django/core/handlers/exception.py” in get_exception_response 98. response = callback(request, **dict(param_dict, exception=exception)) File “/data/virtualenv/sitename/lib/python2.7/site-packages/newrelic-2.70.0.51/newrelic/hooks/framework_django.py” in wrapper 503. return wrapped(*args, **kwargs) File “/data/virtualenv/sitename/lib/python2.7/site-packages/django/utils/decorators.py” in _wrapped_view 149. response = view_func(request, *args, **kwargs) File “/data/virtualenv/sitename/lib/python2.7/site-packages/django/views/defaults.py” in page_not_found 45. body = template.render(context, request) File “/data/virtualenv/sitename/lib/python2.7/site-packages/django/template/backends/django.py” in render 66. return self.template.render(context) File “/data/virtualenv/sitename/lib/python2.7/site-packages/django/template/base.py” in render 208. return self._render(context) File “/data/virtualenv/sitename/lib/python2.7/site-packages/newrelic-2.70.0.51/newrelic/api/function_trace.py” in dynamic_wrapper 98. return wrapped(*args, **kwargs) File “/data/virtualenv/sitename/lib/python2.7/site-packages/django/template/base.py” in _render 199. return self.nodelist.render(context) File “/data/virtualenv/sitename/lib/python2.7/site-packages/django/template/base.py” in render 994. bit = node.render_annotated(context) File “/data/virtualenv/sitename/lib/python2.7/site-packages/django/template/base.py” in render_annotated 961. return self.render(context) File “/data/virtualenv/sitename/lib/python2.7/site-packages/django/template/loader_tags.py” in render 174. return compiled_parent._render(context) File “/data/virtualenv/sitename/lib/python2.7/site-packages/newrelic-2.70.0.51/newrelic/api/function_trace.py” in dynamic_wrapper 98. return wrapped(*args, **kwargs) File “/data/virtualenv/sitename/lib/python2.7/site-packages/django/template/base.py” in _render 199. return self.nodelist.render(context) File “/data/virtualenv/sitename/lib/python2.7/site-packages/django/template/base.py” in render … -
Django tenant schemas and PostgreSQL database replication
I have an application that uses django-tenant-schemas to manage muli-tenancy. While trying to apply database replication I had a problem that when we're running the migrations, the migrations would access the replica. Which caused an exception since the schema is not set on the replica connection. I found an old issue on the project that's supposed to address this problem. He simply created a database wrapper to set the schema on all connections class DatabaseWrapper(TenantSchemasDatabaseWrapper): def __init__(self, *args, **kwargs): TenantSchemasDatabaseWrapper.__base__.__init__(self, *args, **kwargs) self.set_schema_to_public(spread=False) def set_tenant(self, tenant, include_public=True, spread=True): super(DatabaseWrapper, self).set_tenant(tenant, include_public) if spread: for conn in _iter_tenant_connections(exclude=(self,)): conn.set_tenant(tenant, include_public, spread=False) def set_schema(self, schema_name, include_public=True, spread=True): super(DatabaseWrapper, self).set_schema(schema_name, include_public) if spread: for conn in _iter_tenant_connections(exclude=(self,)): conn.set_schema(schema_name, schema_name, spread=False) def set_schema_to_public(self, spread=True): super(DatabaseWrapper, self).set_schema_to_public() if spread: for conn in _iter_tenant_connections(exclude=(self,)): conn.set_schema_to_public(spread=False) My router is pretty simple: class PrimaryReplicaRouter(object): def db_for_read(self, model, **hints): """ Reads go to a replica. """ return 'replica' def db_for_write(self, model, **hints): """ Writes always go to primary. """ return 'default' and in the settings.py file I have: DATABASES = { 'default': { 'ENGINE': 'tenant_backend', 'NAME': 'userdb', 'USER': 'master', 'PASSWORD': 'password', 'HOST': 'localhost', 'PORT': 12010, 'ATOMIC_REQUESTS': True }, 'replica': { 'ENGINE': 'tenant_backend', 'NAME': 'userdb', 'USER': 'master', 'PASSWORD': 'password', 'HOST': … -
How to save custom fields to DB in Django registrationform?
ive been struggling with this particular part for days now, and other posts on this problem dont seem to help me out. So I have connected the User model with my own Gebruiker model that has fields like city, postalcode etc. Now I have managed to show them up on the registerform, but they dont seem to work. My second question is about the order of the inputfields, every time they appear in a random order. How can I set up a steady order? This is my forms.py from django import forms from django.contrib.auth.models import User from .models import Gebruiker from django.contrib.auth.forms import UserCreationForm class RegistrationForm(UserCreationForm): woonplaats = forms.CharField(required=True) postcode = forms.CharField(required=True) class Meta: model = User fields = {'username','email', 'password1', 'password2', 'first_name', 'last_name', 'woonplaats', 'postcode'} def save(self, commit=True): user = super(UserCreationForm, self).save(commit=False) user.email = self.cleaned_data['email'] user.first_name = self.cleaned_data['first_name'] user.last_name = self.cleaned_data['last_name'] gebruiker = Gebruiker(user=user, woonplaats=self.cleaned_data['woonplaats'], postcode=self.cleaned_data['postcode']) gebruiker.save() if commit: gebruiker.save() user.save() return user, gebruiker (where woonplaats = place of residence) Here is a part from views.py def register(request): if request.method == 'POST': form = RegistrationForm(request.POST) if form.is_valid(): form.save() return redirect('/aanmelden') else: form = RegistrationForm() args = {'form' : form} return render(request, 'aanmelden/reg_form.html', args) -
Cqlengine: cannot create table
I am trying to use cassandra with cqlengine and django. This is the table that i am trying to create CREATE TABLE dbo.table ( activity_id varint, actor_id int, feed_id ascii, PRIMARY KEY (actor_id, activity_id, feed_id)); IF i do this on cql directly, everything works. However I haven't been able to define a model using cqlengine that will eventually convert to this. This is what I tried class Table(BaseActivityStoreMapTable): actor_id = columns.Integer(partition_key=True) activity_id = columns.VarInt(primary_key=True) feed_id = columns.Ascii(primary_key=True) but this gets converted to CREATE TABLE dbo.tabkle ( activity_id varint, actor_id int, feed_id ascii, PRIMARY KEY ((activity_id, actor_id), feed_id)) I am very confused about this. The documentation lacks these parts mostly. -
Remove trailing data from Django timesince
Is there a way to remove the trailing data from the django timesince filter? I would like to only display days, weeks months or years without any trailing information. e.g weeks + days -> weeks, months + weeks -> months, years + months +years, etc. Additionally, if the date is less than one day, it should display the hours. e.g. 1 hour ago, 4 hours ago, etc. Currently I have a datetime object and am using the filter like this: {{ my_date_time|timesince}} -
Why python datetime replace timezone is returning different timezone?
I am working on Python/Django project. I am trying to let use select date and time using jQuery plugin datetimepicker add-on. So when I select now option and post data django is saving the time in UTC offset. This is what is saved in database, 2017-03-30 13:38:00+00:00. I need to convert this time from user's timezone and save it in system as utc. Because later I will have script running which will look for data in database which is less than the utc time. Actually the script is to let user post information on website and let them chose the publish date and time. So for example, If use posted an article which will be published on April 2nd 1pm Chicago time, I don't want other users to read the article before this time. So people around the world can read article as soon as it is April 2nd and 1PM in Chicago. So how can I make this functionality work? My solution was to get the time and remove it's timezone information using replace(tzinfo=pytz.timezone('America/Chicago')) and when I print the time, I am getting 2017-03-30 13:38:00-05:51. The actual offset right now is -05:00. Can anyone help me to and tell … -
How to properly configure SSL on django/Heroku and talk to the API through swift?
I have tried looking up easy ways of configuring SSL on a django app hosted on Heroku but none of the methods worked for me. I don't know if I am configuring it incorrectly or trying to access it incorrectly. There are many new django developers and iOS developers like me out there and I thought a simple guide would really be helpful for everyone. So, how do we set up SSL in a built django app that is deployed to heroku and once that is done, how do we properly talk to the API using Alamofire and swift on an iOS app? -
Django - Best way to create tables
I am displaying data from my database following a certain pattern. To do so, I'm using a template with {% for %} loop to create the lines / columns of the table. First question: I'm not sure is this is the right way to do this and if there is a more efficient way. Second question: How to sort. I would like to know how I could sort the table. Because of the {% for %} loop building the table, I don't know how to properly sort my table columns by clicking on the headers. I've seen many solutions but none would work with the loop in the table missing things up. Indeed, with things like django-table2, I don't know how if I can incorporate my specific loop (instead of printing the entire table, which I can sort using django-table2 but w/o being capable of adapting both design and information displayed. Below an example of how I'm building things in the template - with a table included in a table: <table> <thead> <tr> <th>Status</th> <th>Some</th> <th>Something</th> <th>Other</th> </tr> </thead> <tbody> {% block content %} {% for x in xx %} <tr> <td> {{ x.status }} </td> <td> {{ x.some}} </td> … -
Query a model through a User model django in template
I have this scenario: class Package(models.Model): title = models.CharField(max_length=200) createdBy = models.ForeignKey(User) class UserProfile(models.Model): website = models.URLField() user = models.OneToOneField(User) In my template, I have the object object, and I can do this: {{ object.createdBy }} Can I do something like {{ object.createdBy.userprofile.website }} in my template? -
Django - MultiSelectField package not working
I'm attempting to display a form that will let users create, read and update a model object. I recently used pip install django-multiselectfield to install a Python package that allows multiple choices to be stored in one db column. In the admin panel, I can select the choice boxes in the form without any problems, but in the view it returns the form with a ValidationError above the field like Value [u"[u'Digital Video'", u" u'Direct Marketing']"] is not a valid choice In addition, when the values are saved in the admin and I use a template tag to render the values in the view then the values are like so... [u'Digital Video'] as opposed to a normal string which I expected to be just 'Digital Video'. Any ideas why this is 1) Preventing the form from being saved inside the view (but works inside the admin) and 2) Why the template renders the value in the way shown above and how this can be rectified? Thanks