Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django hello word
I am trying to deploying a simple hello word inspired from here on apache2 using mod-wsgi. But I get the following error message althogh I added both the ip and hostname to the ALLOWED_HOST in settings.py of the application. DisallowedHost at / Invalid HTTP_HOST header: '192.168.1.36:8000'. You may need to add u'192.168.1.36' to ALLOWED_HOSTS. Request Method: GET Request URL: http://192.168.1.36:8000/ Django Version: 1.10.3 Exception Type: DisallowedHost Exception Value: Invalid HTTP_HOST header: '192.168.1.36:8000'. You may need to add u'192.168.1.36' to ALLOWED_HOSTS. Exception Location: /var/www/sampleapp/env/local/lib/python2.7/site-packages/django/http/request.py in get_host, line 113 Python Executable: /var/www/sampleapp/env/bin/python Python Version: 2.7.12 Python Path: ['/var/www/sampleapp', '/var/www/sampleapp/env/lib/python2.7', '/var/www/sampleapp/env/lib/python2.7/plat-x86_64-linux-gnu', '/var/www/sampleapp/env/lib/python2.7/lib-tk', '/var/www/sampleapp/env/lib/python2.7/lib-old', '/var/www/sampleapp/env/lib/python2.7/lib-dynload', '/usr/lib/python2.7', '/usr/lib/python2.7/plat-x86_64-linux-gnu', '/usr/lib/python2.7/lib-tk', '/var/www/sampleapp/env/local/lib/python2.7/site-packages', '/var/www/sampleapp/env/lib/python2.7/site-packages'] Server time: Mon, 14 Nov 2016 12:11:35 +0000 Traceback Switch to copy-and-paste view /var/www/sampleapp/env/local/lib/python2.7/site-packages/django/core/handlers/exception.py in inner response = get_response(request) ... ▶ Local vars /var/www/sampleapp/env/local/lib/python2.7/site-packages/django/utils/deprecation.py in __call__ response = self.process_request(request) ... ▶ Local vars /var/www/sampleapp/env/local/lib/python2.7/site-packages/django/middleware/common.py in process_request host = request.get_host() ... ▶ Local vars /var/www/sampleapp/env/local/lib/python2.7/site-packages/django/http/request.py in get_host raise DisallowedHost(msg) ... ▶ Local vars Request information GET No GET data POST No POST data FILES No FILES data COOKIES No cookie data META Variable Value CLUTTER_IM_MODULE 'xim' COLORTERM 'gnome-terminal' COMPIZ_BIN_PATH '/usr/bin/' COMPIZ_CONFIG_PROFILE 'ubuntu-lowgfx' CONTENT_LENGTH '' CONTENT_TYPE 'text/plain' DBUS_SESSION_BUS_ADDRESS 'unix:abstract=/tmp/dbus-nvlHAS61ss' DEFAULTS_PATH '/usr/share/gconf/ubuntu.default.path' DESKTOP_SESSION 'ubuntu' DISPLAY ':0' DJANGO_SETTINGS_MODULE … -
Django - displaying the selection from two drop downs on the same page
I have two drop downs in a page and I want to show the selection in the same page when the select button is pressed (for confirmation before sending them to database). I found a way online that involves jquery. Is there a way to do this with django in back end? or am I stuck with the jquery option???(I know zero jquery) -
Why to upload files to django static directory instead of directly to django static root
I would like to know the following: 1)Why should you upload files into static directories and run 'collectstatic' instead of directly uploading to the static root folder.I know it sounds little bit insecure , not getting the files run through the python first but still.. 2)What does it do to the static files when you run a 'collectstatic' command 3)What can be consequences of directly uploading to static root and alternative to this , this is not just limited to django framework but to whole web dev community if they have the same workflow to upload all the staticfiles. -
Unpack dictionnary as template tag arguments
Is there a way to use a dictionnary as nammed arguments in a template tag in django ? Assuming I have a dictionnary like : my_dict = { 'param1': 'value1', 'param2': 'value2' } I know that can do for example : a_function(**my_dict) But can I do something like : {% url 'my_app.viewname' **my_dict %} The url tag is actually what I'm trying to use here, maybe is there an other way to achieve this ? -
Correct media_root and I recived 404 in django app
I have problem withe icons in admin panel in my Django app. I have all files in my root media folder: '/files/dev/projects/mynewproject/media' but in console I get 404 error. My urls.py urlpatterns = static(settings.STATIC_URL, document_root=settings.STATIC_ROOT ) + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) + patterns('', # ... ) My MEDIA_ROOT: MEDIA_ROOT = '/files/dev/projects/mynewproject/media' Response in terminal: /media/adminextra/js/jquery.js HTTP/1.1" 404 1829 -
Keep HTML formatting when passing variable from Django template to view
I have created a contact form in my Django app. In my template there is a textarea field: <textarea class="form-control" rows="8" id="email_body" name="email_body" placeholder="Email body"></textarea> In my views.py the content of this textarea is passed to a function that sends emails: def index(request): # some code here email_body = request.POST.get('email_body') send_emails(email_subject, email_body, email_list) # the other variables are declared above # more code here I don't know if it is needed, but the code for the send_emails function is: def send_emails(email_subject, email_body, email_list): subject = email_subject message = email_body email = EmailMessage(subject, message, os.environ['EMAIL_HOST_USER'], email_list) email.content_subtype = "html" email.send() The problem is that the email body has no text formatting. All the newline characters (from the textarea) are lost and the message is printed in a single line. Is there a way to keep the original HTML formatting of the textarea message, when this is passed to the view and the send_emails function? -
Send password on user registration, django-allauth
everyone! I am using django-alluth for authentication/registration on my django app. And I need to create a custom signup form with only one field: email. The password will be generated on the server. Here is a form I have created: from django import forms from users.models import User class SignupForm(forms.ModelForm): email = forms.CharField() class Meta: model = User fields = ['email',] esclude = ['password1', 'password'] def __init__(self, *args, **kwargs): super(SignupForm, self).__init__(*args, **kwargs) del self.fields['password1'] del self.fields['password2'] def signup(self, request, user): password = str(User.objects.make_random_password()) user.set_password(password) #!!!!!!! HERE user.save() In settings.py: ACCOUNT_SIGNUP_FORM_CLASS = 'users.forms.SignupForm' And now I need to send an email to the user with his password. Of course, I can do this in signup method, but it is not good practice, as a form is needed only for gathering and checking information. It will be good to listen to user_signed_up django-allauth signal, but it will be impossible to get user password in it, as a password is stored in a hash. Is there any way to pass additional parameters to signal? Or maybe there are some others methods to send an email? Thanks a lot. -
Catch Specific Failed Records in bulk_create Django
I'm using bulk_create to insert thousand of users once: new_users_bulk_list.append(User(user_id=user_id, date_of_birth=dob)) if len(new_users_bulk_list) >= settings.BULK_LIMIT: try: User.objects.bulk_create(new_users_bulk_list) new_users_bulk_list[:] = [] except Exception as e: print("Error: Creating users " + str(e)) and bulk_update to update many records: user_bulk.append(user_sequence) if len(user_bulk) == settings.BULK_LIMIT: bulk_update(user_bulk) user_bulk[:] = [] If bulk_create or bulk_update fails in creating/updating records, how can I identify these failed records? Is there a way to catch specific failed records ? Thank you, -
Django REST authentication from desktop app
I have been trying to use the Django-REST authentication to vallidate the user name /password given in a desktop app. On the server side, I have installed the following DJANGo-REST-FRAMEWORK-JWT package found here: https://github.com/GetBlimp/django-rest-framework-jwt I have gone through the example and when I run the following on the command line get a token as a response: curl -X POST -d "username=luca&password=letmein123" http://localhost:8000/api-token-auth/ And I get: {"token":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6InBhbmthaiIsInVzZXJfaWQiOjIsImVtYWlsIjoiIiwiZXhwIjoxNDc5MTE5NzQ2fQ.RA085m-YSnGFheykCCxSVxI_9rW9AC9kEaOkUB5Gm0A"} My question is how can I do that from my desktop python app. I basically want to call the same API with the username and passord and be able to process the response and access protected APIs. -
Recording data over time in Django Models
This is a very general question I don't seem to find an answer to. Let's say I have a model called Room referring to a hotel room. And I would like to have a time series showing me room occupation in the past, present and future. One "thought" I had was to have a dictionary with something like {'date': room.guest} but I don't see how I can define a dict for a Django Model. Is this approach realisable within Django at all? What kind of alternatives do I have to achieve this goal? Currently my Room Model is very simple and looks like this: class Room(models.Model): number = models.IntegerField() room_type = models.ForeignKey('RoomType') def __str__(self): return "Room {}".format(self.number) The Room itself is a Foreign Key in the Guest Model.. -
embedded: Unexpected token . React.
<script type="text/babel"> class List extends React.Component { state = { objects: ['1', '2', '3'] }; render() { return(<div> objects[1] </div>) } } Error: browser.min.js:41 Uncaught SyntaxError: embedded: Unexpected token (4:18) 2 | class List extends React.Component { 3 | > 4 | state = { | ^ 5 | objects: ['1', '2', '3'] 6 | }; I can't understand(( -
Set dynamic download path to django
How i can set a dynamic download path to django by change this part: (settings.MEDIA_ROOT, 'folder/path/file.pdf') with open(os.path.join(settings.MEDIA_ROOT, 'folder/path/file.pdf'), 'rb') as fh: response = HttpResponse(fh.read(), content_type="application/pdf") response['Content-Disposition'] = 'filename=invoice.pdf' return response to something like this: (settings.MEDIA_ROOT, FUNCTION_RETURN_THE_PATH) with open(os.path.join(settings.MEDIA_ROOT, FUNCTION_RETURN_THE_PATH), 'rb') as fh: response = HttpResponse(fh.read(), content_type="application/pdf") response['Content-Disposition'] = 'filename=invoice.pdf' return response If a use function i get many errors, because it expects a string variable in this place and not a function. -
Python Django:Form validation with pure HTML
I would like to use pure HTML in django ie i don't want to use django auto generated form tags suppose i have an html markup like this <form action="sample/" method="post"> <input type="text" name="name"> <input type="submit" value="submit"> </form> So how can i add the validation rules to above form?? Now i am using form class to generate forms and the validation code look like this if request.method=='POST': form = NameForm(request.POST) if form.is_valid(): return HttpResponse('form ok') else: return render(request, 'templates/form.html', {'form': form,'t':'form submit'}) else: form=NameForm() return render(request, 'templates/form.html', {'form': form}) -
Using external links inside django admin to create or update
I am using a redactor wysiwyg editor to write my content. The page has only the wysiwyg editor and a save button. html: <div id="editor-wrapper"> <input type="text" id="editor-title" {%if blog %} value="{{blog.title}}" {% else %} placeholder="Your title" {% endif %}> <textarea id="editor-redactor" name="content"> {% if blog %} {{ blog.body }} {% else %} <p>Enter you body in here...</p> {% endif %} </textarea> <button id="save-btn"><a href="/save-blog/">Save</a> </button> </div> And in the urls.py I have added the url to go to that page. url(r'^add-update-blog/$', views.add_update_blog), url(r'^add-update-blog/save/(?P<blog_id>\d+)$', views.add_update_blog), views.py: def add_update_blog(request): return render(request, 'editor.html') def add_update_blog_save(request, blog_id): blog = Blog.objects.get(id=blog_id) return render(request, 'editor.html', { blog: blog }) Now, in the django-admin panel there may be list of already written contents: If I click on add, I want to go to the editor page. If I click on any of the already written content object, I want to get that object and load it in the editor page. Right now it displays the list and when I click add or on the content it is displayed inside the admin panel only. How do I achieve what I want? Your help and guidance is really very much appericated. Thank you. -
Django:What is the EMAIL_HOST and EMAIL_PORT of EC2 instance?
I'd like to send email from EC2 instance by Django. I'm using Postfix in order to send email from EC2 instance. I've set /etc/postfix/main.cf as following, then set email parameters at settings.py latelyl. However, it could not send email. What should I set as EMAIL_HOST and EMAIL_PORT, EMAIL_HOST_USER and EMAIL_HOST_PASSWORD of EC2 instance? /etc/postifx/main.cf myhostname = mail.ship-per.com mydomain = ship-per.com myorigin = $mydomain mydestination = $myhostname, localhost.$mydomain, localhost, $mydomain inet_interfaces = all mynetworks = 192.168.0.0/24, 127.0.0.0/8 home_mailbox = Maildir/ smtpd_banner = $myhostname ESMTP unknown #relayhost = mail.ship-per.com:587 smtpd_sasl_auth_enable = yes broken_sasl_auth_clients = yes smtpd_sasl_security_options = noanonymous smtpd_sasl_local_domain = $myhostname smtpd_sender_restrictions = reject_unknown_sender_domain smtpd_client_restrictions = permit_mynetworks, reject_unknown_client, permit smtpd_recipient_restrictions = permit_mynetworks, permit_sasl_authenticated, reject_unauth_destination settings.py DEFAULT_FROM_EMAIL = 'info@ship-per.com' EMAIL_HOST = 'mail.ship-per.com' EMAIL_PORT = 25 #EMAIL_HOST_USER = 'user' #EMAIL_HOST_PASSWORD = 'password' EMAIL_USE_TLS = False -
Querying objects using attribute of member of many-to-many
I have the following models: class Member(models.Model): ref = models.CharField(max_length=200) # some other stuff def __str__(self): return self.ref class Feature(models.Model): feature_id = models.BigIntegerField(default=0) members = models.ManyToManyField(Member) # some other stuff A Member is basically just a pointer to a Feature. So let's say I have Features: feature_id = 2, members = 1, 2 feature_id = 4 feature_id = 3 Then the members would be: id = 1, ref = 4 id = 2, ref = 3 I want to find all of the Features which contain one or more Members from a list of "ok members." Currently my query looks like this: # ndtmp is a query set of member-less Features which Members can point to sids = [str(i) for i in list(ndtmp.values('feature_id'))] # now make a query set that contains all rels and ways with at least one member with an id in sids okmems = Member.objects.filter(ref__in=sids) relsways = Feature.geoobjects.filter(members__in=okmems) # now combine with nodes op = relsways | ndtmp This is enormously slow, and I'm not even sure if it's working. I've tried using print statements to debug, just to make sure anything is actually being parsed, and I get the following: print(ndtmp.count()) >>> 12747 print(len(sids)) >>> 12747 … -
python manage.py runserver and get "Unhandled exception in thread started.....ValueError: the query contains a null character"
when I use "python manage.py runserver",and get such tracebacks as following: Performing system checks... System check identified no issues (0 silenced). Unhandled exception in thread started by <function wrapper at 0x7f518da18230> Traceback (most recent call last): File "/data/program/mtl/venv/lib/python2.7/site-packages/django/utils/autoreload.py", line 226, in wrapper fn(*args, **kwargs) File "/data/program/mtl/venv/lib/python2.7/site-packages/django/core/management/commands/runserver.py", line 124, in inner_run self.check_migrations() File "/data/program/mtl/venv/lib/python2.7/site-packages/django/core/management/base.py", line 437, in check_migrations executor = MigrationExecutor(connections[DEFAULT_DB_ALIAS]) File "/data/program/mtl/venv/lib/python2.7/site-packages/django/db/migrations/executor.py", line 20, in __init__ self.loader = MigrationLoader(self.connection) File "/data/program/mtl/venv/lib/python2.7/site-packages/django/db/migrations/loader.py", line 52, in __init__ self.build_graph() File "/data/program/mtl/venv/lib/python2.7/site-packages/django/db/migrations/loader.py", line 203, in build_graph self.applied_migrations = recorder.applied_migrations() File "/data/program/mtl/venv/lib/python2.7/site-packages/django/db/migrations/recorder.py", line 65, in applied_migrations self.ensure_schema() File "/data/program/mtl/venv/lib/python2.7/site-packages/django/db/migrations/recorder.py", line 56, in ensure_schema with self.connection.schema_editor() as editor: File "/data/program/mtl/venv/lib/python2.7/site-packages/django/db/backends/sqlite3/schema.py", line 27, in __enter__ return super(DatabaseSchemaEditor, self).__enter__() File "/data/program/mtl/venv/lib/python2.7/site-packages/django/db/backends/base/schema.py", line 86, in __enter__ self.atomic.__enter__() File "/data/program/mtl/venv/lib/python2.7/site-packages/django/db/transaction.py", line 184, in __enter__ connection.set_autocommit(False, force_begin_transaction_with_broken_autocommit=True) File "/data/program/mtl/venv/lib/python2.7/site-packages/django/db/backends/base/base.py", line 389, in set_autocommit self._start_transaction_under_autocommit() File "/data/program/mtl/venv/lib/python2.7/site-packages/django/db/backends/sqlite3/base.py", line 318, in _start_transaction_under_autocommit self.cursor().execute("BEGIN") File "/data/program/mtl/venv/lib/python2.7/site-packages/django/db/backends/utils.py", line 79, in execute return super(CursorDebugWrapper, self).execute(sql, params) File "/data/program/mtl/venv/lib/python2.7/site-packages/django/db/backends/utils.py", line 62, in execute return self.cursor.execute(sql) File "/data/program/mtl/venv/lib/python2.7/site-packages/django/db/backends/sqlite3/base.py", line 336, in execute return Database.Cursor.execute(self, query) ValueError: the query contains a null character what I use: django 1.10 python2.7 virtualenv settings.py: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } I have searched for a long … -
Invalid quality setting when I working with jpg and jpeg
I want to have images in my application (Django 1.8.15) in jpg and jpeg formats but only png format is working. When I try put images in jpg and jpeg format I get error: ValueError at /admin/files/select/1 Invalid quality setting Exception Type: ValueError Exception Value: Invalid quality setting My code in admin.py: class EventImageForm(forms.ModelForm): image = FileFormField(extensions=('jpg', 'jpeg', 'png'), image_format=4, label='Image') class Meta: model = EventImage exclude = [] My model: class EventImage(TranslationModel): event = models.ForeignKey(Booking) image = models.ForeignKey('files.File') text = models.CharField(max_length=255, null=True, blank=True) text_en = models.CharField(max_length=255, null=True, blank=True) video = models.CharField(max_length=255, null=True, blank=True) position = models.PositiveIntegerField(null=True, blank=True) class Meta: ordering = ['position', 'id'] verbose_name = 'Image' verbose_name_plural = 'Images' def __unicode__(self): return self.text or self.image.name -
Simple user profiles and django user authentication system
I am working on an app which doesn't require any login. But people need to provide email to complete certain tasks. So I want to create user-profiles based on the email to track users and also avoid repetition of email. I know I can create a simple model and get it done. But I want to use django-user-authentication so that in future, a user can also create login using the email and all data will be available to him/her. Need suggestion ? -
Django rest framework validate pagination limit and offset
Django Rest Framework by default swallows the exception raised for invalid limit and offset values even if they are not an integer and returns the default limit and offset values. Also there is no min_offset and min_limit thus it allows negative values in limit and offset. I need to throw error on those cases in my API . I have built a custom pagination class overriding the paginate_queryset method and made my validations there. Is there an API to validate the minimum limit and minimum offset values. I have the below code where I validate it by myself. Is it ok to write validations for paginator inside the method as there is no mention of it from the docs or do I need to validate inside my viewset methods itself? class CustomPagination(pagination.LimitOffsetPagination): default_limit = 25 max_limit = 50 min_limit = 1 min_offset = 1 max_offset = 50 def paginate_queryset(self, queryset, request, view=None): limit = request.query_params.get('limit') offset = request.query_params.get('offset') if limit: limit = int(limit) if limit > self.max_limit: raise serializers.ValidationError({"limit" : ["Limit should be less than or equal to {0}".format(self.max_limit)]}) elif limit < self.min_limit: raise serializers.ValidationError({"limit" : ["Limit should be greater than or equal to {0}".format(self.min_limit)]}) if offset: offset = int(offset) … -
is there a way to write this if..else statement in one line?
I'm newbie with python and django and now I'm learning how to simplify code in writing the if ..else statements in one line. But in this case I have a two querysets with a little change . I want to know if it is possible to simlify this code in one line if self.booked: x= qs.filter(content_id=content_id, object_id=model.id, action=10) else: x= qs.filter(content_id=content_type_id, object_id=model.id).exclude(action=10) return x -
Django: allocate foreignkey field as object?
models.py class Order(TimeStampedModel): name = models.CharField(max_length=50) class Payment(TimeStampedModel): order = models.ForeignKey( 'orders.Order', null=True, blank=True, unique=True, ) What I want to do is to create Payment first and add it to Order. Let say Order is already created without payment field. <1> In [1]: order = Order.objects.first() In [2]: payment = Payment.objects.create() In [3]: order.payment = payment In [4]: order.save() <2> In [7]: order.payment_set.add(payment) I'd like to know what is difference between <1> and <2>. What is a right way? -
Django Related name not working
i have a model with user = models.OneToOneField(User, on_delete=models.CASCADE, related_name="get_profile") say 'obj' is a user object then if i call obj.get_profile.country It says Author has no get_profile. Using django 1.6 -
Django 1.10 - Cannot resolve keyword '__' into field. Join on '__' not permitted
I am trying to make a chart using chartjs for showing all statistics of a poll votes. This is for a specific year with 12 months. For example, Are you a programmer? Yes No I would like to show in chart - how many votes users give to 12 months of a year. I ll draw 2 lines in chart that represents Yes and No answers statistics with levels Jauary - December. I already made all models and they work perfectly. But when in poll detail page I try to get 12 months statistics of vote record, get an error. Here is view code to get record counts - vote_records = Vote.objects.filter(question = question_record, pub_date__year = current_year).values_list('pub_date__month').count() Here pub_date is the Vote model publish date - pub_date = models.DateTimeField(auto_now_add=True) Error is - Cannot resolve keyword 'month' into field. Join on 'pub_date' not permitted. Thanks for your help! -
Django haystack boost (document=true) field (Solr backend)
So I have class ProductIndex(indexes.SearchIndex, indexes.Indexable): text = indexes.EdgeNgramField(document=True, use_template=True) region = fields.MultiValueField(model_attr='region') condition = fields.MultiValueField(model_attr='condition') Inside the (document=True) field I have {{ object.name }} {{ object.description }} How can I boost the object.name field ? Do I have to create separate name field ?