Python 3 Django Create Super User Manually

Gpg -verify Python-3.6.2.tgz.asc Note that you must use the name of the signature file, and you should use the one that's appropriate to the download you're verifying. (These instructions are geared to GnuPG and Unix command-line users.).

As part of an automation process I need to create the superuser for Django via python in the CLI.

I could consider other possibilities to this problem but only if they're easily scritable with ansible.

Anyway, this is what I have so far (for Django 1.6)

However, when I run this i get this error.

Any idea what's wrong or how to fix it please? It seems strange it should complain about DJANGO_SETTINGS_MODULE when it has been explicitly set..

The problem you're seeing is because you're running it as two separate python commands. You import the settings in the first, then python exits, then you start the second (which hasn't imported settings).

If you put them all into one python -c call, it should work.

It also looks like you're not passing the right number of arguments to .db_manager(). See this for more details:

How can i hook into django migrations for django 1.8

python,django,migration

When migration created, you can manually change the base migration class to your custom subclass with overridden apply method from django.db import migrations class MyBaseMigration(migrations.Migration): def apply(self, project_state, schema_editor, collect_sql=False): for operation in self.operations: '' Examine operation classes here and provide end-user notes '' return super(MyBaseMigration, self).apply(project_state, schema_editor, collect_sql=collect_sql) ...

Switch Case in Django Template

python,django,django-1.3

There is no {% switch %} tag in Django template language. To solve your problem you can either use this Django snippet, that adds the functionality, or re-write your code to a series of {% if %}s. The second option in code: {% if property.category.id 0 %} <h4>'agriculture'</h4> {%...

Django include template tag alternative in python class

python,django,django-templates

I think you might be looking for render_to_string. from django.template.loader import render_to_string context = {'foo': 'bar'} rendered_template = render_to_string('template.html', context) ...

Create angular page in Django to consume data from JSON

angularjs,django,django-templates

You can add the angular app as a simple template view in Django views.py def index(request): return render(request, 'yourhtml.html', {}) urls.py .... url(r'^your_url/$', views.index), .... Then the index.html file can have your angular code...

User registration endpoint in Django Rest Framework

django,django-rest-framework

Forgive me to digress a little, but I can't help but wonder use could have gotten away with far less code, than you have if you had created a serializer and used a class-based view. Besides, if you had just created email as EmailField of serializer it would have automatically...

How can I resolve my variable's unexpected output?

django,python-2.7

Remove the comma on your first line of code, this turns it into a tuple optional_message = form.cleaned_data['optional_message'], should be optional_message = form.cleaned_data['optional_message'] ...

Django: html without CSS and the right text

python,html,css,django,url

Are you using the {% load staticfiles %} in your templates?

Upload to absolute path in Django

Django create user

You should be able to create a different FileSystemStorage instance for each storage location. Alternatively, you could write a custom storage system to handle the files....

Using .update with nested Serializer to post Image

django,rest,django-models,django-rest-framework,imagefield

As noted in the docs, .update() doesn't call the model .save() or fire the post_save/pre_save signals for each matched model. It almost directly translates into a SQL UPDATE statement. https://docs.djangoproject.com/en/1.8/ref/models/querysets/#update Finally, realize that update() does an update at the SQL level and, thus, does not call any save() methods on...

sorl-thumbnail: Creating a thumbnail inside a for loop in a template

django,sorl-thumbnail

Django Create Admin User

It looks like your plural are in the wrong spot: {% for post_images in post.sellpostimage_set.all %} should be: {% for post_image in post.sellpostimage_set.all %} post_image = SellPostImage.objects.filter(post=poster_posts) context_dict['post_image'] = post_image should be: post_images = SellPostImage.objects.filter(post=poster_posts) context_dict['post_images'] = post_images or: post_image = SellPostImage.objects.get(post=poster_posts) context_dict['post_image'] = post_image why do you do this...

django and python manage.py runserver execution error

python,django,manage.py

It looks like you're running against the system version of python on the new laptop, rather than the virtualenv, so it is probably a different version. You can check this by looking at the version of Python on the virtualenv in the old laptop and the new laptop with python...

How can I fill the table? (Python, Django)

python,django

There are two things that you need to change. In the views.py file, rather than returning 4 different lists, return a single zipped version of the lists like zipped_list = zip(first_list, second_list, third_list, fourth_list) Now this must be passed to the view file that is being rendered. context_dict = {'zipped_list':...

Django TemplateDoesNotExist Error on Windows machine

python,django

The solution that worked for me was removing the below piece of code from settings.py: TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] And adding : TEMPLATE_DIRS = ('C:/Users/vaulstein/tango_with_django_project/templates',) OR Changing the line...

django cannot multiply non-int of type 'str'

python,django

I would use this: def _total_amount(self): req = QuoteRow.objects.filter(quote=self.pk) return sum([i.unit_price * i.quantity for i in req]) It takes one more line but it's clearer to me....

Does Django implement user permissions in databases with models?

python,django,orm,django-admin

Django by itself doesn't provide access to the database-level users / groups / permissions, because it doesn't make much sense for a typical web application where all connections will be made with the same database user (the one defined in settings.DATABASES). Note that it's not a shortcoming be really the...

Django file upload took forever with Phusion Passenger

django,apache,file-upload,passenger

Passenger author here. Try setting passenger_log_level to a higher value, which may give you insights on why this is happening. I don't know which Passenger version you are using, but in version 5, the Passenger request processing cycle looks like this: Apache receives the request. Once headers are complete, it...

Django add an attribute class form in __init__.py

python,django,forms,django-forms

You need to assign the field to form.fields, not just form. However this is not really the way to do this. Instead, you should make all your forms inherit from a shared parent class, which defines the captcha field....

Django runserver not serving some static files

django,python-3.x

According to the Django documentation regarding static/: This should be an initially empty destination directory for collecting your static files from their permanent locations into one directory for ease of deployment; it is not a place to store your static files permanently. You should do that in directories that will...

Django: Handling several page parameters

python,django,list,parameters,httprequest

Since, request.GET is a dictionary, you can access its values like this: for var in request.GET: value = request.GET[var] # do something with the value ... Or if you want to put the values in a list: val_list = [] for var in request.GET: var_list.append(request.GET[var]) ...

Callable in model field not called upon adding new object through Django admin

django,django-models,django-admin

Try: when_first_upload = models.DateTimeField(default=datetime.datetime.now) You need the callable itself, not the result returned by it....

Django ClearableFileInput - how to detect whether to delete the file

django,django-forms,django-crispy-forms

You shouldn't check the checkbox, but check the value of the file input field. If it is False, then you can delete the file. Otherwise it is the uploaded file. See: https://github.com/django/django/blob/339c01fb7552feb8df125ef7e5420dae04fd913f/django/forms/widgets.py#L434 # False signals to clear any existing value, as opposed to just None return False return upload ...

can roles and tasks exist in the same playbook?

ansible,ansible-playbook

Actually this should be possible and I remember I did this a few times during testing. Might be something with your version - or the order does matter, so that the tasks will be executed after the roles. I would have posted this as a commend, rather than an answer,...

Django listview clone selected record

I've done this with a simple method in views.py. Simply retrieve the record, blank out its id then save and open it. Something like def create_new_version(request) : record = models.MyDocument.objects.filter(id=request.GET['id'])[0] record.id = None record.save() return http.HttpResponseRedirect(reverse('edit-mydocument', kwargs={'pk':record.id})) where MyDocument is your model and edit-mydocument is your UpdateView. Just call this...

How to use template within Django template?

Python Super User

python,html,django,templates,django-1.4

You can use the include tag in order to supply the included template with a consistent variable name: For example: parent.html <div> <div> {% include 'templates/child.html' with list_item=mylist.0 t=50 only %} </div> </div> child.html {{ list_item.text|truncatewords:t }} UPDATE: As spectras recommended, you can use the...

How to work with django-rest-framework in the templates

json,django,django-templates,django-rest-framework

model.py: class Day(models.Model): date = models.DateField(default=date.today) def get_todo_list(self): return self.day_todo_set.order_by('-id')[:5] class ToDo(models.Model): date = models.ForeignKey(Day, related_name='day_todo_set') name = models.CharField(max_length=100) very_important = models.BooleanField(default=False) finished = models.BooleanField(default=False) In serializers.py class ToDoSerializer(serializers.ModelSerializer): class Meta: model = ToDo field = ('id', 'date', 'name', 'very_important', 'finished') class...

Get the first image src from a post in django

django,django-templates,django-views

Here's a basic approach you can tweak for your convenience: Add a first_image field to your model: class Blog(models.Model): title = models.CharField(max_length=150, blank=True) description = models.TextField() pubdate = models.DateTimeField(default=timezone.now) publish = models.BooleanField(default=False) first_image = models.CharField(max_length=400, blank=True) Now all you have to do is populate your first_image field on save, so...

Django test RequestFactory vs Client

django,unit-testing,django-views,django-rest-framework,django-testing

RequestFactory and Client have some very different use-cases. To put it in a single sentence: RequestFactory returns a request, while Client returns a response. The RequestFactory does what it says - it's a factory to create request objects. Nothing more, nothing less. The Client is used to fake a complete...

Display django runserver output from Vagrant guest VM in host Mac notifications?

python,django,osx,notifications,vagrant

Why not run a SSH server on the VM and connect from the host via a terminal? See MAC SSH. Which OS is running on the VM? It should not be too hard to get the SSH server installed and running. Of course the VM client OS must have an...

Permission denied Setuptools

python,django,curl,setuptools

You need sudo for the python command to write to /Library/Frameworks...: curl https://bootstrap.pypa.io/ez_setup.py -o - | sudo python ...

Use django to expose python functions on the web

python,django

Typically, as stated by @DanielRoseman, you certainly want to: Create a REST API to get data from another web site Get data, typically in JSON or XML, that will contain all the required data (name and surname) In the REST controller, Convert this data to the Model and save the...

Django template not found in main project directory error

python,django,templates

Django Create User

If your template is independent of apps, it shouldn't be in your app folder - namespace it accordingly. How do you load your template? Did you setup your templates/staticfolders in your settings.py? Updated For the fresh project you need to configure your settings.py file. Read here, ask away if you...

Why is Django widgets for TimeInput not showing

django,django-forms,django-templates,django-views

The Django admin uses AdminTimeWidget to display time fields, not the TimeInput widget that you are using in your code. There isn't a documented way to reuse the AdminTimeWidget outside of the Django admin. Getting it to work is very hacky (see the answer on this question, which is probably...

Python3 Django

Trying to write a unit test for file upload to a django Restless API

python,django,rest,file-upload,request

I tried to fix this but in the end it was quicker and easier to switch to the Django-REST framework. The docs are so much better for Djano-REST that it was trivial to set it up and build tests. There seem to be no time savings to be had with...

Django MySQLClient pip compile failure on Linux

python,linux,django,gcc,pip

It looks like you're missing zlib; you'll want to install it: apt-get install zlib1g-dev I also suggest reading over the README and confirming you have all other dependencies met: https://github.com/dccmx/mysqldb/blob/master/README Also, I suggest using mysqlclient over MySQLdb as its a fork of MySQLdb and what Django recommends....

Button updates text of first element instead of selected element

javascript,jquery,html,django,django-templates

Every photo has the same id for its like count: {% for photo in photos %} <a href='#'>0</a> {% endfor %} Therefore, only the first is recognized as the 'real' #like_count Since you have a primary key for the photo, you could make the ids distinct by incorporating the...

Django REST tutorial DEBUG=FALSE error

python,django,django-rest-framework

This error: File '/tutorial/tutorial/urls.py', line 9, in <module> url(r'^admin/', include(snippets.urls)), NameError: name 'snippets' is not defined occurs because snippets.urls has to be quoted. See the example here: urlpatterns = [ url(r'^', include('snippets.urls')), ] As shown here, you could write something like this: from django.contrib import admin urlpatterns = [ url(r'^polls/',...

Add field to django ModelForm that are in the model but not in the form

python,django

Save the form with commit=False, edit the returned instance, then save it to the db. if request.POST: f = Create_EventForm(request.POST) if f.is_valid(): event = f.save(commit=False) event.other_value = lookup_value() event.save() See the doc's on ModelForm's save method for more info....

DRF Update Existing Objects

django,django-rest-framework

In your view, you need to provide the following: lookup_field -> Most probably the ID of the record you want to update lookup_url_kwarg -> The kwarg in url you want to compare to id of object You need to define a new url in your urls.py file. This will carry...

upload_to dynamically generated url to callable

python,django,models

It looks like (re-reading your post it's not 100% clear) what you want is a partial application. Good news, it's part of Python's stdlib: import os from functools import partial def generic_upload_to(instance, filename, folder): return os.path.join(instance.name, folder, filename) class Project(TimeStampedModel): name = models.TextField(max_length=100, default='no name') logo = models.ImageField( upload_to=partial(generic_upload_to, folder='logo')...

Django: show newlines from admin site?

python,html,django,newline,textfield

Use the linebreaks template filter.

How to get simple ForeignKey model working? (a list of class in another class)

django,django-models,django-queryset

You should reverse the foreign key relationship: class HeartRate(models.Model): timestamp = models.DateTimeField('Date and time recorded') heartrate = models.PositiveIntegerField(default=0) exercise = models.ForeignKey(Exercise, related_name='heartrates') class Exercise(models.Model): start_timestamp = models.DateTimeField('Starting time') finishing_timestamp = models.DateTimeField('Finishing time') To get all of the heartrates of an exercise: heartrates = my_exercise.heartrates.all() ...

Algoritm to sort object by attribute value without allowing gaps or duplicates

python,sql,django,sorting,django-orm

The above algorithm would not work , because assume you have the following list - [0,2,5,9] You should ideally get - [0,1,2,3] The sum of that list is 6 , but the length of the list is 4 , this does not meet your condition in is_compressed() . The algorithm...

Show message when there's no excerpt - Django templates

Python Install Django

python,django,django-templates,django-template-filters

Django Add User

Your problem is with your if/else tags. You have this: {{ % if ... %}} ... {{% else %}} ... First off, you need to surround if/else by {% %}, not {{% %}}. Secondly, you don't have an endif. An if/else block should look like this: {% if ... %}...

How do I loop through a nested context dictionary in Django when I have no idea the structure I will recieve

django,django-templates,django-views

You need to define a custom template tag which returns the type of data. from django import template register = template.Library() @register.filter def data_type(value): return type(value) Then use it inside your template like this: {% for key, value in leasee.items %} <p> {{key}} </p> <ul> {%if value|data_type 'dict' %}...

DjangoCMS 3 Filter Available Plugins

django,django-cms

Remove plugins you don't need from INSTALLED_APPS. Alternatively, in an app after all plugin apps in INSTALLED_APPS in either cms_plugins.py or models.py you can use cms.plugin_pool.plugin_pool.unregister_plugin to remove them from the pool: from cms.plugin_pool import plugin_pool from unwanted_plugin_app.cms_plugins import UnwantedPlugin plugin_pool.unregister_plugin(UnwantedPlugin) ...

How to list objects in many to many Django

django,many-to-many,django-queryset

You're very close: Change: [i.dealership for i in q.dealership.all] to: [dealership for dealership in q.dealership.all()] Here's sample output from one of my model's M2M relationships on a project which demonstrates what you should see from the list comprehension. shared_with is an M2M field to a model called Profile: >>> from...

Django does not render my forms' fields

django,django-models,django-forms,django-templates,django-views

Your form inherits from forms.Form, which does not know anything about models and ignores the Meta class. You should inherit from forms.ModelForm.

Is there a way to install django with pip to point to a specific version of python in virtualenv

python,django,pip,virtualenv

Invoke django-admin.py like this python django-admin.py, in your activate virtualenv. Alternatively you can do /path/to/virtualenv/bin/python django-admin.py. The best solution is probably adding a shebang to django-admin.py that looks like #!/usr/bin/env python which should use the python interpreter of your active virtualenv. See http://stackoverflow.com/a/2255961/639054

Django block inclusion not working. What did I miss?

django,django-templates

Django templates do not use inclusion so much as template inheritance. The idea is you set up a hierarchy of templates, specializing some common thing. For instance: you could have a base.html that has some basic page structure, common to all pages of your website. you could then have a...

django 1.8 CreateView Error

python,django

Your SignUpView is not specifying the form it should render, you need to add the form_class attribute. class SignUpView(CreateView): form_class = RegistrationForm model = User template_name = 'accounts/signup.html' ...