Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Web Dev: Need Advice from a seasoned developer
Recently I've been getting into Django development and I am currently working on creating my own website. As for the static portions of the site, (about section, header, and footer) I am setting everything manually in my html file. Is this typically how professionals go about their business? As for my github repository, I find my self having to create dozens of tedious commits as I troubleshoot (the site is hosted on AWS). Any advice on getting around redundancies in this aspect? -
Insert multiple data in django to django form
I want to insert multiple row into my database from form2. Below are my codes views.py def tambah_siswa(request): form = datasiswa(request.POST) form2 = riwayatsekolah(request.POST) if request.method == 'POST': if form.is_valid() and form2.is_valid(): siiswa_instance = form.save() Sekolah_instance = form2.save(commit=False) Sekolah_instance.SiswaID_FK = siiswa_instance Sekolah_instance.save() return redirect('index') else: form = datasiswa() form2 = riwayatsekolah() return render(request, 'siswa/tambah_siswa.html', {'form': form, 'form2': form2}) and this is my template <tr> <td>{{ form.SiswaNama }}</td> </tr> <tr> <td>{{ form2.SekolahNama }}</td> <td>{{ form2.SekolahThMasuk }}</td> <td>{{ form2.SekolahThKeluar }}</td> <td>{{ form2.SekolahKet }}</td> </tr> How to insert multiple row from form2 into database? when i run this code, it just insert one row. -
How to call Django ManyToMany.add in a save override
When super overriding Django's Model.save, and adding a ManyToMany.add call, it isn't adding the related models, even though it's after the super.save call. Has anyone else encountered this and been able to solve it? Here is the sudo code: class Friend(models.Model): friends = models.ManyToManyField("self") def save(self, *args, **kwargs): super(Friend, self).save(*args, **kwargs) self.do_something() def do_something(self): for friend in Friend.objects.filter(foo=bar): # this 'add' isn't working self.friends.add(self) -
Incompatible oAuth2 token requests between python oauth2 request and spring oauth2 server
My python oauth2 client is attempting to fetch an access_token via python requests to a 3rd party using spring oauth via a token code. auth_session = OAuth2Session( self.configuration_store.client_id, redirect_uri=self.configuration_store.redirect_url) auth_session.fetch_token( self.configuration_store.token_url, client_secret=self.configuration_store.client_secret, code=code, headers=utils.generate_header(self.configuration_store.client_id, self.configuration_store.client_secret), **{"access_token": "TOKEN", "token_type": "bearer", "expires_in": 3599, 'scope': 'bar read write'}) Using the same code against our local test server using django oauth toolkit implementation, the above code successfully retrieves a token. However, against the spring provider, returning a 401. Furthermore, if I construct the request to the 3rd party manually using straight python requests, I can get success. result = requests.post(self.configuration_store.token_url, params = {'grant_type':'authorization_code', 'client_id': self.configuration_store.client_id, 'code':code, 'client_secret':self.configuration_store.client_secret, 'redirect_uri':self.configuration_store.redirect_url }, headers =utils.generate_header(self.configuration_store.client_id, self.configuration_store.client_secret), data={"access_token": "TOKEN","token_type": "bearer","expires_in": 3599,"scope": ["bar", "read", "write"]}) However the POST requests are completely different. Working requests using request.post... # Working INFO 2016-11-28 08:19:15,303 connectionpool 50122 123145426345984 Starting new HTTPS connection (1): example.com send: b'POST /authorization/oauth/token?redirect_uri=https://theredirecturl.com/login&client_secret=XXXXXXXXXXXX&code=XXXXXXX&grant_type=authorization_code&client_id=clientid HTTP/1.1 Host: example.com Accept: */* Content-Length: 85 Connection: keep-alive Accept-Encoding: gzip, deflate Content-Type: application/x-www-form-urlencoded User-Agent: python-requests/2.9.1 Authorization: Basic XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX= Cache-Control: no-cache scope=bar&scope=read&scope=write&token_type=bearer&access_token=TOKEN&expires_in=3599' reply: 'HTTP/1.1 200 OK ' Not working using oauth python requests INFO 2016-11-29 23:32:18,063 connectionpool 73412 123145511739392 Starting new HTTPS connection (1): example.com send: b'POST /authorization/oauth/token/ HTTP/1.1 Host: example.com Authorization: Basic XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX= Connection: keep-alive Content-Length: … -
How do I create property for objects in views.py in order to pass changed object to JS code
I load "endless scroll" feed via AJAX and pagination. Before passing objects to JS code, I need to add property to every object, which contains boolean, whether it was liked by current user or not. I thought it might work but something is wrong, because everything is getting undefined in frontend. How do I implement what I want in the right way? def loadmore(request,page_number): answers_to_questions_objects = Question.objects.filter(whom=request.user.profile).filter(answered=True).order_by('-answered_date') paginator = Paginator(answers_to_questions_objects,10) current_page = (paginator.page(page_number)) for item in current_page: if request.user.profile in item.who_liked.all(): item.liked = True else: item.liked = False print(current_page.liked) answers = serializers.serialize('json', current_page) data = { 'answers': answers, } return Response(data) -
add help text to a read only field in django admin view
Below is my admin view: @admin.register(AuditStashAwsMasterPolicies) class AuditPoliciesAdmin(reversion.VersionAdmin): exclude = ['source_policy_path', 'source_state', 'target_state'] readonly_fields = ['comparison_date', 'source', 'source_policy_name', 'target', 'target_policy_name', 'target_policy_path', 'policy_difference'] def policy_difference(self, instance): return drift.compare_two_policies(instance.source, instance.source_policy_name, instance.source_policy_path, instance.target, instance.target_policy_name, instance.target_policy_path) What I want to do is add some help text to my 'policy_difference' read only field. From the help documentation, I am only able to do this by modifying the model and creating a read-only field there with help text. The thing is I don't store any values in the 'policy_difference' field I just generate it on the fly and would like to avoid storing it in the model. Is there any way to add text to the 'policy_difference' read-only field without changing the model AuditStashAwsMasterPolicies? -
Show status messages from script running on AWS EC2 instance on Heroku Django application?
I am running a django application on heroku and a script (bot) on an aws ec2 instance (heroku has a time limit on how long a script can run). The bot on the ec2 instance prints messages to show its progress. How can I display on the front end of the heroku application the messages i print from the bot on the ec2 instance? (I want to use toastr to display these messages) -
How to label a form instance within a django inline formset?
I have what I think is a common enough situation, but can't seem to get my head around it. I've used the inlineformset_factory to create a formset of forms which allow the user to alter aspects of a foreign key object, and these are working fine. The trouble is that I want to be able to label each of these forms within the formset (note, not fields within each form, but the foreign key model on which each form is based). For example, if I tweak the example in the docs: from django.db import models from django.forms import inlineformset_factory class Author(models.Model): name = models.CharField(max_length=100) class Book(models.Model): author = models.ForeignKey(Author, on_delete=models.CASCADE) title = models.CharField(max_length=100) pages = models.IntegerField(default=0) I create my formset to allow people to change the number of pages in any book by Daffy Duck: BookFormSet = inlineformset_factory(Author, Book, fields=('pages',)) author = Author.objects.get(name='Daffy Duck') formset = BookFormSet(instance=author) Say Daffy has written five books, these show up as integer entries all labelled "Pages", with no reference to which book each points to. How can I label the form with the title of the book so that they know which one they're changing? I've tried passing a dictionary to the labels field … -
Django: Extend jQuery CDN from base
I thought that by just including jQuery from CDN in base.html, it will be defined in all html pages that extend the base, like when including from static files, without repeating <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script> Does {% extends 'base.html' %} have some limits? -
Python PIllow with Django .thumbnail not respecting the sizes I declare
I'm trying to resize images with Pillow but it is not working correctly, I always get a very small image. I need three different sizes, that is why I'm doing this: Save Base64 Images cover = Image.open(StringIO.StringIO((base64.b64decode(cover_image_64)))) cover_original = cover cover_small = cover cover_medium = cover small_size = ProductCover.IMAGE_SIZES["small"] medium_size = ProductCover.IMAGE_SIZES["medium"] print(small_size) print(medium_size) HERE-> cover_small.thumbnail(small_size, Image.ANTIALIAS) cover_medium.thumbnail(medium_size, Image.ANTIALIAS) original_image_file = StringIO.StringIO() small_image_file = StringIO.StringIO() medium_image_file = StringIO.StringIO() cover_small.save(small_image_file, format="JPEG") cover_medium.save(medium_image_file, format="JPEG") cover_original.save(original_image_file, format="JPEG") ProductCover.objects.create(product=product, original=InMemoryUploadedFile(original_image_file, None, "cover_original.jpg", "image/jpeg", original_image_file.len, None), medium=InMemoryUploadedFile(medium_image_file, None, "cover_medium.jpg", "image/jpeg", medium_image_file.len, None), small=InMemoryUploadedFile(small_image_file, None, "small_small.jpg", "image/jpeg", small_image_file.len, None)) The print statements print this to the console: (60, 60) (512, 512) Why then I get three 60*60 images? The code seems so straightforward and simple that I'm completely lost. Maybe its Django. I don't know. -
Django Redirects Causing Migration Error
I recently updated my local database to mirror production and now I am having migration issues. Trying to migrate an application called events: ./manage.py migrate events NoMigrations: Application '<module 'django.contrib.redirects' from '/Users/my_username/.virtualenvs/my_website/lib/python2.7/site-packages/django/contrib/redirects/__init__.pyc'>' has no migrations. I don't understand what is happening here. Why is it looking for migrations in the environment files? The migration has no problem running in production. Our site is running in Django 1.5. Also, the south_migrationhistory table does have the 0001_initial migration for redirects. -
How do you access a Django JSONField's keys using `django.models.F` or similar method during a query?
Is it possible to extract a sub-key from a JSONField field and annotate the Queryset with its value? I'm trying to extract the value within the query rather than post-processing in the Python code. Model architecture is: Django 1.10 Model has a django.contrib.postgres.fields.JSONFieldcalleddata` to store an API response. This example is Twitter. Other fields are profile_id and screen_name. The rest of the data lives within the data field so it can be queried ad-hoc. I thought I'd be able to combine annotate and django.models.F but I'm getting the following error: > models.TwitterUser.objects.annotate(foll_count=F("data__followers_count")) Traceback (most recent call last): File "<console>", line 1, in <module> File "/Virtualenv/env_name/lib/python3.5/site-packages/django/db/models/manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/Virtualenv/env_name/lib/python3.5/site-packages/django/db/models/query.py", line 914, in annotate clone.query.add_annotation(annotation, alias, is_summary=False) File "/Virtualenv/env_name/lib/python3.5/site-packages/django/db/models/sql/query.py", line 971, in add_annotation summarize=is_summary) File "/Virtualenv/env_name/lib/python3.5/site-packages/django/db/models/expressions.py", line 463, in resolve_expression return query.resolve_ref(self.name, allow_joins, reuse, summarize) File "/Virtualenv/env_name/lib/python3.5/site-packages/django/db/models/sql/query.py", line 1462, in resolve_ref self.get_initial_alias(), reuse) File "/Virtualenv/env_name/lib/python3.5/site-packages/django/db/models/sql/query.py", line 1402, in setup_joins names, opts, allow_many, fail_on_missing=True) File "/Virtualenv/env_name/lib/python3.5/site-packages/django/db/models/sql/query.py", line 1370, in names_to_path " not permitted." % (names[pos + 1], name)) django.core.exceptions.FieldError: Cannot resolve keyword 'followers_count' into field. Join on 'data' not permitted. This isn't explicitly documented anywhere so I'm attempting to reverse engineer it using the double underscores … -
Django: Having arbitrary file access models
Seems like a really simple issue I am having, but for whatever reason I cannot get an arbitrary file i create within a Django app to access my models/compile. analytics/ analytics/ settings.py etc... mapper/ models.py views.py filetoDothings.py I would like "fileToDoThings.py" do things with my models, but when i put even a few simple lines of code in filetodothings, and try to import the models i get the following error: "Requested setting DEFAULT_INDEX_TABLESPACE, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure()" A lot of searching has led me to find answers similar to this: sys.path.append("path/toproject") os.environ["DJANGO_SETTINGS_MODULE"] = "myApp.settings" from django.contrib.auth.models import ModelName This worked, but only when i moved the arbitrary file to the outermost "analytics" directory. Even though I got this to work, it never quite seemed to make sense to me/seemed like a lot of work to get a file to access models in the same directory. So what I am trying to do now is the following, in filetoDothings.py: from models import Addresses usaMapPoints = Addresses.objects.filter(countryCode='US').order_by("-frequency")[:25] print(usaMapPoints) For "messing around" purposes, I want to call "python filetodothings.py" and have it print the results in the console. But ultimately Im … -
Django prepending www to all urls
I need to redirect all http://example.com/<'path'> urls to http://www.example.com/<'path'>. Tried to use the following in my settings.py: ALLOWED_HOSTS = ['www.example.com', 'example.com'] MIDDLEWARE_CLASSES = ( 'django.middleware.common.CommonMiddleware', ) PREPEND_WWW = True It did't work. In case of @ page it's possible to set the redirect in the DNS settings but I don't know how to prepend "www" to all the other URLs that the web-site generates. Any help is appreciated. -
Django formModel's fields conflict
I have two models and two modelForms: class Email(models.Model): # .... is_main = models.BooleanField(default=False, blank=True) class PhoneNumber(models.Model): # .... is_main = models.BooleanField(default=False, blank=True) class EmailForm(ModelForm): class Meta: model = Email fields = ['email', 'email_type', 'is_main'] class PhoneNumberForm(ModelForm): class Meta: model = PhoneNumber fields = ['phone_number', 'phone_number_type', 'is_main'] Also i have a template: <form> {{ email_form }} {{ number_form }} </form> Django rendering a template with two the same id's and label's for field is_main. And they conflict to each other. How i can fix it without renaming is_main? -
Django 1.10: "new style" middleware equivalent of `process_request()`
How would one create "new style" middleware, which fulfills an equivalent implementation to using the process_request() hook with the "old style"? I've already adapted pre 1.10 middleware process_request() using MiddlewareMixin... from django.utils.deprecation import MiddlewareMixin class MyCustomMiddleware(MiddlewareMixin): def process_request(self, request): # My request logic return response I'd like to know how to do a "pure" >1.9 "new style" implementation. I tried doing so by implementing __init__() and __call__() like this without luck: class MyCustomMiddleware(object): def __init__(self, get_response): self.get_response = get_response def __call__(self, request): # My request logic return response Thanks. -
Django View Testing Returning 301 or not found
I'm trying to test the response code of a view, but I'm either getting a 301 or does not exist. urls.py ... url(r'^myview/(?P<view_id>.*)/$', view_myview.index, name='myview'), ... Test code 1: import unittest from django.test import Client class SimpleTest(unittest.TestCase): def setUp(self): self.client = Client() def test_details(self): response = self.client.get('/myview/123') self.assertEqual(response.status_code, 200) The above code gives: AssertionError: 301 != 200 Test code 2: import unittest from django.test import Client class SimpleTest(unittest.TestCase): def setUp(self): self.client = Client() def test_details(self): response = self.client.get('/myview/123/') self.assertEqual(response.status_code, 200) The above code gives: Mymodel matching query does not exist. All I want to do is simple testing of my views to ensure they aren't throwing an error code, but I can't seem to find the right way to do it and I've tried many, many suggestions from the internets. Is there a different way to pass in view_id? What if I also want to throw in some query parameters? -
calling function in python script from javascript
i'm developing web base chatbot , using Django with its CSS and JS files.i have a previous python script for a chat bot application that i used to run in the terminal. Now what I want is connecting between the JS and python script, where the JS catch the user input and send it to a function in the python file and it will return the generated reply to be displayed. Any ideas?! thank you, -
Django views accessible in the admin site
I would like to embed front end views in my django admin site at any possible specified locale, maybe in a class or site admin dashboard;anywhere I feel is the best option.. Tried out a few git projects but seems they are not compatible with current django versions..any one offering any idea?! -
django ImageField empty after form post
when i upload photo to django through form the image field is empty , i confirmed this by using logging.info(form.cleaned_data['picture'] ) i checked through the console that the form has 'multipart/form-data' the model : class Person(models.Model): user = models.ForeignKey(User, default=1) name = models.CharField(max_length=250,null=True) last_name = models.CharField(max_length=500) treatment_plan=models.CharField(max_length=256,null=True,blank=True) treatment_done=models.CharField(max_length=256,null=True,blank=True) picture = models.ImageField(upload_to='image', storage=DEFAULT_FILE_STORAGE,blank=True) def __str__(self): return self.name the modelForm : class PersonForm(forms.ModelForm): class Meta: model = Person fields = ['name', 'last_name', 'age', 'martial_status', 'mobile', 'sex', 'amount_paid','amount_left','note', 'address','date','picture','treatment_done','treatment_plan','chief_complain'] widgets = { 'name': forms.TextInput(attrs={'required': True, 'class': 'form-control', 'placeholder': 'name'}), 'last_name': forms.TextInput(attrs={'required': True, 'class': 'form-control', 'picture': forms.FileInput(attrs={'required': False,'class': 'form-control','enctype': 'multipart/form-data'}), view.py : def add_person(request): if not request.user.is_authenticated(): return render(request, 'core/login.html') else: form = PersonForm(request.POST or None,request.FILES or None,instance=Person()) #form = PersonForm(request.POST or None,request.FILES ) if form.is_valid(): persons = form.save() persons.user = request.user #to captilized the first litter so we have consistancy when quering , this is a workarround since __iexact is not working persons.name=persons.name.title() persons.last_name=persons.last_name.title() logging.info(form.cleaned_data['last_name'] ) persons.save() return redirect('home') context = { "form": form, } return render(request, 'core/add_person.html', context) the html template : <div class="col-sm-4 form-group"> <label for="address">{% trans "Address" %}</label> {{ form.address|add_class:"form-control" }} </div> <div class="col-sm-4 form-group"> <label for="pic">{% trans "Picture" %}</label> {{form.picture}} </div> -
Adding a composite field to a django model
I'm working on a blog in Django where I have the following model for blog posts: class BlogPost(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, default =1) title = models.CharField(max_length = 120) image = models.ImageField(upload_to= upload_location, null = True, blank = True, width_field = "width_field", height_field = "height_field") slug = models.SlugField(unique=True) height_field = models.IntegerField(default= 0) width_field = models.IntegerField(default= 0) draft = models.BooleanField(default=False) publish = models.DateField(auto_now = False, auto_now_add= False) content = models.TextField() timestamp = models.DateTimeField(auto_now = False, auto_now_add = True) update = models.DateTimeField(auto_now = True, auto_now_add = False) Each blog post needs to have certain tags associated with it (one word descriptions of the content of the post). Currently I have a tag model and a tag relation which maps each post to any number of tags. In the create post page I have two forms, one for the blog post model and one for the tags model as this allows me to map each post to multiple tags. The issue with this implementation is that when the form for the blog post is submitted, a foreign key needs to first be created for each tag and the blogpost in the tagged_with relation table and then the tag form can subsequently be submitted. I … -
control navbar swich django
I'm working on a project and I'm trying to control navbar logo color change, after you visit about page on my app, navbar should change color and half off it needs to be yellow so it will reflect on the purple background properly. This project is build in django and I'm including my navbar inside my base template using standard template tag {% include 'navbar.html' %}, and I'm {extends 'base.html' %} to about page, standard django template inheritance, but I'm failing to understand how can I control my navbar logo, so is there a way that I can control this, and how, can I restrict my navbar to just one template? -
Which django form field type should I use for an array of values?
I'm receiving an array of up to N uuid4 values in the POST data for a SPA. I'm then supposed to be feeding into a view that deletes the specified object instances: uuids = [ a1a241bd-147f-4672-86d7-1a6225b8080e 791db3f0-5134-4927-b328-347c7261d7f6 b8087a1b-710e-47b4-af5a-bae4d5e30532 6d1a96b2-1b99-4707-a8e3-376a0d596d95 ... ] As far as I can tell, it probably isn't the intent of MultiValueField to handle this data because I don't want to "compress" it. What's the django way of dealing with form data like this? Should I be manually trying to process request.POST myself and running each uuid through a form to validate it? Or overriding form.clean()? -
Django on Heroku: error=H10, no module named Django
From the last 2 hours I am trying to deploy my Django project on Heroku. I have read solution to all similar problems but I am still seeing the following error on doing heroku logs: ImportError: No module named 'django' 2016-11-29T18:26:33.959843+00:00 app[web.1]: [2016-11-29 18:26:33 +0000] [4] [INFO] Reason: Worker failed to boot. 2016-11-29T18:26:34.092546+00:00 heroku[web.1]: State changed from starting to crashed 2016-11-29T18:26:34.083366+00:00 heroku[web.1]: Process exited with status 3 2016-11-29T18:26:37.057428+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=intense-thicket- 88077.herokuapp.com request_id=6ec39e42-b2b4-486d-8211-7b6ed096eb67 fwd="202.142.70.146" dyno= connect= service= status=503 bytes= 2016-11-29T18:28:10.720588+00:00 heroku[run.5806]: Awaiting client 2016-11-29T18:28:10.680678+00:00 heroku[run.5806]: State changed from starting to up 2016-11-29T18:28:40.724034+00:00 heroku[run.5806]: Error R13 (Attach error) -> Failed to attach to process 2016-11-29T18:28:40.728213+00:00 heroku[run.5806]: Process exited with status 128 2016-11-29T18:28:40.741231+00:00 heroku[run.5806]: State changed from up to complete 2016-11-29T18:31:26.538645+00:00 heroku[run.4330]: Awaiting client 2016-11-29T18:31:26.740288+00:00 heroku[run.4330]: State changed from starting to up 2016-11-29T18:31:56.547335+00:00 heroku[run.4330]: Error R13 (Attach error) -> Failed to attach to process 2016-11-29T18:31:56.547335+00:00 heroku[run.4330]: Process exited with status 128 2016-11-29T18:31:56.572416+00:00 heroku[run.4330]: State changed from up to complete 2016-11-29T18:43:50.795965+00:00 heroku[web.1]: State changed from crashed to starting 2016-11-29T18:43:54.458675+00:00 heroku[web.1]: Starting process with command `gunicorn sachin_test_app.wsgi --log-file -` 2016-11-29T18:43:56.697645+00:00 app[web.1]: [2016-11-29 18:43:56 +0000] [4] [INFO] Starting gunicorn 19.6.0 2016-11-29T18:43:56.698106+00:00 app[web.1]: [2016-11-29 18:43:56 +0000] [4] [INFO] Listening at: http://0.0.0.0:13028 … -
django wizard view - doesn't process unique constraints until final form submitted
I've been testing out using django wizard view from django formtools (previously in core django). I using it for a mutlti form signup process. However although some validations for fields are processed after each form/page is submitted and fields with unique constraints eg username and unique together constraints (house/no & postcode/zip) don't seem to be checked until the last form is submitted. Is there a way round this?