Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to save in django using expression as keyword
I want to create an entry in a single column of the model/table by iterating an array of objects. The array of objects is something like this: arr = [ { "field_name" : "email", "field_value" : "abc@abc.com" }, { "field_name" : "name", "field_value" : "Abc Xyz" }, { "field_name" : "gender", "field_value" : "M" } ] I want the data to be saved like this: | **email** | **name** | **gender** | | abc@abc.com | Abc Xyz | M | Suppose if I have a model named "model_name", then the code which I have written is like this: modelObject = model_name() for data in arr: modelObject( data['field_name'] = data['field_value'] ) modelObject.save() I want to save this data in a single-go as the data corresponds to a single column. But the code which I have written is giving "keyword can't be an expression" Error at line: modelObject( data['field_name'] = data['field_value'] ) Can somebody help me in figuring a way out of this? -
Patching multiple ORM calls in Django
I have a service layer in my Django app, where I have some business logic and the corresponding data retrieval code. Now, when I am writing unit tests, I want to mock out the calls to the ORM so that I am testing the service layer only. My service layer looks something like this: from .models import Event class EventService(): def get_client_separated_events(self): # Some complex business logic goes here qs = Event.objects.all() # Some complex business logic here as well return foo When I'm testing the EventService class, I'd want the calls such as Events.objects.all() to be mocked out totally. As of now, I'm using patch to achieve this: class TestEventService(TestCase): @classmethod def setUpTestData(cls): cls.event_service = EventService() cls.dummy_events = [Event(id=1, name='n1', description='d1'), Event(id=2, name='n2', description='d2')] @patch('foo.bar.Events.objects.all') def test_get_all(self, get_events): get_events.return_value = self.dummy_events expected_events = self.event_service.get_all() self.assertListEqual(expected_Events, self.dummy_events, msg="Assertion failed for get_all method " "in Event Service") However, there might be ten such different ORM calls and I don't want to write ten lines worth of @patch statements to mock them out. I read online that @patch.multiple can do this - but I don't quite know if this is the right way to go about it. Can someone help? -
django one-to-one fields with User model with using serializer
The User model and UserProfile model are connected with one-to-one field .I want to post data through serializer but the program gives error... this is model code.. class UserProfile(models.Model): GENDERS = ( ('M', 'Male'), ('F', 'Female'), ('T', 'Transgender'), ) user = models.OneToOneField(User) dob = models.DateField(null=True) contactno = models.BigIntegerField(null=True) gender = models.CharField(max_length=1, choices=GENDERS,blank=True, null=True) country = models.ForeignKey(Country, null=True) state = ChainedForeignKey(State,chained_field="country", chained_model_field="country", null=True) city = ChainedForeignKey(City,chained_field="state", chained_model_field="state", null=True) pin_code = models.IntegerField( null=True, blank=True, default = None) class Meta: verbose_name_plural = 'User Profile' def __unicode__(self): return str(self.user) this is serializer code... class userProfileSerializer(serializers.ModelSerializer): class Meta: model = UserProfile fields = ("dob","contactno","country","state","city",'user') class userSerializer(serializers.ModelSerializer): dob = userProfileSerializer() contactno = userProfileSerializer() country = countrySerializer() state = stateSerializer() city = citySerializer() class Meta: model = User fields = ('username','email','password',"dob","contactno","country","state","city") def create(self, validated_data): dob_data = validated_data.pop('dob') contactno_data = validated_data.pop('contactno') country_data = validated_data.pop('country') state_data = validated_data.pop('state') city_data = validated_data.pop('city') user = User.objects.create(username=validated_data['username'],email=validated_data['email'],password=validated_data['password']) user.set_password(validated_data['password']) user.save() UserProfile.objects.create(user=user,dob=dob_data,contactno=contactno_data,country=country_data,state=state_data,city=city_data) return user it will be very great if anyone help me.... -
Django: many to many reverse of its own type
I have a model called "Service", which subclasses a "Page" model. This is defined as follows: class Service(Page): content = RichTextField(null="True", blank="True") links = models.ManyToManyField("pages.Page", blank=True, related_name="service_links") The "links" many-to-many relationship should allow every service to link to multiple pages (regardless of if they are a service) I want to be able to pull these results into its own service page (which I'll call Page A in this example) so that it can show these links to the end user. I am currently using: related_links = Service.objects.filter(links=request.page.id) but this only works for Pages that are pointing to Page A, not Page A's links. How can I reverse this filter to get the links on Page A? -
nginx doesn't forward to django app in docker-compose in ubuntu but it all works in docker-machine in Mac
I have a django backend where I use docker-compose to deploy. This django application uses a nginx proxy in the front. When I deploy it in a docker-machine and I go to the docker-machine ip I am redirected to the django site properly. But when i deploy it in a ubuntu machine on docker, when i go to the ip of the nginx container I am given the default nginx page, I am not redirected to the django application. The nginx container doesn't log any error too. All services are running in docker without any error. I am sharing the config file of nginx, docker-compose files below nginx.conf server { listen 80; server_name omaha; listen 443 ssl; ssl_certificate /etc/nginx/ssl/ssl.crt; ssl_certificate_key /etc/nginx/ssl/ssl.key; charset utf-8; client_max_body_size 200M; location / { proxy_pass http://web:8000; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; } } nginx dockerfile FROM nginx COPY conf/nginx.conf /etc/nginx/conf.d/nginx.conf COPY certs/ /etc/nginx/ssl docker-compose.yml version: '2' services: nginx: restart: always build: context: ./nginx/ ports: - "80:80" - "443:443" volumes_from: - web web: restart: always build: context: ./web depends_on: - web_ffmpeg - postgres - redis - rabbitmq expose: - "8000" environment: - DEBUG=True command: /usr/local/bin/gunicorn wsgi:application -w 2 -b :8000 … -
NoReverseMatch when using url
Almost all posts to the error "NoReverseMatch" I've seen were caused, by using url in a template and not passing an ID. I get following error: Reverse for 'save_ytlink' with arguments '()' and keyword arguments '{}' not found. 0 pattern(s) tried: [] when trying to execute following line: home.html <form action="{% url 'ytlinks:save_ytlink' %}" method="post"> urls.py app_name = 'ytlinks' urlpatterns = [ url(r'^save_ytlink', views.save_ytlink, name='save_ytlink'), views.py def save_ytlink(request): The error message says, that I have to pass an argument, which would be request. Isn't this generated automatically? How can I pass it? Off-topic: Can I use ytlinks:xxx on the level of urls.py and all subfolders? -
How to create new postgreSQL rows to save data every time you run your django code
I have a doubt now when I execute my script I am able to save it in a row My models.py has 2 tables ( or class) Page and Category This code is a snip from my views.py Category.objects.all() f = Category() Page.objects.all() p = Page() p.category = f x = India(symb) f.name = x['Company Name'] f.save() p.category = f p.title = symb p.price = float(x['Price']) p.save() when I execute it again or everytime , it overwrites the same row which makes sense the way I used it. How do I create new row every time I run my script so that I can save new data in a new row instead of overwriting the same row I thought of using python 'random' to pick a random letter from a list (g for example) everytime I run the script then join it to get something like 'g.price' but then this has limitation of 26 letters , random but not unique so same letters can be generated ( though I can do a 'if' check on that). Is there an easy and proper way to do this.? -
Put elements from left and right side to the same line
I'm using html2pdf with my Django project in order to create some PDF files and I get an HTML problem. I would like to put two elements situated on the same line but the first one is located into the right side and the other one to the left side. My script looks like : <html> <head> {% load staticfiles %} <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <link rel="stylesheet" type="text/css" href="{% static 'css/BC_base.css' %}"/> <style> body { font-family: Courier New, Courier, monospace; /*text-align: justify;*/ list-style-type: none; } .alignleft { float: left; border-right : 100px; } .alignright { float: right; border-left: 100px; } .title { border-top: 150px; font-size: 7; } {% block style %} @page { size: landscape; } {%endblock%} </style> </head> <h2 class = "title" align="center" > ATTESTATION DE RECENSEMENT </align> </h2> <div id="textbox"> <p class="alignleft">Le maire de la commune <br />de {{mairie.city}}</p> <p class="alignright">Imprimé n° {{ar.id}}<br/> Loi n° ... du XX XX XXXX</p> </div> But I don't overcome to put alignleft and alignright classes on the same line. I'm using the library html2pdf to do that so all CSS command are not take account. Thank you if you have an idea ? -
Blank spaces inserted in Django template empty div
I have a Django template which looks like this: <div class = 'description' contenteditable = 'true' placeholder='{{my_placeholder}}'> </div> The problem is that Django inserts blank spaces in div so that the code below yields A B instead of AB alert('A' + $('.new').find('.description').html() + 'B'); If I rewrite the HTML code as follows (by bring </div> on the same line): div class = 'description' contenteditable = 'true' placeholder='{{my_placeholder}}'> ...the issue goes away. However, I do like the HTML structure where the closing is on a new line. How can I keep this structure so that the element is really blank and I can see the placeholder value ? -
django uwsgi creates log file but the file is empty (works with development server)
I am trying to set up my django project with uwsgi. I have defined my log handlers in settings.py and they will write logs fine when i used the development server. However when i move to my production server using uwsgi, although the log file is created, it is empty. My settings.py contains this enter code here import logging logger = logging.getLogger('django_auth_ldap') logger.addHandler(logging.StreamHandler()) logger.setLevel(logging.DEBUG) LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'handlers': { 'console': { 'class': 'logging.StreamHandler', }, 'file': { 'level': 'DEBUG', 'class': 'logging.FileHandler', 'filename': '/tmp/zdebug.log', }, }, 'loggers': { 'django': { 'handlers': ['console','file'], 'level': os.getenv('DJANGO_LOG_LEVEL', 'INFO'), }, 'devices': { 'handlers': ['console','file'], 'level': 'INFO' }, 'stack_configs': { 'handlers': ['console','file'], 'level': 'INFO' }, 'django_auth_ldap': { 'handlers': ['console','file'], 'level': 'INFO' }, }, } Thanks in advance for any help you can offer. -
Create query between ManyToMany relationship models in Django ORM
class Review(models.Model): student = models.ForeignKey(UserDetail) text = models.TextField() created_at = models.DateTimeField(auto_now=True) vote_content = models.FloatField() vote_knowledge = models.FloatField() vote_assignment = models.FloatField() vote_classroom = models.FloatField() vote_instructor = models.FloatField() class UserDetail(models.Model): username = models.CharField(max_length=100) email = models.CharField(max_length=255) firstname = models.CharField(max_length=100, blank=True, null=True) lastname = models.CharField(max_length=100, blank=True, null=True) class Course(models.Model): title = models.CharField(max_length=255) studentlist = models.ManyToManyField(UserDetail, related_name='course_studentlist', blank=True) reviewlist = models.ManyToManyField(Review,related_name='course_reviewlist', blank=True) In the above model structure, the Course model has a relationship with UserDetail and Review with ManyToMany. The review is based on the average of the 5 votes. (content, knowledge etc.) A review of a course is the average of the votes of all the students. I would like to make a search and sort according to Course's review, for example, list bigger than 3 votes. Thanks for your help. -
How to highlight the code using prismjs code highlighter for django-summernote?
I am using django-summernote wysiwyg editor, now I want to highlight the code using Prism-js highlighter. I don't want to use Code Mirror which is default code highlighter for django-summernote. Please help -
'credential' is an invalid keyword argument for this function
I'm working with Django and trying to pull some Google Analytics user data using oAuth2Client. I keep getting: 'credential' is an invalid keyword argument for this function And I can't figure out what I'm doing wrong. In my models.py I have: class CredentialsModel(models.Model): credentials = CredentialsField() id = models.OneToOneField(User, primary_key=True) class Meta: db_table = 'credentials' def __str__(self): return 'creds' My Views.py: def google_connected(request): """Step 2: connect to google analytics API""" flow = OAuth2WebServerFlow(client_id = settings.GOOGLE_OAUTH2_CLIENT_ID, client_secret = settings.GOOGLE_OAUTH2_CLIENT_SECRET, scope = settings.GOOGLE_SCOPE, redirect_uri = settings.OAUTH_REDIRECT_URI,) #/complete/google if request.method == 'GET': if 'code' in request.GET: code = request.GET['code'] credentials = flow.step2_exchange(code) http = httplib2.Http() http = credentials.authorize(http) service = build('analytics', 'v4', http=http) v3_service = build('analytics', 'v3', http=http) profiles = v3_service.management().accountSummaries().list().execute() print(profiles) account_names = profiles['items'][0]['name'] google_username = profiles['username'] property_list = {} try: current_user = User.objects.get(username=google_username) except User.DoesNotExist: current_user = User.objects.create_user(username=google_username) current_user.backend = 'django.contrib.auth.backends.ModelBackend' if current_user: login(request, current_user) print("logging in user") else: print("problem logging in user") current_user = None if current_user: current_profile = Profile.objects.get_or_create(user=current_user)[0] print(current_profile) if not current_profile.google_credentials: creds = CredentialsModel.objects.create(user_id=current_user, credential=credentials) current_profile.google_credentials = creds creds.save() current_profile.save() if current_profile.google_property: #redirect to report page return render(request, 'ga_app/base.html', {'current_profile': current_profile}) else: if not current_profile.google_property: google_property_form = GooglePropertyForm() #need to ask which property they want to use … -
Django : Passing multiple objects to templates but nothing in there
I wanted to pass two objects to templates, so I put theme in the context and try to send them but failed. I tried few times but it seems like user get objects but comment is always empty even though there are some data in db. This is views.py @login_required def detail(request, article_no): if not request.user.is_authenticated(): return redirect_to_login(next, 'blog/login.html') else: user = request.user if 'username' in request.session: username = request.session['username'] item = get_object_or_404(Article, pk=article_no) item.hit = Article.objects.filter(pk=article_no).update(hit = item.hit+1) #comment = Comment.objects.filter(pk=article_no).order_by('comment_no') comment = Comment.objects.all() context = { 'item': item, 'comment': comment, } return render(request, 'blog/detail.html', context) this is models.py from datetime import datetime from django.db import models from django.template.defaultfilters import default class Article(models.Model): no = models.AutoField(primary_key=True) title = models.CharField(max_length=50) content = models.CharField(max_length=300) writer = models.CharField(max_length=50) is_visible = models.BooleanField(default=True) created_date = models.DateTimeField(editable=False, default=datetime.now()) hit = models.IntegerField(default=1) class Comment(models.Model): article_no = models.IntegerField(default=1) comment_no = models.AutoField(primary_key=True) comment_writer = models.CharField(max_length=50) comment_body = models.CharField(max_length=300) comment_date = models.DateTimeField(editable=False, default=datetime.now()) template {{ item.title }} {{ item.no }} {{ item.writer }} {{ item.hit }} {{ item.created_date }} {{ item.content }} {% if comments %} {% for comment in comments %} {{ comment.comment_no }} {{ comment.comment_writer }} {{ comment.comment_body }} {{ comment.comment_date }} {% endfor %} {% else … -
NoReverseMatch error in Django pagination
The slug name pattern matches for the first page of pagination but it returns 'NoReverseMatch' error for other pages. This is the template: added by <a href="{% url 'pplistPage' story.author %}"><strong>{{ story.author }}</strong></a> This is the urls.py (I've tried many other regex, still same problem) url(r'^profile/(?P<profile>[a-zA-Z0-9_]+)/', views.profilepostlist, name='pplistPage'), this is the views.py def homepage(request, latest_f=latest_f, latest_m=latest_m, latest_a=latest_a, ppp=ppp): stories = Story.objects.all().order_by("-modified") paginator = Paginator(stories, ppp) page = request.GET.get('page') try: story_list = paginator.page(page) except PageNotAnInteger: story_list = paginator.page(1) except EmptyPage: story_list = paginator.page(paginator.num_pages) context = { 'stories' : story_list, 'latest_f' : latest_f, 'latest_m' : latest_m, 'latest_a' : latest_a, } return render(request, 'listing/index.html', context) Weird thing is it works in the first page of pagination and in index page and even in the story page which does not have pagination. But when I click the other pages ( '127.0.0.1:8000/?page=2' ) it raises the error. Example pattern: '127.0.0.1:8000/profile/orhan/' Error message: 'Reverse for 'pplistPage' with arguments '('',)' and keyword arguments '{}' not found. 1 pattern(s) tried: ['profile/(?P[a-zA-Z0-9_]+)/']' -
SOAP services using Django
I am looking to develop a few SOAP based services using Django. Coming from Java where we had multiple options liek from Eclipse or Jax-WS, i don't see anything in Django. While is see multiple options for REST like Django REST, Flask etc i don't see anything for SOAP. Any pointer's ? -
Django Foreign Key automatically filled based off of another field on model
So I currently have an "Account" Model and "Account Comments" Model -- keep in mind, that I can't really control the scheme of the database, and I'm writing a wrapper around existing DB. Under the AccountComments Model, there is a field called "Data". It is where the AccountComments actually are and I'm trying to basically create a foreign key on the Account model without actually having to redesign and add a "AccountComments" field on Account that holds the AccountID. class Account(models.Model): AccountID = models.AutoField(editable=False, db_column='AccountID', verbose_name='ID', primary_key=True) acctno = models.IntegerField(editable=True, unique=True, db_column='ACCTNO', verbose_name='Acct #', blank=True, null=True) # Field name made lowercase. accountComments = models.ForeignKey('accountComments',to_field='accountID',db_column='Data') def __str__(self): return str(self.acctno) class Meta: managed = False db_table = 'Account' class accountComments(models.Model): accountCommentID = models.AutoField(db_column='AccountCommentID', primary_key=True) # Field name made lowercase. accountID = models.IntegerField(db_column='AccountID') # Field name made lowercase. EntryUserID = models.IntegerField(db_column='EntryUserID') # Field name made lowercase. EntryStamp = models.DateTimeField(db_column='EntryStamp', ) # Field name made lowercase. Data = models.TextField(db_column='Data') # Field name made lowercase. guid = models.CharField(db_column='guid', max_length=255) # Field name made lowercase. class Meta: managed = False db_table = 'AccountComment' ultimately, want accountComments on the Account Model to use 'AccountID' to do a lookup onto accountComments.accountID and then provide back 'Data'. I know … -
Why when I try to use models in celery tasks django raises "Apps aren't loaded yet" error?
I work with django 1.10.5 and celery 4.0.2. I have the structure like this. -proj -application __init__.py celery.py celery_conf.py settings.py tasks.py urls.py wsgi.py -extuser (application with extended UserModel) -pages -migrations -templates __init__.py admin.py apps.py forms.py models.py tasks.py tests.py views.py I have the task which uses model from file which contains my extended user model. If I try to run celery with this command: celery -A application worker -l INFO -B Then I see this error: Traceback (most recent call last): File "/home/dmitriy/MyEnv/DjangoProjects/sPrint/env/bin/celery", line 11, in <module> sys.exit(main()) File "/home/dmitriy/MyEnv/DjangoProjects/sPrint/env/local/lib/python2.7/site-packages/celery/__main__.py", line 14, in main _main() File "/home/dmitriy/MyEnv/DjangoProjects/sPrint/env/local/lib/python2.7/site-packages/celery/bin/celery.py", line 326, in main cmd.execute_from_commandline(argv) File "/home/dmitriy/MyEnv/DjangoProjects/sPrint/env/local/lib/python2.7/site-packages/celery/bin/celery.py", line 488, in execute_from_commandline super(CeleryCommand, self).execute_from_commandline(argv))) File "/home/dmitriy/MyEnv/DjangoProjects/sPrint/env/local/lib/python2.7/site-packages/celery/bin/base.py", line 281, in execute_from_commandline return self.handle_argv(self.prog_name, argv[1:]) File "/home/dmitriy/MyEnv/DjangoProjects/sPrint/env/local/lib/python2.7/site-packages/celery/bin/celery.py", line 480, in handle_argv return self.execute(command, argv) File "/home/dmitriy/MyEnv/DjangoProjects/sPrint/env/local/lib/python2.7/site-packages/celery/bin/celery.py", line 412, in execute ).run_from_argv(self.prog_name, argv[1:], command=argv[0]) File "/home/dmitriy/MyEnv/DjangoProjects/sPrint/env/local/lib/python2.7/site-packages/celery/bin/worker.py", line 221, in run_from_argv return self(*args, **options) File "/home/dmitriy/MyEnv/DjangoProjects/sPrint/env/local/lib/python2.7/site-packages/celery/bin/base.py", line 244, in __call__ ret = self.run(*args, **kwargs) File "/home/dmitriy/MyEnv/DjangoProjects/sPrint/env/local/lib/python2.7/site-packages/celery/bin/worker.py", line 255, in run **kwargs) File "/home/dmitriy/MyEnv/DjangoProjects/sPrint/env/local/lib/python2.7/site-packages/celery/worker/worker.py", line 94, in __init__ self.app.loader.init_worker() File "/home/dmitriy/MyEnv/DjangoProjects/sPrint/env/local/lib/python2.7/site-packages/celery/loaders/base.py", line 116, in init_worker self.import_default_modules() File "/home/dmitriy/MyEnv/DjangoProjects/sPrint/env/local/lib/python2.7/site-packages/celery/loaders/base.py", line 111, in import_default_modules return [self.import_task_module(m) for m in self.default_modules] File "/home/dmitriy/MyEnv/DjangoProjects/sPrint/env/local/lib/python2.7/site-packages/celery/loaders/base.py", line 97, in import_task_module return self.import_from_cwd(module) File "/home/dmitriy/MyEnv/DjangoProjects/sPrint/env/local/lib/python2.7/site-packages/celery/loaders/base.py", line 106, … -
Getting Django Apache Mysql WSGI working using a python 3.4 virtualenv on a machine with a pre-exisiting flask app running under the global python2.7
I set up a flask app running with apache 2.4, mod wsgi, python 2.7 on a mac mini. It serves some useful data which my team use to monitor our project. I have recently developed a Django App with a MySQL database backend which works really nicely under the test server in a python 3.4 virtual environment with Django 1.10 and PyMySQL and mysqlclient installed via by pip but I cannot get this working under apache. My Apache Virtual server congiguration is as follows: WSGIScriptReloading On <VirtualHost *> ServerName <server_name> ServerAlias <project_name> ServerAdmin <myEmail LogLevel info # This is the WSGI daemon process for the existing python 2.7/flask project # Even if I comment this bit out, the Django project still won't work WSGIDaemonProcess theApp user=_www group=staff threads=5 WSGIScriptAlias /app1 /path/to/app1/apache/wsgi.py <Directory "/path/to/app1/apache"> WSGIProcessGroup app1 WSGIApplicationGroup %{GLOBAL} <Files wsgi.py> Require all granted </Files> </Directory> # This is the WSGI daemin process for my django app - I've anonymised it # a bit but I am confident the paths used are correct WSGIDaemonProcess djangoApp user=_www group=staff processes=2 threads=15 python-path=/path/to/djangoApp:/path/to/virtualenvs/env34 display-name=%{GROUP} WSGIProcessGroup djangoApp WSGIApplicationGroup %{GLOBAL} WSGIScriptAlias /djangoApp /path/to/djangoApp/djangoApp/wsgi.py <Directory /path/to/djangoApp/djangoApp> <Files wsgi.py> Require all granted </Files> </Directory> </VirtualHost> There is a line … -
Django on Docker - relation "django_session" does not exist at character 109
I'm trying to run Django project based on coockiecutter using Docker but I get these errors: full output: https://dpaste.de/eKF5 sudo docker-compose up crm_postgres_1 is up-to-date Starting crm_django_1 Starting crm_nginx_1 Attaching to crm_postgres_1, crm_django_1, crm_nginx_1 django_1 | Postgres is up - continuing... postgres_1 | LOG: database system was shut down at 2017-02-15 10:39:52 UTC postgres_1 | LOG: MultiXact member wraparound protections are now enabled postgres_1 | LOG: database system is ready to accept connections postgres_1 | LOG: autovacuum launcher started postgres_1 | LOG: received smart shutdown request postgres_1 | LOG: autovacuum launcher shutting down postgres_1 | LOG: shutting down postgres_1 | LOG: database system is shut down postgres_1 | LOG: database system was shut down at 2017-02-15 10:41:58 UTC postgres_1 | LOG: MultiXact member wraparound protections are now enabled postgres_1 | LOG: database system is ready to accept connections postgres_1 | LOG: autovacuum launcher started postgres_1 | ERROR: relation "django_session" does not exist at character 109 postgres_1 | STATEMENT: SELECT "django_session"."session_key", "django_session"."session_data", "django_session"."expire_date" FROM "django_session" WHERE ("django_session"."expire_date" > '2017-02-15T11:04:25.807267+00:00'::timestamptz AND What should I check? I can't debug this by myself. -
Django annotation output_field=DecimalField ignores max_digits and decimal_places
Inside an annotation I do some calculations, and I want the output to be a decimal, with max 8 digits and max 2 decimal. I don't know why but Django ignores decimal_places and max_digits. Here is my code: Order.objects.all().annotate( amount=Coalesce( Sum( Case( When( Q(payments__status='complete'), then=F('payments__amount') - ( F('payments__amount') * F('payments__vat')/CustomDecimal(100) ) ), output_field=DecimalField(decimal_places=2, max_digits=8) ) ), 0) ).values('amount') output = 12.5999999999999996447286321199499070644378662109375 -
Nested URL not showing in Django Rest Swagger
I'm trying to document my Django REST API using Django Rest Swagger. My main url conf looks like this: urlpatterns =[ url(r'^tickers/', include('tickerapi.urls')), ] and tickerapi/urls: schema_view = get_swagger_view(title='Ticker API') urlpatterns = [ url(r'^docs/', schema_view), url(r'^(?P<channel_name>[-\w]+)/', include([ url(r'^$', views.ChannelUpdateView.as_view(),name='channel_update'), url(r'^ONAIR$', views.CarouselsOnAirContentList.as_view(),name='carousel_onair_content_list'), url(r'^(?P<carousel_name>[-\w]+)$', views.CarouselUpdateView.as_view(), name='carousel_update'), ])), ] As you can see, my url are nested in order to have different views handling the following urls: /tickers/{channel_name} (Operations: PUT, PATCH) /tickers/{channel_name}/ONAIR (Operations: GET) /tickers/{channel_name}/{carousel_name} (Operations: GET, PUT, PATCH) My issue is that Django Rest Swagger is only displaying part of the nested urls, like so: Django Rest Swagger Screenshot From what I can understand Django Rest Swagger is considering that /tickers/{channel_name} and /tickers/{channel_name}/{carousel_name} is the same endpoint. Indeed, if I only allow GET operation on the view handling /tickers/{channel_name}/{carousel_name} (using a ListAPIView), the missing nest URL is showing in Swagger, minus the GET operation: Django Rest Swagger Screenshot Has anyone come across this issue ? I'm using Django 1.10.5, Django Rest Framework 3.5.4 and Django Rest Swagger 2.1.1 Thank you for you help -
Django can't download file via admin
I'm using Django version 1.10.5 to build a website with the following apps installed: django.contrib.admin django.contrib.auth django.contrib.contenttypes django.contrib.sessions django.contrib.messages django.contrib.staticfiles bootstrap3 myapp storages In the models.py I defined the following class: class SourceData(models.Model): File = models.FileField(blank=True, null=True, upload_to='Upload') On the website I tried to upload a file via admin, which was successfull. However if I click on the uploaded file, I get a Page not found 404 Error. Any help or ideas apreciated. Thanks in advance! -
AttributeError: Manager isn't accessible via UserBillingHistory instances
This is my signal: @receiver(post_save, sender=settings.AUTH_USER_MODEL) def create_auth_token(sender, instance=None, created=False, **kwargs): """Receiver to create authoriasation tokens for users""" if kwargs.get('raw'): return # ignore for loading fixtures import pdb; pdb.set_trace() if created: Token.objects.create(user=instance) UserBillingHistory.objects.create(user=instance) if settings.NEW_USER_EMAIL is not None: send_email( "Spotless data - new user", "New user with email %s has signed up" % instance.email, "Spotless Data<team@spotlessdata.com>", settings.NEW_USER_EMAIL ) This is my model: class UserBillingHistory(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) description = models.TextField(max_length=500, blank=False, default="Free 100Mb on sign-up and Buy $40 and get 100Mb") cash_amount = models.DecimalField(max_digits=9, decimal_places=2) data = models.IntegerField(null=False, blank=False) date = models.DateTimeField(default=timezone.now, blank=False, null=False) is_confirmed = models.BooleanField(default=False) job = models.ForeignKey("Job", on_delete=models.SET_NULL, null=True) def __unicode__(self): return self.description @property def user_can_view(self, user): return (self.user == user) def user_can_edit(self, user): return (self.user == user) def get_absolute_url(self): return "/userbillinghistorys/%s/" % self.id def cash_amount(self): return "$%s" % 0 def data(self): return 100 * 1024 * 1024 When i try to create new user signup i am getting below error. AttributeError: Manager isn't accessible via UserBillingHistory instances And Regarding this model by default will show content to data=100*1024*1024 and cash_amount=0. Can you please suggest regarding it thanks. -
How I can force nginx to save response in a cache folder, with headers from upstream server?
I use Django REST Framework for my API, nginx as a reverse proxy and redis for caching some static api data. I was trying to implement caching with Cache-Control: max-age and Last-Modify headers. In a nutshell it looks like this: class SomeViewSet(viewsets.ModelViewSet): .... def list(self, request, *args, **kwargs): queryset = self.get_queryset() cache_key = self._get_cache_key() # get a key for reddis response = self._get_data_from_cache(cache_key) # get a data from reddis if response: # If data in redis return Response with a same Last-Modify # and 'Cache-Control': 'max-age=120' return response # Setting up new value for this viewset in a reddis serializer = self.get_serializer(queryset, many=True) now = datetime.datetime.now() cache.set(cache_key, [now, serializer.data]) return Response(serializer.data, headers={'Last-Modified': now, 'Cache-Control': 'max-age=120'}) It work like I expect, browser caching data for 120 seconds and when it expire client check content with an If-Modified-Since header. But I though when I setting up max-age headers nginx will save it in a cache folder and will serving up all clients without hitting a server. here is my testing nginx config from local machine: upstream django { server 127.0.0.1:8002; } proxy_cache_path /home/ivan/projects/kors/test_prod/cache levels=1:2 keys_zone=my_cache:10m max_size=10g inactive=60m use_temp_path=off; server { listen 8000; server_name 127.0.0.1; # charset utf-8; client_max_body_size 75M; location /media { …