Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
#!/usr/bin/env python
# https://docs.djangoproject.com/en/3.1/topics/settings/#calling-django-setup-is-required-for-standalone-django-usage
import django
from django.conf import settings
# https://blog.amedama.jp/entry/sqlite3-in-memory-issue
import tempfile
tfile = tempfile.NamedTemporaryFile()
import sqlite3
conn = sqlite3.connect(tfile.name)
c = conn.cursor()
c.execute('CREATE TABLE question (id integer primary key, text text)')
settings.configure(DEBUG=True, DATABASES={
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': tfile.name,
}
})
django.setup()
# Now this script or any imported module can use any part of Django it needs.
from django import forms
class NameForm(forms.Form):
your_name = forms.CharField(label='Your name', max_length=100)
name_form = NameForm()
print(name_form)
from django.db import models
class Question(models.Model):
id = models.BigAutoField(primary_key=True)
text = models.TextField()
def __str__(self):
return f'[{self.id}] {self.text}'
class Meta:
app_label = 'standalone'
db_table = 'question'
q = Question(text="who's the president of USA?")
q.save()
print(q)
print(Question.objects.all())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment