Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
400 (Bad Request) from Django Ajax POST Request
I have read countless SO threads regarding this issue, but I cannot get my form to submit without producing a 400 (Bad Request) console error. I've tried everything at this point; too many options to list. I'm hopeful someone can point me in the right direction. Below are my code pieces - I've included all the relevant pieces. Thank you. Django==1.10.3 jQuery==2.2.4 tag.py @register.inclusion_tag('tags/_plaque-order-form.html', takes_context=True) def plaque_order_form(context): title = 'Plaque Order Form' form = PlaqueOrderForm() context = { 'form': form, 'title': title, } return context Order Form <form action="{% url 'contribute:plaque_order_form' %}" method="POST" id="plaqueOrderForm"> {% csrf_token %} {% for field in form %} {{ field }} {% endfor %} <button class="btn btn-black no-margin-bottom btn-small" type="submit" id="plaqueOrderFormBTN">Submit</button> </form> Url urlpatterns = [ url(r'^$', index, name='home'), url(r'^plaque_order_form/$', plaque_order_form, name='plaque_order_form') ] Insert form in template as a tag inclusion {% plaque_order_form %} view def plaque_order_form(request): if request.method == "POST": form = PlaqueOrderForm(request.POST) if form.is_valid(): first_name = form.cleaned_data['first_name'] last_name = form.cleaned_data['last_name'] subject = 'New Plaque Order' from_email = settings.DEFAULT_FROM_EMAIL recipient_list = [from_email, 'chris@somewhere.net'] ctx = { 'subject': subject, 'first_name': first_name, 'last_name': last_name } message = get_template('email_forms/plaque_order_form_email.html').render(Context(ctx)) msg = EmailMessage(subject, message, from_email=from_email, to=recipient_list) msg.content_subtype = 'html' msg.send() messages.success(request, "Thank you for your order; someone will … -
Python - find first dictionary key in template
I'm trying to show my dictionary keys and values in template in for loop, but I don't want to show the first key. What is the best way to do it? I thought of using something like dictionary.keys()[0] but i can't do it in template. or maybe add counter to the for loop (not sure how to do it in the loop below) This is my loop to show the dictionary- {% for year, durations in durationDict.items %} <optgroup label={{ year }}> {% for duration in durations %} <option data-from-date="{{ duration.from_date }}" data-to-date="{{ duration.to_date }}" value={{ duration.duration_id }}>{{ duration.from_date }} - {{ duration.to_date }}</option> {% endfor %} {% endfor %} -
Django-Leafet map - get Points from a Postgres DB
I have records with lat and lngs in a Postgresql database and I want to add them to a Leaflet map as markers. i am pretty new to python and js. I am using python 3.4, django 1.10, Postgresql 9.3 do i have to make a json from the db record and use ajax to load the json? like in this example done with php $.ajax({ type: "GET", url: "./geojson.php", dataType: "geojson", success: function(response) { L.geoJson(response, { onEachFeature: onEachFeature }).addTo(map); } }).error(function() {}); -
How to drop MongoDB field using PyMODM and Django
How can I drop/delete a field from the document when it is already created using PyMoDM? I have following model: class User(MongoModel): email = fields.EmailField(required=True) password = fields.CharField(required=True) first_name = fields.CharField(required=True) last_name = fields.CharField(blank=True) I have a user with all the fields. After deleting last_name from the model next "get" throws an error: ValueError: Unrecognized field name 'last_name' user = User.objects.get({'email': email.lower()}) -
How to find a code/method with the longest execution time
Couple of pages in my Django project are very slow to load (5 - 10 seconds). I'm trying yo figure out where the problem is. The first thing I did was to run debugger with breakpoints on functions in those views. And I found the slowest ones. But to go deeper, I would have to debug all of these functions one by one so I decided to use a Pycharm profiler. When I run it and take a snapshot and load some of those slow pages and then take snapshot too, those snapshots are the same. Do I do something wrong? After starting a server: After loading some page: I expected an execution tree with execution times. -
Django internalization - changing current language does not work
I want to localize my REST app, and have read the doc. Seems like I've done everything accordingly, and yet can't get the message in my exception appear in Russian on client side. The view: @api_view(['POST']) def foo(request): if serialized.is_valid(): activation_key = hashlib.sha1(str(random.random())).hexdigest()[:5] email = request.data['email'] user_language = 'ru' translation.activate(user_language) request.session[translation.LANGUAGE_SESSION_KEY] = user_language try: # SMTPRecipientsRefused error generating code except SMTPRecipientsRefused: return Response({'msg': _('Invalid email address'), 'object': None}, status=status.HTTP_400_BAD_REQUEST) # ... And here's what I have done to tackle localization. Set up gettext for Windows downloading the corresponding files from this source Ran the django-admin compilemessages command and successfully generated the .po files Opened the generated .po file and filled in the necessary translation The .po file looks like this: # SOME DESCRIPTIVE TITLE. # Copyright (C) YEAR THE PACKAGE'S COPYRIGHT HOLDER # This file is distributed under the same license as the PACKAGE package. # FIRST AUTHOR <EMAIL@ADDRESS>, YEAR. # #, fuzzy msgid "" msgstr "" "Project-Id-Version: PACKAGE VERSION\n" "Report-Msgid-Bugs-To: \n" "POT-Creation-Date: 2017-01-04 19:49+0400\n" "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" "Last-Translator: FULL NAME <EMAIL@ADDRESS>\n" "Language-Team: LANGUAGE <LL@li.org>\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" "Plural-Forms: nplurals=4; plural=(n%10==1 && n%100!=11 ? 0 : n%10>=2 && n" "%10<=4 && (n%100<12 || n%100>14) ? 1 … -
Save the file for a FileField without a form
I need to save the file for a FileField object which gets its name and content not from a form (but from my code). How? I need something like: field = FileField() ... save_under_name(field, name, content_bytes) How to write this function save_under_name? Also I need to get the link to the saved filename. -
Get name of a form submit button Django
I have an array of forms. When the user click to submit one of those forms i want identify which one he decided to submit. So I have an array of names to name all my submit buttons : {% for n in db %} ... <input type = 'submit' name = '{{ n.movie_id }}' value = 'ok' /> {% endfor %} I'd like to get this name in my view to create objects in my database. Is there a way to do it ? -
Windows PowerShell - Set-Execution Unrestricted
Is it safe to Set-Execution Unrestricted? When I attempt it warns me: The execution policy helps protect you from scripts that you do not trust. Changing the execution policy might expose you to the security risks ... I am doing this as part of a tutorial on Django where I need to use a virtual environment and it gives the following error: activate.ps1 cannot be loaded because running scripts is disabled on this system Which I googled a solution for entailing a Execution Policy Change. -
Django import error from django.db.models.expressions
When I try to get all my objects of a model, the following exception is raised: from django.db.models.expressions import OrderBy, Random, RawSQL, Ref ImportError: cannot import name OrderBy That's my input: Page.objects.all() #Page is a model And that's my models.py: from django.db import models class Answer(models.Model): choice_text = models.CharField(max_length=1000) information_text = models.CharField(max_length=3000) class Page(models.Model): image = models.ImageField(upload_to='images') icon = models.ImageField(upload_to='images') header = models.CharField(max_length=1000) question = models.CharField(max_length=1000) answers = models.ForeignKey(Answer) What am I missing here? I'm new to Django. Thanks in advanced. -
'utf8' codec can't decode byte 0xb5 in position 0: invalid start byte
Before marking this as a duplicate, I want to make it clear that I have tried countless solutions to make this go away, by using from __future__ import unicode_literals to every pertumations and combinations of str.encode('utf8') and str.decode('utf8'), putting # -*- coding: utf-8 -*- at the start of the file and what not. I know I'm getting something wrong so I'll be as specific as possible, I'm converting a dictionary into a JSON Array/Object and showing it in it's raw string form on the webpage. The unicode string which I'm having issue is the one starting with "µ" in a file name, thus the error occurs at the last fourth line in the below code. The files array is showing the value at the index of that string as \xb5Torrent.lnk. if os.path.isdir(finalDirPath): print "is Dir" for (path,dir,files) in os.walk(finalDirPath): if dir!=[]: for i in dir: if not hidden(os.path.join(path,i)): # Here JSONarray.append({"ext":"dir","path":b64(os.path.join(path,i)),"name":i}) if files!=[]: for i in files: if not hidden(os.path.join(path,i)): # Here JSONarray.append({"ext":i.split('.')[-1],"path":b64(os.path.join(path,i)),"name":i}) break jsonStr = {"json":json.dumps(JSONarray)} return render(request,"json.html",jsonStr) -
Override save method to add list in the many to many field
I have this model to save post from the users: class Tag(models.Model): name = models.CharField(max_length=255, unique=True) class Post(models.Model): user = models.ForeignKey(User) body = models.TextField() tags = models.ManyToManyField(Tag, blank=True, null=True) pub_date = models.DateTimeField(default=timezone.now) activity = GenericRelation(Activity, related_query_name="posts") def save(self, *args, **kwargs): if self.body: tag_list = [word for word in self.body.split() if word.startswith("#")] self.body = tag_list self.tags.add(*tag_list) super(Post, self).save(*args, **kwargs) So whenever a user post something, I would like to check if there's any hash-tag used inside the body. If there are tags, then fetch the tags inside the list. But when I am posting, I get this error: "<Post: user@gmail.com :- [u'#from', u'#hell']>" needs to have a value for field "post" before this many-to-many relationship can be used. What am I doing wrong here? Would you please help me. -
django-allauth Not Saving first_name and last_name
So I have django-allauth installed, but for some reason first_name and last_name are not saved when a user registers. Any ideas? settings.py LOGIN_URL = 'ra_app:index' LOGIN_REDIRECT_URL = 'ra_app:index' ACCOUNT_LOGIN_REDIRECT_URL = 'ra_app:index' ACCOUNT_LOGOUT_REDIRECT_URL = 'ra_app:index' ACCOUNT_AUTHENTICATION_METHOD = 'email' ACCOUNT_EMAIL_REQUIRED = True # Used in conjuction with ACCOUNT_AUTHENTICATION_METHOD to ensure ability to login ACCOUNT_USERNAME_REQUIRED = False # Used in conjuction with ACCOUNT_AUTHENTICATION_METHOD to ensure ability to login ACCOUNT_LOGOUT_ON_GET = True # Logout without confirmation forms.py hide_required_text = { 'required': '', } class MySignupForm(SignupForm): """ This form only used for django-allauth package (called in Settings.py) """ first_name = forms.CharField(error_messages=hide_required_text, max_length=30, widget=forms.TextInput(attrs={'placeholder': 'First Name*'})) last_name = forms.CharField(error_messages=hide_required_text, max_length=30, widget=forms.TextInput(attrs={'placeholder': 'Last Name*'})) username = forms.CharField(error_messages=hide_required_text, max_length=30, widget=forms.TextInput(attrs={'placeholder': 'Username*'})) email = forms.EmailField(error_messages=hide_required_text, max_length=30, widget=forms.TextInput(attrs={'placeholder': 'Email*'})) password1 = forms.CharField(error_messages=hide_required_text, max_length=30, widget=forms.PasswordInput(attrs={'placeholder': 'Password*'})) password2 = forms.CharField(error_messages=hide_required_text, max_length=30, widget=forms.PasswordInput(attrs={'placeholder': 'Confirm Password*'})) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['first_name'].label = '' self.fields['last_name'].label = '' self.fields['email'].label = '' self.fields['password1'].label = '' self.fields['password2'].label = '' self.helper = FormHelper() self.helper.layout = Layout( Div('first_name', css_class='col-md-6'), Div('last_name', css_class='col-md-6'), Div('username', css_class='col-md-12'), Div('email', css_class='col-md-12'), Div('password1', css_class='col-md-6'), Div('password2', css_class='col-md-6'), HTML('<div class="col-md-12"><br></div>'), FormActions( Submit('submit', 'GET STARTED', css_class='btn btn-signup btn-block', style='padding:15px;font-size:1.25em;font-weight:bold;'), ) ) html <form method="POST" action="{% url 'account_signup' %}"> {% if redirect_field_value %} <input type="hidden" name="{{ redirect_field_name }}" value="{{ … -
Static files are not loaded after folder relocation and can't open manage.py Django 1.8
While developing django project locally I hade my static folder in django_project/app_folder/. Later, when I wast learning how to deploy, I found that in all examples/tutorials static folder is normally located in django_project/. So I decided also to move the folder locally from django_project/app_folder/ to django_project/. Settings are still the same: STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') Static files seemed to be loaded fine when I migrated and ran the server first time after relocation, but later I ran server and static files didn't load. I have also accidentally did run python manage.py collecstatic in local development and got the following error after next attempt to run server : /Library/Frameworks/Python.framework/Versions/3.5/Resources/Python.app/Contents/MacOS/Python: can't open file 'manange.py': [Errno 2] No such file or directory Why static is not loaded ? And how to fix -
numpy python3.5 error how to fix this?
Hello i have a error how to fix python3.5 I have tried to install the numpy and it is not fixed This is the error -
one-to-one relation from different models with reverse access
I need to relate a model(e.g. Ad) to multiple possible models (based on Ad type) And I need to be able to refer to this related model(Rent or Purchase) from my Ad object. these possible models can have different fields and I dont want to add a reverse related_name and make multiple null fields in every record of my table. I have the following structure now. class Ad(models.model): submit_date = models.DateTimeField(auto_now_add=True) title = models.CharField(max_length=100) . . . description = models.TextField() class Rent(models.Model): models.OneToOneField( Ad, on_delete=models.CASCADE, primary_key=True, ) deposit = models.BigIntegerField() monthly_rent = models.PositiveIntegerField() class Purchase(models.Model): models.OneToOneField( Ad, on_delete=models.CASCADE, primary_key=True, ) price = models.BigIntegerField() price_per_squaremetter = models.PositiveIntegerField() but with this structure, with multiple models pointing to one model, adding a "related_name" argument to these OneToOneFields seems impossible. I even tried to use generic relations with ContentType but still its not working as expected. Is there a concept that I'm not aware of? Is there any way to achieve this without generic relations? Is there any way to access something like Ad_object.related_model.deposit or Ad_object.related_model.price , based on the model which is related to this Ad_object? -
Using BigQuery with AppEngine conflicting in package google
I am trying to add BigQuery to a Django-AppEngine project and I am finding a lot of problems in doing that since the google library for BigQuery documentation use a package named google and this folder is already in use for AppEngine purposes. What I find now is that, if I install BigQuery, it will overwrite this package and then nothing works! The content of the two google packages Is there maybe someone who faced this problem before and has any idea how to solve this? It is some way to combine existing folders using pip or something else? Thanks!! -
Django extending from included template
I want to divide my base.html template into 2 with some differences in style and html. My structure is like this: base.html <html> <head> <p>same content for both templates</p> </head> {% if category.title == 'something' %} {% include "base-copy.html" %} {% else %} <body> <p>content</p> . . . </body> {% endif %} </html> base-copy.html <body> <p>content</p> . . . </body> inside the body content there are several blocks and other templates extend from base.html {% extends "base.html" %}. If i just copy the whole block of code from body into the included template the content is not showing but if I leave it on the original base.html the content is showing... Btw I'm using the include statement because otherwise I get the "block" appears more than once error from Django... any suggestions on how to make this work? -
502 Bad Gateway Django Nginx Gunicorn
I'm trying to run a django website on a server through nginx and gunicorn. I followed these instructions to get setup but I'm receiving a bad gateway error when I google my ip. If anyone can help thanks so much! Best, Evvan https://www.digitalocean.com/community/tutorials/how-to-set-up-django-with-postgres-nginx-and-gunicorn-on-ubuntu-16-04 Also when I do status of nginx and gunicorn I get: derians@myCodingBlog:~$ sudo systemctl status nginx [sudo] password for derians: nginx.service - A high performance web server and a reverse proxy server Loaded: loaded (/lib/systemd/system/nginx.service; enabled; vendor preset: enabled) Active: active (running) since Tue 2017-01-03 23:50:52 UTC; 15h ago Main PID: 28998 (nginx) Tasks: 2 Memory: 2.1M CPU: 163ms CGroup: /system.slice/nginx.service |-28998 nginx: master process /usr/sbin/nginx -g daemon on; master_process on `-28999 nginx: worker process Jan 03 23:50:52 myCodingBlog systemd[1]: Stopped A high performance web server and a reverse proxy server. Jan 03 23:50:52 myCodingBlog systemd[1]: nginx.service: Unit entered failed state. Jan 03 23:50:52 myCodingBlog systemd[1]: nginx.service: Failed with result 'timeout'. Jan 03 23:50:52 myCodingBlog systemd[1]: Starting A high performance web server and a reverse proxy server... Jan 03 23:50:52 myCodingBlog systemd[1]: nginx.service: Failed to read PID from file /run/nginx.pid: Invalid argument Jan 03 23:50:52 myCodingBlog systemd[1]: Started A high performance web server and a reverse proxy … -
Error Making POST to ServiceM8
I'm getting the following error making a POST request to ServiceM8: {'Content-Type': 'text/html;charset=UTF-8', 'Content-Length': '343', 'Connection': 'keep-alive', 'Date': 'Wed, 04 Jan 2017 16:57:31 GMT', 'Server': 'Apache', 'X-Frame-Options': 'SAMEORIGIN', 'X-Cache': 'Error from cloudfront', 'Via': '1.1 49ccc390fa499ab821b632cf67d38720.cloudfront.net (CloudFront)', 'X-Amz-Cf-Id': 'DCkbBH5hfQ-ZyeyefPZJAyaVhKar_oD3n_VDZ8TYS97CyLpG4r5YGQ=='} I'm currently using: Django==1.10.4 requests==2.12.4 -
Django + Go API
I have a project with Django. Now I need write/migrate some API's to Go. How can I implement a condition if user is authenticated in Django and get user ID in Go API by the request? Like the existing request.user.is_authenticated() in Django. -
Merge two querysets that is related through a common model
Suppose I have two models in Django that is related to each other via a common model such as the example below: class ModelA(models.Model): f = models.IntegerField() class ModelX(models.Model): a = models.ForeignKey(ModelA) x = models.FloatField() class ModelY(models.Model): a = models.ForeignKey(ModelA) y = models.FloatField() Now suppose I want to query ModelX and ModelY and merge the two querysets into a single queryset where their reference is equal to ModelA. What is the best way to achieve this? What I've tried so far is building a dictionary with the one model and then looking it up when iterating over the second model, but I'm sure there must be a better way? I typically need to do this when I'm building a html table and looping over the queryset. m_x = ModelX.objects.all() d = {} for m in m_x: d[m.a] = m.x m_y = ModelY.objects.all() for m in m_y: m.x = d.get(m.a) -
How to run all django tests, even if some failed
How is it possible to show execution of each test, even if some tests failed. Now python manage.py test executes until the first fail. -
Django haystack check if instance is already indexed in the should_update method
class SmartReceiptIndex(indexes.SearchIndex, indexes.Indexable): text = indexes.CharField(document=True, use_template=True) email = indexes.CharField(model_attr='user__email') image_url = indexes.CharField(indexed=False, stored=True, model_attr='image') created = indexes.DateTimeField(model_attr='created') date = indexes.DateTimeField(indexed=False, stored=True, model_attr='date', null=True) cost = indexes.DecimalField(indexed=False, stored=True, model_attr='cost') x_coordinate = indexes.IntegerField(indexed=False, stored=True, null=True, model_attr='total_x_position') y_coordinate = indexes.IntegerField(indexed=False, stored=True, null=True, model_attr='total_y_position') def prepare(self, obj): obj = SmartReceipt.objects.select_related('user').get(id=obj.id) return super(SmartReceiptIndex, self).prepare(obj) def get_model(self): return SmartReceipt def get_updated_field(self): return 'updated' def should_update(self, instance, **kwargs): # I want to check in here if the instance already exists # in the elastic search index. if instance.processed: return True return False def prepare_email(self, smartreceipt): return smartreceipt.user.email def prepare_image_url(self, smartreceipt): if hasattr(smartreceipt.image, 'url'): return smartreceipt.image.url return None def index_queryset(self, using=None): return self.get_model().objects.filter(processed=True).exclude(user_id=1) In the should_update method I want to check if the instance has already been created in the elastic search index. I know that the kwargs have a created field which is a boolean, but I don't know if that represents what I think it does. If that field returns true does it mean that instance has been indexed? The other option I could see is this: from haystack.query import SearchQuerySet ... def should_update(self, instance, **kwargs): if instance.processed and SearchQuerySet().filter(id=instance.id).count() == 1: return True return False What is recommended? Thanks. -
Dynamic database for Django
I have a simple yet somehow complex pattern to put in place. I'm working on creating an app that will need to basically work as white labels for several customers. Each customers should have their own database with their own information. The idea would be for those customers to send a signature (token or such) within the requests or at connection, identifying them so that the app will know what database to get the information from. I've read here and there that the settings should not be altered, but I was wondering how this can be achieved simply? The need would be for a super admin to be able to create dynamically a new database and for a customer to be able to access an app with this specific database without having to redeploy the app entirely nor knowing beforehand the name of the database in the settings. How one should achieve this?