Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can I make sure that every child is meeting one condition on Django Models?
I need to look for a recipe if and only if all of its ingredients are included in a list of ingredients. In SQL the query would be something like SELECT * FROM recipe r WHERE no exists (SELECT 1 FROM recipe_ingredient ri WHERE r.id = ri.recipe_id AND ri.ingredient_id not in (1,2,3)) Where 1,2,3 is the list of ingredients. How can I do this using Django Models? -
django.db.utils.OperationalError: FATAL: role "django" does not exist
I followed this tutorial on Digital Ocean to install PostgreSQL 9.5 on an Ubuntu 16.04 server to use with Django 1.10. Everything went smoothly, but I can't get my Django app to connect to the database (or so it seems). App and database are on the same server. Here are some settings, configs and reports: The error I get: File "/home/mathieu/web/agencies/lib/python3.5/site-packages/psycopg2/__init__.py", line 164, in connect conn = _connect(dsn, connection_factory=connection_factory, async=async) django.db.utils.OperationalError: FATAL: role "django" does not exist My Django project's database settings: DATABASES = { 'sqlite3': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3') }, 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'agencies', 'USER': 'django', 'PASSWORD': '<password>', 'HOST': 'localhost', 'PORT': '5432', }} The hba_file postgres=# SHOW hba_file; hba_file -------------------------------------- /etc/postgresql/9.5/main/pg_hba.conf Its contents (well, the relevant part anyway): # TYPE DATABASE USER ADDRESS METHOD # "local" is for Unix domain socket connections only local all all peer # IPv4 local connections: host all all 127.0.0.1/32 md5 # IPv6 local connections: host all all ::1/128 md5 # Allow replication connections from localhost, by a user with the # replication privilege. #local replication postgres peer #host replication postgres 127.0.0.1/32 md5 #host replication postgres ::1/128 md5 Users and database in psql postgres=# \du List of roles Role name … -
How to run django sslserver with webpack to read https requests?
I am creating a website whose frontend is on Reactjs and backend is on django. Whenever i run sslserver of django, webpack is unable to read any https requests. I have already tried Webpack Dev Server running on HTTPS/Web Sockets Secure , http://webpack.github.io/docs/webpack-dev-server.html#webpack-dev-server-cli These links did not help me much. -
Django is rendering without context. Why?
I am building a new framework for an institution. I'm currently working with Django to create the framework. When i was creating the "New user" form, i noticed that some parts of the page was rendering without context. Why is that? Look: view.py from django.contrib.auth.models import User def index(request): context = { 'user': request.user, 'userDB': User.objects.all() } return render(request, 'user/home.html', context) def new_user(request): return render(request, 'users/new.html', {}) user/home.html {% user.username %} user/new.html {% user.username %} As you can see, there is no context available to render new_user, but it renders it. I am afraid this could bring some problems in the future. Although, it's the desired effect, but i don't understand it... -
Django & aws S3 : How can I collectstatic only changed files?
I used AWS EC2 and S3 for server and storages. Everytime I changed my static files and execute python manage.py collectstatic, then it overwrite ALL files in S3 storage. I searched some answer in google, but there is no obvious way to do it. Need your advices. Thanks. -
Too many keys specified; max 64 keys allowed django mysql
I have a table with 155 columns. All they are Charfield. First I added db_index=True. But when I ran manage.py migrate, I had above error. Then I removed db_index, but still get the same error. What makes django create indices and how to increase this limit? -
How does a Serializer handle Posted JSON data?
My front-end (Angular2) is posting JSON to my Django Rest Framework backend. I am confused how my serializer should handle the JSON and extract the information. How can my ContactFormSerializer extract the JSON data['userDetails']['email']? # Posted data example: { "sessionID": "1", "created": "2/12/2016", "completed": false, "payment": { ... }, "userDetails": { "userID": 1, "email": "foo@gmail.com", "location": "US" } } class ContactUsView(APIView): def post(self, request): serializer = ContactFormSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) class ContactFormSerializer(serializers.Serializer): def save(self): # How can I grab the user email address from the JSON? # send email to us -
How can i implement SMS on my web application, send sms, also the server can reply to a specific SMS
i have a web application, so i use some API SMS, they are too expensive for the goal of my application. i want to know if you know the best way to create a sms server to send sms to users, and if the users ask a question to the server, my application can easily reply. I think i can use a modem with a SIM card, it's my first idea. Web application with django -
pass request.path like parameter Django
Hi everyone I have this url in my urls.py file url('^login$', 'lib.views.site_login'), I use this URL in my home template like this <a href="{% url 'lib.views.site_login' %}?next={{request.path}}">Login</a> I have to pass request.path like a parameter but I obtain this error 'Settings' object has no attribute 'HOME_URL' any idea! -
Disable Captcha on Django form unittest
I have a Django model form that includes a NoReCaptchaField and it's working fine. I want to write a unittest but I can't seem to override the captcha field (which I guess is its purpose, but it's causing all my tests to fail). class MyForm(forms.ModelForm): full_text = forms.CharField() captcha = NoReCaptchaField() -
Django Local to Production Setup: just change manage.py?
Currently my manage.py file is hardcoded to import my local.py - development settings file. Is this the 'industry standard' way to set this up? When I deploy to the server do I just change manage.py to point to my production settings file? Or should I set this up another way? #!/usr/bin/env python import os import sys if __name__ == "__main__": # Hard coded imports local settings file os.environ.setdefault("DJANGO_SETTINGS_MODULE", "project.settings.local") from django.core.management import execute_from_command_line execute_from_command_line(sys.argv) Structure: project/ manage.py settings/ local.py shared.py production.py -
Django - Combine serializers/Models
I have models like this.. class Faculty(models.Model): faculty_name = models.CharField(max_length=30) class Department(models.Model): department_name = models.CharField(max_length=30) faculty = models.ForeignKey(Faculty) class Section(models.Model): section_name=models.CharField(max_length=50) department=models.ForeignKey(Department) class Student(models.Model): first_name=models.CharField(max_length=20) last_name=models.CharField(max_length=20) section= models.ForeignKey(Section) Now I want to retrieve data like this by combining all the models : [ { "first_name": "abc", "last_name": "def", "section": { "section_id": "sec-2", "section_name": "Section_Name" }, "department": { "department_id": "DD-2", "department_name": "Department_Name" }, "Faculty": { "Faculty_id": "fac-2", "Faculty_name": "Enggineering" }, } ] Is there any way to achieve this through serializers or views ? if yes please help me. -
Unable to execute Python script in a Django view
I'm relatively new to Django and Python is not my "native" language, so I'm a bit stuck with the following problem. What I want to achive is to be able to create map tiles with zoomifyimage package. This package can be downloaded from here. It works good for me, so I can create map tiles through a command line. This is how I do it: cd C:\Zoomify C:\Zoomify> python ZoomifyFileProcessor.py big_image.jpg And the above command creates really nice tiles, that I can work with in my map application (not written in Python). Besides, I can do the same trick from Python shell: >>> import subprocess >>> subprocess.call(['python', 'ZoomifyFileProcessor.py', 'big_image.jpg']) Or, the third method also works for me: >>> subprocess.Popen(['python ZoomifyFileProcessor.py big_image.jpg']) But all this works either through the command line or Python shell. Now I want to do the same thing in my Django view (since I want to integrate this functionality with my map application). So, first of all, I created a nice Django project and made my first "Hello world" view, that looks like so: from django.http import HttpResponse def index(request): return HttpResponse("Hello, world") At this stage everything works ok. When I go to the browser, I see … -
Dynamically load data in django template
I am using django to create an application that read data from sql server and show it on the webpage. I want the content to change based on selected options from the drop down. Basically I have written queries ion the model and I want my model to load content dynamically. How can I do that? I am trying to use ajax. -
unexplainable error in Django
When I tried to run $ " python manage.py runserver localhost:8000 ", I get the exception error below. Please Help!!! What am I doing wrong. Request Method: GET Django Version: 1.8.13 Exception Type: TypeError Exception Value: __init__() takes 1 positional argument but 2 were given Exception Location: /usr/local/lib/python3.4/site-packages/django/core/handlers/base.py in get_response, line 132 Python Executable: /usr/local/bin/python3.4 Python Version: 3.4.4 views.py class CreateMsg(CreateView): #model = Visitor form_class = Msg template_name = "message.html" forms.py class Msg(forms.ModelForm): class Meta: model = Visitor fields = ['name', 'contact', 'message'] main/urls.py urlpatterns = [ url(r'^contact/', include('msgapps.urls')), ] msgapps/url.py urlpatterns = patterns( 'msgapps.views', url(r'^msg/$', CreateMsg, name='CreateMsg'), ) -
Display jumbotron with background image
I have started an app with django named 'blog'. The app 'blog' contains 2 folders 'static' and 'templates'. 'static' contains one folder 'blog' which contains 2 folders 'css' and 'img'. The file 'blog.css' is in the folder 'css' and 'epingle.jpg' is in the folder 'img'. 'templates' contains one folder 'blog' with the file base.html on which I am working. In 'blog.css', I have created the class jumbotron as follows: .jumbotron { position: relative; background: #000 url("../img/epingle.jpg") center center; width: 100%; height: 100%; background-size: cover; overflow: hidden; } In 'base.html', I have the following line: <div class="jumbotron"> <div class="container"> <h3>Everything is so easy... when you get some help!</h3> </div> </div> The jumbotron is displayed but not the image. Could you please let me know what I do wrong? Thanks -
Django HVAD and ForeignKey
I have simple app with: class NamedModel(TranslatableModel): code = models.CharField(max_length=120) translations = TranslatedFields( name=models.CharField(max_length=256), description=models.TextField() ) class Meta: abstract = True class Product(NamedModel): translations = TranslatedFields() class Report(TranslatableModel): quantity = models.DecimalField(max_digits=20, decimal_places=6) inv = models.ForeignKey(Inv) translations = TranslatedFields( product=models.ForeignKey(Product) ) And then, from shell I creating some instances: product = Product.objects.language('en').create(name='asd', description='asd', code='asd') inv = Inv.objects.create(code='xxx') report = Report.objects.language('en').create(quantity=1, inv=inv, product=product) And if I type: len(Report.objects.language('en').all()), I get 1, but when I try this: Report.objects.language('en').all() I get: NoTranslationError: Accessing a translated field requires that the instance has a translation loaded, or a valid translation in current language (None) loadable from the database Do you have any advice? -
How to establish a permanent connection between an EC2 and an RDS for data transfer?
I am still learning AWS so this is kind of a basic question, but I've been researching and trying things without any success. I launched an Postgresql RDS on AWS as well as a EC2 Ubuntu server running apache. I wrote some Python code using Django and Django-rest-framework to query the database and return some data to a mobile app. Both the EC2 and RDS are on the same VPC. I was wondering how does one go around establishing a permanent connection between the EC2 and the RDS so that when I query from a web app or a mobile app I get some data back. This is the code I have so far in my views.py from django.shortcuts import render from django.http import HttpResponse from rest_framework.renderers import JSONRenderer from rest_framework.parsers import JSONParser from .models import UserDatabase from .serializers import UserDatabaseSerializer class JSONResponse(HttpResponse): """ An HttpResponse that renders its content into JSON. """ def __init__(self, data, **kwargs): content = JSONRenderer().render(data) kwargs['content_type'] = 'application/json' super(JSONResponse, self).__init__(content, **kwargs) def database_list(request): if request.method == 'GET': database = UserDatabase.objects.all() serializer = UserDatabaseSerializer(database, many=True) return JSONResponse(serializer.data) In my models.py: from django.db import models class UserDatabase(models.Model): """ """ id = models.IntegerField(primary_key=True) email = models.CharField(max_length=320) first_name = … -
django.core.exceptions.FieldError: Unknown field(s) (body ) specified for Comment
I am new to Django, Am receiving error as written in title. i google it but i cant found any thing.actually what i whant to do is just an add "Comment" to my blog site. i add my code as follows. and thank you my files: #form.py from django import forms from django.db import models from blog.models import Comment class EmailPostForm(forms.Form): name = forms.CharField(max_length=25) email = forms.EmailField() to = forms.EmailField() comments = forms.CharField(required=False, widget=forms.Textarea) email = forms.EmailField() to = forms.EmailField() comments = forms.CharField(required=False, widget=forms.Textarea) class CommentForm(forms.ModelForm): class Meta: model = Comment fields = ('name', 'email', 'body ') #models.py from django.db import models from django.utils import timezone from django.contrib.auth.models import User from django.core.urlresolvers import reverse class Post(models.Model): STATUS_CHOICES = ( ('draft', 'Draft'), ('published', 'Published'), ) title = models.CharField(max_length=250) slug = models.SlugField(max_length=250, unique_for_date="publish") author = models.ForeignKey(User, related_name='blog_posts') body = models.TextField() publish = models.DateTimeField(default=timezone.now) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) status = models.CharField(max_length=10, choices=STATUS_CHOICES, default="draft") objects = models.Manager() published = PublishedManager() class Meta: ordering = ('-publish', ) def __str__(self): return self.title def get_absolute_url(self): return reverse('blog:post_detail', args=[self.publish.year, self.publish.strftime('%m'), self.publish.strftime('%d'), self.slug]) class Comment(models.Model): post = models.ForeignKey(Post, related_name='comments') name = models.CharField(max_length=80) email = models.EmailField() body = models.TextField() created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) active = models.BooleanField(default=True) … -
Django-channels ManyToManyField
I would like to put django-channels at use in a case where a relation ManyToMany exist between two models. in models.py class ClassA(models.Model): InstanceD = models.OneToOneField(ClassD, null=True) InstanceC = models.ManyToManyField(ClassC, null=True) service = models.ForeignKey(service) class ClassB(models.Model): InstanceC = models.OneToOneField(ClassC, null=True) InstanceD = models.ManyToManyField(ClassD, null=True) service = models.ForeignKey(service) class ClassC(models.Model): InstanceB = models.OneToOneField(ClassB) InstanceA = models.ManyToManyField(ClassA) class ClassD(models.Model): InstanceA = models.OneToOneField(ClassA) InstanceB = models.ManyToManyField(ClassB) in views.py InstanceA = ClassA.create(attributesNames=attributesValues) InstanceA.save() InstanceBs = ClassB.objects.filter(service=service) InstanceD = ClassD () InstanceD.ClassA = InstanceA InstanceD.ClassB = InstanceBs InstanceD.save() InstanceA.ClassD = ordebookbuyer InstanceA.save() for InstanceB in InstanceBs: InstanceB.ClassD.add(ordebookbuyer) InstanceB.save() return render(request, template.html', {'form': form, InstanceD: InstanceD, InstanceBs: InstanceBs}) in template.html {% for InstanceB in InstanceBs %} <tr> <td>{{ InstanceB }}</td> </tr> {% endfor %} I would like the template to show the updated InstanceBs when the objects of Class A are created/modified/deleted. As django channels (not more than a year of documenttion) is not much older than I am in django (less than 2 month), I am having difficulties finding documentation and guidances on how to proceed... Any help would be much appreciated! -
converting time in django
hi i'm new in working with datetime objects in django all I know now is that instead of python's datetime.datetime.now() we should use django's timezone.now(), i've also set TIMEZONE and USE_TZ=True in settings.py but my problem is now for converting these types of time. as far as I know, even if we use timezone.now() for saving in database, django uses UTC time to store in DB. so I need a simple syntax for converting UTC time into my local time which is set in settings.py and vice versa to get local time from human and return local time. i've also seen that django has some template tags to do that, but since i am doing this mostly for a REST API with django-rest for an android app, i need to be able to do this in python syntax. thanks everyone, I hope I could be clear at what I mean :) -
Django: AutoSlug error "slug is defined before trying to ensure uniqueness"
I have a model with a django-autoslug field: class Article(models.Model): headline = models.TextField() content = models.TextField() slug = AutoSlugField(populate_from='headline', max_length=128, allow_unicode=True, always_update=True) Everything works nice in a dev environment (OS X + Postgres). However, on the deployed instance (Ubuntu + Postgres) an error occurs when trying to create an object using django admin. It occurs only when a headline has Cyrillic in it: AssertionError: slug is defined before trying to ensure uniqueness -
forbidden error when post to API rest
i have a web chatbot application that i created using Django and REST for the API. so i want when the press ENTER the entered text will be POST to the API under the name 'request'. So far this is my code in index.js: $('.message-submit').click(function() { insertMessage(); var post_data = { csrfmiddlewaretoken: '{{ csrf_token }}', request : $('.message-input').val()}; $.ajax({ type: "POST", url: "http://127.0.0.1:8000/chat/api/", data: post_data, dataType: "application/json" }); }); But the error ""POST /chat/api/ HTTP/1.1" 403 58" in red keeps coming up. I've used many solution such as: 1.csrfmiddlewaretoken: '{{ csrf_token }}' 2.@csrf_exempt and non of them in working!! any solution? -
Django, changing form field based on form.instance in admin
I have an admin page that uses inlines. I would like to change a field in the inline form depending on the state of the parent model on the page. Is there a way to check for this in the inline form object? I have a few models that depend on each other. For the sake of fewer clicks, I'd like to be able to create them all at once, but then introduce some user friendly features once database entries exist (i.e., ChoiceField instead of IntegerField for setting Element().quality. #proj/elements/models.py ... class Group(models.Model): """A group of elements""" name = models.CharField(max_length=50) class QualityChoice(models.Model): """Translates quality values to human-readable descriptions within a group""" value = models.SmallIntegerField() name = models.CharField(max_length=50) group = models.ForeignKey(Group, on_delete=models.CASCADE) class Meta: unique_together = ('value', 'group') class Element(models.Model): """An element""" name = models.CharField(max_length=50) quality = models.SmallIntegerField() group = models.ForeignKey(Group, on_delete=models.CASCADE) Here is essentially what I'm trying to do: #proj/elements/admin.py ... class ElementForm(ModelForm): class Meta: model = Element fields = ('name', 'description', 'quality', 'group', 'marker_id') def __init__(self, *args, **kwargs): super(ElementForm, self).__init__(*args, **kwargs) if self.instance.group: # Set quality field to be a select scoped to valid choices # for the group. Assume `choices` is set elsewhere self.fields['quality'] = ChoiceField(choices=choices) class ElementInline(TabularInline): … -
Remapping traffic from one port to another using ATS
I have a django application deployed on port 2501. And I have ATS configured to terminate HTTPS, and act as a reverse proxy and route traffic to 2501; my config looks like so: map https://example.com:443/ http://127.0.0.1:2501/ And this works great, whenever you hit https://... you'll terminate https and traffic gets routed to 2501. But if you visit 2501 you can access the site normally as well. Is it possible to make it so that if you visit 2501 it'll route you back to 443? I tried using reverse_map but it's not working for me (maybe I'm misunderstanding what reverse map does?) reverse_map http://example.com:2501/ https://127.0.0.1:443/