Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Using datetime.now() in Django view
The Code I am using datetime.now() as part of a filter in a Django view as follows: #views.py import datetime published_announcements = Announcement.objects.filter(publish_start_date__lte=datetime.datetime.now(), publish_end_date__gte=datetime.datetime.now()).filter(hidden=False, under_review=False).extra(order_by=['-publish_start_date', 'publish_end_date']) then I pass it to the context as such context['announcements'] = published_announcements It works correctly and gets announcements that are supposed to be published and are not hidden or under review according to to the date supplied by datetime.now() The Problem I use datetime.datetime.now() to filter out old announcements but I realised after a day in the production environment that datetime.datetime.now() is being evaluated only when the server starts and the value does not update each time the view is called which results in the wrong data being filtered when the next day comes around. This is also affecting another function which retrieves upcoming birthdays in the next 7 days. Things I Read and Tried I have seen a number of questions about using the callable datetime.now instead of datetime.now() but only in the context of setting default values in the model. I have defined a function as follows thinking it would force datetime.now to be evaluated again but it does not seem to work. def get_now(): return datetime.datetime.now() When I pass the date … -
Error with Python Social Auth and Django 1.10
LookupError at /admin/Admin/ No installed app with label 'Social Nonce'. Request Method: GET Request URL: http://127.0.0.1:8000/admin/Admin/ Django Version: 1.10.2 Exception Type: LookupError Exception Value: No installed app with label 'Social Nonce'. I get the above error message when using Social Auth and Django 1.10. Can you provide hints/clues tell how to resolve. -
Python Django trying to pass variables to Django
Hello guys I have been studying forms in django and all seems to be fine for me until this moment. I have a function to plus numbers with **args, let see: def hello(return, *args): sum(args) .... That's ok, the problem is that I need to get the plus of many numbers and it should be dynamic, if I make a form with only 2 or 3 o 5 text box it suppose to get the totally plus (sum) of those values, I mean the value typed in the textbox. I wonder how can I add a button to dynamicly insert an other text box and that value make calculated by django function? I have been reading about java script to add many text boxes with a button, but I also have been reading that I can not insert those values in django to make calculated. so how can I achieve something like this? I can create a form with 1,2 or 5 textbox and get the plus of those but sometimes I need to type between 10 or 32 values to make a big calculation. The sum function it's just an example the issue here that I need to pass … -
How do I use transaction in ModelViewSet of Django Rest Framework
I update two models in ModelViewSet. How do I use transaction ? I know how to use transaction.atomic in django class based view, but don't know in ModelViewSet(and ViewSet) in DRF. # models class Store(models.Model) name = models.TextField() class Stuff(models.Model) store = models.ForeignKey(Store, related_name='stuffs') first_name = models.TextField() last_name = models.TextField() # serializers class StuffSerializer(serializers.ModelSerializer): class Meta: model = Stuff fields = ('id', 'first_name', 'last_name', ) class StoreSerializer(serializers.ModelSerializer): stuffs = StuffSerializer() def create(self, validated_data): instance = Stoer.objects.create(name=validated_data['name'] for stuff in validated_data['stuffs'] Stuff.objects.create(store=instance, first_name=stuff['first_name'], last_name=stuff['last_name']) return instance def update(self, instance, validated_data): instance.name = validated_data['name'] instance.save() for stuff in validated_data['stuffs'] stuff_instance = Stuff.objects.get(id=stuff['id']) stuff_instance.first_name=stuff['first_name'] stuff_instance.last_name=stuff['last_name'] stuff_instance.save() return instance class Meta: model = Store fields = ('id', 'name', 'stuffs', ) # ModelViewSet class StoreViewSet(viewsets.ModelViewSet): queryset = Store.objects.all() serializer_class = StoreSerializer -
Configuring a Postgresql POSTGIS database
First off, I am new to django. I am trying to use GeoLite(GeoIP2) datasets in my POSTGIS database in django1.10. When I attempt to configure the myapp/settings.py file, i get error messages.There seem to be database backends in different pathes in the django directory;Can you please clarify why? django\contrib\gis\db\backends\postgis django\db\backends After activating my python3 virtual environment, when i try to set the default database in my settings.py file as postgresql('django.db.backends.postgresql'), i get an error: "AttributeError:”Database Operations’ object has no attribute ‘geo_db_type’." When i try to use POSTGIS as my database engine (i set the GDAL_LIBRARY_PATH in my virtual environment), i get an error: "django.contrib.gis.db.backends.postgis' is not an available database backend. Try using 'django.db.backends.XXX', where XXX is one of 'mysql', 'oracle', 'postgresql',and 'sqlite'. Error was: Cannot import name ‘GDALRaster’." Can you suggest possible solutions to the above error messages? Thank you. -
Django abstract model foreignkey to another abstract model
Tag.type should be a Foreignkey to TagType, so should the to parameter be AbstractTagType or TagType? I do not want to write this ForeignKey manually everywhere I use this abstract class. (The class inheriting AbstractTagType will always be named TagType) class AbstractTag(models.Model): type = models.ForeignKey('TagType', models.CASCADE, 'tags') # <--- Line in question tag = models.CharField(max_length=254) class Meta: abstract = True class AbstractTagType(models.Model): type = models.CharField(max_length=254, unique=True) class Meta: abstract = True class Tag(AbstractTag): pass class TagType(AbstractTagType): pass -
psycopg2 control connection IP address
I'm kind of lost here. I have an app on heroku (django) that runs a script with a connection, like this: conn = psycopg2.connect(database="****", host="***", user="***", password="****") The database it connects to has a firewall with a white list filled with IP addresses. The Heroku app continuosly resets the IP address so I can't know which IP psycopg2 will be using, this makes it impossible for me to effectively connect to the db. How can I set a static IP address so that psycopg2 uses that IP all the time and I can add that IP to the firewall's whitelist?. Any advice will help. -
How to open layer editor and django flopyforms integration? OLE (http://ole.geops.de/)
I tried to load utilities from OLE (http://ole.geops.de/) into template django with form: Model: class GeozonaPoligonal(models.Model): nombre = models.CharField(max_length=50, null=False) geom = models.PolygonField(srid=4326) def __unicode__(self): return self.nombre Form: import floppyforms as forms class GMapPolygonWidget(forms.gis.BaseOsmWidget,forms.gis.PolygonWidget): map_width = 900 pass class Media: js = ( '/static/js/OpenLayers.js', '/static/js/OpenStreetMap.js', '/static/js/MapWidget.js', ) class FormGeozonaPoligonal(ModelForm): geom = forms.gis.PolygonField(widget=GMapPolygonWidget, required=False) class Meta: model = GeozonaPoligonal View: @transaction.atomic def editar_geozona_poligonal(request, id=None): obj = GeozonaPoligonal.objects.get(id=id) form = FormGeozonaPoligonal(instance=obj) template = 'editar_geozonas_pol.html' if request.method == 'POST': form = FormGeozonaPoligonal(request.POST, files=request.FILES) if form.is_valid(): form.save() ctx = { 'form': form, } return render_to_response(template, ctx, context_instance=RequestContext(request)) HTML Page: {% extends 'base.html' %} {% load static from staticfiles %} {% block js_top %} <script type="text/javascript" src="/static/js/OpenLayers.js"> </script> <script type="text/javascript" src="/static/js/MapWidget.js"></script> <script type="text/javascript" src="/static/js/loader.js"></script> {% endblock %} {% block css %} <link rel="stylesheet" href="/static/css/geosilk.css" type="text/css"/> {% endblock %} {% block content %} <head> {{ form.media }} </head> <form method="post" action="."> {% csrf_token %} <div class="row"> <div class="col-sm-12 form-horizontal"> <div class="form-group"> <label for="{{ form.geom.id }}" class="col-sm-2 control-label">{{ form.geom.label }}</label> <div class="col-sm-10"> {{ form.geom.errors }} {{ form.geom }} </div> </div> </div> </div> <div class="form-group"> <div class="pull"> <input type="submit" value="Guardar" class="btn btn-success"> </div> </div> </form> {% endblock %} {% block js_bottom %} <script type="text/javascript" src="/static/js/OpenLayers.js"></script> <script type="text/javascript" src="http://www.openstreetmap.org/openlayers/OpenStreetMap.js"></script> … -
Django not saving the multi-select option from form right.
I have a form that has a select multiple option for a model with a Many2Many. This seems to work but upon actually using the form if I select multiple things and click save, it only saves one of the items. The pertinent info int he views.py is located showing where this is happening. Also the output from the transaction is here, it looks like it is doing an insert every time. I think I want to fore a create? Though not sure if I did that (or how to) if it would also do that every time the change what groups the provider belongs to. Output: (0.000) BEGIN; args=None (0.001) DELETE FROM "ipaswdb_providerlocations" WHERE "ipaswdb_providerlocations"."provider_id" = 1; args=(1,) here!IPANM Made a location! here!IPAABQ Made a location! (0.000) BEGIN; args=None (0.000) INSERT INTO "ipaswdb_providerlocations" ("provider_id", "group_location_id", "created_at", "updated_at") VALUES (1, 2, '2016-10-04', '2016-10-04'); args=[1, 2, u'2016-10-04', u'2016-10-04'] Id: 42 forms.py class ProviderForm(forms.ModelForm): phone = forms.RegexField(required=False, regex=r'^(\+\d{1,2}\s)?\(?\d{3}\)?[\s.-]?\d{3}[\s.-]?\d{4}$', error_message = ("Phone number must be entered in the format: '555-555-5555 or 5555555555'. Up to 15 digits allowed."), widget = forms.TextInput(attrs={'tabindex':'8', 'placeholder': '555-555-5555 or 5555555555'})) fax = forms.RegexField(required=False, regex=r'^(\+\d{1,2}\s)?\(?\d{3}\)?[\s.-]?\d{3}[\s.-]?\d{4}$', error_message = ("Fax number must be entered in the format: '555-555-5555 or 5555555555'. Up to … -
Convert html file containing mathjax to pdf using reportlab django
I would like to know how is it possible to convert an HTML file containing some Mathjax to pdf (in order to print it). I tried to make it work like this : VIEWS.PY from easy_pdf.views import PDFTemplateView class HelloPDFView(PDFTemplateView): template_name = "mytemplate.html" def get_context_data(self, **kwargs): context = super(HelloPDFView, self).get_context_data( pagesize="A4", title="Hi Pierre!", **kwargs ) context.update({'variable':12}) return context MYTEMPLATE.HTML {% extends "easy_pdf/base.html" %} {% block extra_style %} <script type="text/x-mathjax-config"> MathJax.Hub.Config({ tex2jax: {inlineMath: [["$","$"],["\\(","\\)"]]} }); </script> <script type="text/javascript" src="https://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-MML-AM_HTMLorMML"></script> {% endblock %} {% block content %} <div id="content"> <h1>Hi there!{{variable}}</h1> {% autoescape on %} $$ \frac{a}{b} x=2 $$ {% endautoescape %} </div> {% endblock %} URLS.PY urlpatterns = patterns('', ('^monpremierpdf.pdf$', HelloPDFView.as_view()), ) But it doesn't give me the result I was expecting. And I still can see the "$$" in my pdf without any Latex inside. If someone could explain me the easiest way to do this, it would be really helpful for the project I'm working on... Thanks! -
Failure during project creation using 'djangocms' command
Django CMS 3.4.1 Django 1.10.2 pip modules: http://pastebin.com/vJWvZVfA pip 8.1.2 Python 2.7.12 OS: Amazon Linux AMI release 2016.03 I'm new to Django CMS, Django, and Python. My previous CMS experience has been with WordPress and I'm try to try out Django CMS as an alternative to WordPress, but am getting an error that I can not seem to figure out. I have updated the pip modules and installed others as suggested in threads on StackOverflow, but to no avail. I followed the tutorial the instructions, with the exception of the djangocms command, which is incorrect in the tutorial. (It's missing the -w flag.) (env)[ec2-user@${HOST} tutorial-project]$ djangocms -w -f -p . mysite Database configuration (in URL format). Example: sqlite://localhost/project.db [default sqlite://localhost/project.db]: postgres://${USERNAME}:${PASSWORD}@${HOST}:${PORT} django CMS version (choices: 3.2, 3.3, 3.4, stable, develop) [default stable]: Django version (choices: 1.8, 1.9, stable) [default stable]: Activate Django I18N / L10N setting; this is automatically activated if more than language is provided (choices: yes, no) [default yes]: Install and configure reversion support (only for django CMS 3.2 and 3.3) (choices: yes, no) [default yes]: no Languages to enable. Option can be provided multiple times, or as a comma separated list. Only language codes supported by Django … -
How do test in Django
I'm trying to do my first tests on Django and I don't know do it or after reading the docs (where it explains a very easy test) I still don't know how do it. I'm trying to do a test that goes to "login" url and makes the login, and after a succesfull login redirects to the authorized page. from unittest import TestCase from django.test.client import Client class Test(TestCase): def testLogin(self): client = Client() headers = {'X-OpenAM-Username': 'user', 'X-OpenAM-Password': 'password', 'Content-Type': 'application/json'} data = {} response = client.post('/login/', headers=headers, data=data, secure=False) assert(response.status_code == 200) And the test success, but I don't know if it's beacuse the 200 of loading "/login/" or because the test do the login and after redirect get the 200 code. How can I check on the test that after the login the url redirected it's the correct? There is a plugin or something that helps with the test? Or where I can find a good tutorial to test my views and the model? Thanks and regards. -
How do I create multiple instances of python application server?
How do I create multiple instances of python application server? I created an application server in python using httpserver. I am not using any python frameworks. Now I want to create multiple instances of the server and use load balancer on top of it. How can I create multiple instances of this application server? Are there any tutorials on how to create multiple instances? I was going through Nginx. Can nginx create multiple instances? Are there any tutorials? Details: I am working on windows machine. It is a python application server created using BaseHTTPServer. I am not using any framework like tornado, django. -
Inspectdb error django
I have postgresql db. I want to make reverse engeneering from db by command python3 manage.py inspectdb > models/models.py All was ok, but I needed to customize auth. I extends from AbstractBaseUser, and try to reispect, because I was alter fields.Then, I looked up in db, and I saw that django add a pound of tables and I cant reinspect my db. Error: python3 manage.py inspectdb > models/models.py super(ForeignObject, self).contribute_to_class(cls, name, private_only=private_only, **kwargs) File "/usr/local/lib/python3.4/dist-packages/django/db/models/fields/related.py", line 314, in contribute_to_class lazy_related_operation(resolve_related_class, cls, self.remote_field.model, field=self) File "/usr/local/lib/python3.4/dist-packages/django/db/models/fields/related.py", line 81, in lazy_related_operation return apps.lazy_model_operation(partial(function, **kwargs), *model_keys) File "/usr/local/lib/python3.4/dist-packages/django/db/models/fields/related.py", line 79, in <genexpr> model_keys = (make_model_tuple(m) for m in models) File "/usr/local/lib/python3.4/dist-packages/django/db/models/utils.py", line 23, in make_model_tuple "must be of the form 'app_label.ModelName'." % model ValueError: Invalid model reference 'models.model.Account'. String model references must be of the form 'app_label.ModelName'. artem@artem-debian:/usr/finstatement/project$ python3 manage.py inspectdb > models/models.py ERROR OH NO Traceback (most recent call last): File "/usr/local/lib/python3.4/dist-packages/django/db/models/utils.py", line 14, in make_model_tuple app_label, model_name = model.split(".") ValueError: too many values to unpack (expected 2) During handling of the above exception, another exception occurred: Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/usr/local/lib/python3.4/dist-packages/django/core/management/__init__.py", line 367, in execute_from_command_line utility.execute() File "/usr/local/lib/python3.4/dist-packages/django/core/management/__init__.py", line 341, in execute … -
is there a way I can store the factorization machine model?
I am using https://github.com/coreylynch/pyFM module, to predict move ratings. However, is there a way I can store (I am using django) the factorization machine after it is trained? Because right now (following the example), I would have to retrain the model everytime I restart the server. -
How to apply read/write permissions to user-uploaded files in Django
I have a "document" model, an upload system using dropzone.js and the register/login. Im now lost on how to apply permissions to each individual uploaded File so only the specified users can access them. Basically: File1->accessible_by = user1,user2 File2->accesible_by=user3,user5... And so on. Thanks to anyone for advice/help on my problem. -
Django: NoReverseMatch when changing to relative url
When I change the line <a href="/rango/category/{{category.slug}}"> to <a href="{% url 'show_category' category.slug %}"> I get NoReverseMatch. What's going wrong? URLs: app_name="rango" urlpatterns = [ url(r'^$', views.index, name='index'), url(r'^about/', views.about, name='about'), url(r'^category/(?P<category_name_slug>[\w\-]+)/', views.show_category, name='show_category'), url(r'^add_category/$', views.add_category, name='add_category'), url(r'^category/(?P<category_name_slug>[\w\-]+)/add_page/$', views.add_page, name='add_page'), ] -
correct way to obtain the rest of the parameters of URL in Django rest framework
Hi everyone I am using Django rest framework to create an API In my URLs.py file I have this url(r'^cpuProjects/$', cpuProjectsViewSet.as_view({'get': 'list'})), url(r'^cpuProjects/(?P<project_name>[a-zA-Z0-9]+)$', cpuProjectsViewSet.as_view({'get': 'retrieve'})), This work perfectly, and I have this to url http://127.0.0.1:8000/cpuProjects/ http://127.0.0.1:8000/cpuProjects/ad in my retrieve function, I have this to get the parameter def retrieve(self, request, project_name=None): try: opc = self.kwargs.get(self.lookup_url_kwarg) print(opc) ... Now, I add this to my URLs.py files url(r'^cpuProjects/(?P<project_name>[a-zA-Z0-9]+/[a-zA-Z0-9]+)$', cpuProjectsViewSet.as_view({'get': 'retrieve'})), http://127.0.0.1:8000/cpuProjects/name_project/whatever_string_here My print(opc) in this last case return this ad/pending. Is this the correct way to obtain the rest of the parameters of URL in Django rest framework? -
How to use HTML5 color picker in Django admin
I'm trying to implement the HTML5 colorpicker in Django's admin page. Here is my model: #model.py ... class Category(models.Model): ... color = models.CharField(max_length=7) Here is the form: #form.py from django.forms import ModelForm from django.forms.widgets import TextInput from .models import Category class CategoryForm(ModelForm): class Meta: model = Category fields = '__all__' widgets = { 'color': TextInput(attrs={'type': 'color'}), } class CategoryAdminForm(ModelForm): form = CategoryForm And finally the admin: #admin.py ... from .forms import CategoryAdminForm ... class CategoryAdmin(admin.ModelAdmin): form_class = CategoryAdminForm filter_horizontal = ('questions',) fieldsets = ( (None, { 'fields': (('name', 'letter'), 'questions', 'color') }), ) However, the type for the field is still text. How do I change the type for the input field to color in the admin page? -
Django basic testing
I'm trying to test a django app. The application returns ok if their is assertion error presence. Here is code. from django.test import TestCase class DemoTest(TestCase): def test_addition(self): self.assertEqual(1 + 1, 3) Please help me to find the error. I'm using the latest version of django. -
django-gulp reports EACCES error on css and js minify
I have a django app that uses a few bower packages, local scripts and css with the compress module turned on. This is supposed to output my minified CSS/JS to /staticfiles which in turn is hosted by the web server. Pretty basic, small project. When running locally everything works but on the EBS server it has these errors (venv)[ec2-user@ip-10-0-1-47 app]$ python manage.py collectstatic [12:01:16] Using gulpfile /opt/python/bundle/7/app/gulpfile.js [12:01:16] Starting 'minify-js'... [12:01:16] Starting 'minify-css'... [12:01:17] 'minify-js' errored after 694 ms [12:01:17] Error: EACCES: permission denied, open '/opt/python/bundle/7/app/static/scripts/application.js' at Error (native) [12:01:17] 'minify-css' errored after 879 ms [12:01:17] Error: EACCES: permission denied, open '/opt/python/bundle/7/app/static/css/main.css' at Error (native) CommandError: Command 'gulp build --production' returned non-zero exit status 1 This is the gulpfile: var gulp = require('gulp'), uglify = require('gulp-uglify'), util = require('gulp-util'), cleanCSS = require('gulp-clean-css'), sass = require('gulp-sass'); gulp.task('stream', function () { return gulp.watch('assets/**/*.*', ['build']); }); gulp.task('default', ['stream', 'build'], function () {}); gulp.task('build', ['minify-js', 'minify-css'], function () {}); gulp.task('minify-js', function () { return gulp.src('assets/javascript/**/*.js') .pipe(util.env.production ? uglify() : util.noop()) .pipe(gulp.dest('static/scripts/')); }); gulp.task('minify-css', function() { return gulp.src('assets/sass/*.scss') .pipe(sass().on('error', sass.logError)) .pipe(util.env.production ? cleanCSS() : util.noop()) .pipe(gulp.dest('static/css/')); }); What could be the problem? -
Geodjango. Distance beetwen two points in one SQL query
I have a task to find the nearest town to the apartment. I suppose it is not difficult task, but I'm new in GeoDjango so every anwser will help :) I have to use only one SQL query. Using django ORM of course. from django.contrib.gis.db.models import MultiPolygonField, PointField from django.db import models class City(models.Model): geo_area = MultiPolygonField(verbose_name='Area') center = PointField(verbose_name='center of City') class Flat(models.Model): geo_point = PointField(verbose_name='Coordinates of apartment') def distance_from_city(self): """ Method calculating distance to the nearest town. In the case where the coordinates of the apartments are located in the middle of the city, it counts the distance to the center of the city (City.center) otherwise has the distance to the border town (City.geo_area) closest to the coordinates of the apartment. The distance is returned in kilometers """ pass -
How to create a generic relation with User model in Django Framework
Question: How to implement a reverse generic relation with User model that could be used on templates and views, without needing to test every time which type of Profile (CompanyProfile or PersonProfile) the logged user has. Context: I've created two types of profile (CompanyProfile and PersonProfile) to include User extra info. The profile has OneToOne relationship with User model and it's created signup time. So far so good, I can access the profile of the logged user on views and templates by using 'user.companyprofile' ou 'user.personprofile', or by whatever related_name I define. But how can I do this in a "generic" way? I'd like to use something like 'user.profile', and have access to fields and methods of each profile without testing and discriminating it. What is the best way to do this?Should I use Generic Relations? If so, could anyone guide me through this? I've already tried using model inheritance (an abstract ProfileBase model inherited by the two others), but this doesn't work for me, because I can't get from ProfileBase objects the user profile (well, it's an abstract model) Real example of what i'd like to accomplish: I've created a method to fetch the user avatar. On PersonProfile, this … -
Accessing link via salted token
I'm generating an url composed of a single use token, and sending it to a user by e-mail. The user should click this link and be redirected to a page which will validate the token and do some actions. On the database side, I'm storing this token (hashed and salted, for security reasons). The problem is I'm having some difficulties to validate the the token because, the way I'm storing it, I cannot generate the same salt for the same token. And, therefore, I cannot compare this salt with the ones I have stored. # Retrieving or creating object usertokens usr, created = UserToken.objects.get_or_create(email=email) # Adding a new token token = uuid.uuid4().hex usr.token = make_password(token) # Stores in the local database the salted and hashed token usr.save() This make_pas sword method I'm using is defined in django.contrib.auth.hashers. By using this method, I cannot generate two times the same salt from the same token. >>> token = 'test' >>> enc_token1 = make_password(token) >>> enc_token2 = make_password(token) >>> enc_token1 == enc_token2 False This, however, does not help me to retrieve from my database the entry corresponding to the token and I cannot validate it. -
Test variables INSIDE a view function - no return
I'm new to Django + Python so I'm not sure how much of this question will make sense. Basically, I'm working on a project (not created by me) that has a function within a views.py file. The purpose of this view function is not to give a HTTP response but to send an email. It accepts a request as a parameter (which contains data that will be looped through - some of it being inserted into the email. The end of the function does a call to an email_extrals.utils function send_mail_template(various different variables passed in). My issue is that I want to write a test for this function which essentially returns nothing (that I can see - it just sends an email). This view function is actually called elsewhere in an API. The purpose of this test is to ensure that if certain variables are present in the request data, then they should be present in a variable which gets passed to the send_email_template() call. So I'm kind of testing for variables inside the function - not what gets returned. I need a way of somehow accessing the internal variables of the function to test them. I can't think of …