Inserting data from csv too slow Django - django-models

My problem is that inserting data into the database is too slow. I have written a correct algorithm that loads the data properly however with this method it will take 700 hours to load the database. There are almost 30 million records in the csv file.
Here is my models.py
from django.db import models
class Region(models.Model):
region = models.CharField(max_length=20)
class Rank(models.Model):
rank = models.IntegerField()
class Chart(models.Model):
chart = models.CharField(max_length=8)
class Artist(models.Model):
artist = models.CharField(max_length=60)
class Title(models.Model):
title = models.CharField(max_length=60)
class ArtistTitle(models.Model):
artist = models.ForeignKey(Artist, on_delete=models.CASCADE)
title = models.ForeignKey(Title, on_delete=models.CASCADE)
class SpotifyData(models.Model):
title = models.ForeignKey(ArtistTitle, related_name='re_title', on_delete=models.CASCADE)
rank = models.ForeignKey(Rank, on_delete=models.CASCADE)
date = models.DateField()
artist = models.ForeignKey(ArtistTitle, related_name='re_artist', on_delete=models.CASCADE)
region = models.ForeignKey(Region, on_delete=models.CASCADE)
chart = models.ForeignKey(Chart, on_delete=models.CASCADE)
streams = models.IntegerField()
My upload script looks like this:
def load_to_db(self, df):
bad = 0
good = 0
start = datetime.datetime.now
for _, row in df.iterrows():
try:
region_obj, _ = Region.objects.get_or_create(
region=row["region"],
)
rank_obj, _ = Rank.objects.get_or_create(
rank=row["rank"],
)
chart_obj, _ = Chart.objects.get_or_create(
chart=row["chart"],
)
artist_obj, _ = Artist.objects.get_or_create(
artist=row["artist"],
)
title_obj, _ = Title.objects.get_or_create(
title=row["title"],
)
arttit_obj, _ = ArtistTitle.objects.update_or_create(
artist=artist_obj,
title=title_obj,
)
spotifydata_obj, _ = SpotifyData.objects.update_or_create(
title=arttit_obj,
rank=rank_obj,
date=row["date"],
artist=arttit_obj,
region=region_obj,
chart=chart_obj,
streams=row["streams"],
)
good += 1
now = datetime.datetime.now
print(f"goods: {good}, loading time: {start-now}", )
except Exception as e:
bad += 1
current_time = datetime.datetime.now()
with open("data_load_logging.txt", "w") as bad_row:
bad_row.write(
f"Error message: {e} \n"
+ f"time: {current_time}, \n"
+ f"title: {row['title']}, type: {row['title']} \n"
+ f"rank: {int(row['rank'])}, type: {int(row['rank'])} \n"
+ f"date: {row['date']}, type: {row['date']} \n"
+ f"artist: {row['artist']}, type: {row['artist']} \n"
+ f"region: {row['region']}, type: {row['region']} \n"
+ f"chart: {row['chart']}, type: {row['chart']} \n"
+ f"streams: {int(row['streams'])}, type: {int(row['streams'])} \n"
+ "-" * 30
+ "\n"
)
I know it could probably help to use bulk/bulk_create/bulk_update but I can't figure out how to write the correct script....
def load_to_db(self, path):
start_time = timezone.now()
try:
with open(path, "r") as csv_file:
data = csv.reader(csv_file)
next(data)
packet_region = []
packet_rank = []
packet_chart = []
packet_artist = []
packet_title = []
packet_artist_title = []
packet_spotify_data = []
bad = -1 # first row is a header
for row in data:
region = Region(
region = row[4]
)
rank = Rank(
rank = row[1]
)
chart = Chart(
chart = row[5]
)
artist = Artist(
artist = row[3]
)
title = Title(
title = row[0]
)
artist_title = ArtistTitle(
artist = artist,
title = title
)
spotify_data = SpotifyData(
title = artist_title,
rank = rank,
date = row[3],
artist = artist_title,
region = region,
chart = chart,
streams = int(row[6])
)
packet_region.append(region)
packet_rank.append(rank)
packet_chart.append(chart)
packet_artist.append(artist)
packet_title.append(title)
packet_artist_title.append(artist_title)
packet_spotify_data.append(spotify_data)
if len(packet_spotify_data) > 1000:
print(datetime.datetime.now())
Region.objects.bulk_create(packet_region)
Rank.objects.bulk_create(packet_rank)
Chart.objects.bulk_create(packet_chart)
Artist.objects.bulk_create(packet_artist)
Title.objects.bulk_create(packet_title)
ArtistTitle.objects.bulk_update(packet_artist_title)
SpotifyData.objects.bulk_update(packet_spotify_data)
packet_region = []
packet_rank = []
packet_chart = []
packet_artist = []
packet_title = []
packet_artist_title = []
packet_spotify_data = []
logging.info(f"Failure numbers: {bad}")
if packet_spotify_data:
Region.objects.bulk_create(packet_region)
Rank.objects.bulk_create(packet_rank)
Chart.objects.bulk_create(packet_chart)
Artist.objects.bulk_create(packet_artist)
Title.objects.bulk_create(packet_title)
ArtistTitle.objects.bulk_update(packet_artist_title)
SpotifyData.objects.bulk_update(packet_spotify_data)
except FileNotFoundError as e:
raise NoFilesException("No such file or directory") from e
end_time = timezone.now()
self.stdout.write(
self.style.SUCCESS(
f"Loading CSV took: {(end_time-start_time).total_seconds()} seconds."
)
)
I tried to use bulk this way but unfortunately it doesn't work

Related

AttributeError: module 'interactions' has no attribute 'Client'

Full disclosure I haven't written this code myself and I'm still a little new to discord intents. I'm worried that some older discord libraries on my computer may be causing this but i'm not sure why I'm getting this error. Every time I run my program "AttributeError: module 'interactions' has no attribute 'Client' ".
Here is the code I was using
#imports
import interactions
import random
import cloudscraper
#settings
SafeMines = ':white_check_mark:'
TileMines = ':x:'
SafeTowers = ':white_check_mark:'
TileTowers = ':x:'
BotToken = ''
ServerId = 0
BuyerRoleId = 0
#StartUp
bot = interactions.Client(
token=BotToken
)
#defines
def GenGrid(SafeTiles:int):
Generating = True
BoardNums = []
Board = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]
Grid = f''
line = 0
endrownums = [6,11,16,21]
while Generating:
if len(BoardNums) < SafeTiles:
Selection = random.randint(1, 25)
if Selection in BoardNums:
pass
else:
BoardNums.append(Selection)
else:
Generating = False
for Number in BoardNums:
Board[Number-1] = 1
for Position in Board:
line += 1
if line in endrownums:
Grid += f'\n'
if Position == 1:
Grid += f'{SafeMines}'
else:
Grid += f'{TileMines}'
else:
if Position == 1:
Grid += f'{SafeMines}'
else:
Grid += f'{TileMines}'
return Grid
def gentower(rows:int):
if rows >= 9:
return "Max Rows 8!"
else:
def pr():
rowtp1 = f"{SafeTowers}{TileTowers}{TileTowers}"
rowtp2 = f"{TileTowers}{SafeTowers}{TileTowers}"
rowtp3 = f"{TileTowers}{TileTowers}{SafeTowers}"
joe = random.randint(1,3)
if joe == 1:
return rowtp1
elif joe == 2:
return rowtp2
else:
return rowtp3
leg = True
counter = 0
finaltower = f""
while leg:
if counter == rows:
leg = False
else:
counter +=1
finaltower += f"{pr()}\n"
return finaltower
#Commands
#bot.command(
name='mines',
description="Generates A Mine Grid",
scope=ServerId,
options= [
interactions.Option(
name="game_id",
description="Put your game id here",
type=interactions.OptionType.STRING,
required=True,
),
interactions.Option(
name="clicks",
description="How many safe spots to generate",
type=interactions.OptionType.INTEGER,
required=True,
)
]
)
async def Mines(ctx, game_id: str, clicks:int):
if BuyerRoleId in ctx.author.roles or ctx.author.id == 756534114143961088:
if int(clicks) > 23:
mines = interactions.Embed(title=f"Mines", description=f"Too Many SafeClicks! Max is 23\nYou Chose {clicks}/23", color=0xFC4431)
await ctx.send(embeds=mines, ephemeral=True)
else:
count = 0
includes_dash = False
includes_number1 = ""
includes_number2 = ""
l = [14,15,16]
l2 = [18,19,20,21,22]
lsu = False
for v in game_id:
count += 1
if count == 9:
if v == "-":
includes_dash = True
if count in l:
if v == "4":
includes_number1 += v
if count in l:
try:
int(v)
if lsu == True:
continue
else:
includes_number2 +=v
lsu = True
except ValueError:
continue
if includes_dash == True:
if includes_number1 == "4":
try:
int(includes_number2)
mines = interactions.Embed(title=f"Mines", description=f"Generated Tiles!", color=0xFC4431)
mines.add_field(name=f"Field {clicks} Clicks", value=GenGrid(clicks),inline=True)
await ctx.send(embeds=mines, ephemeral=True)
print(f"\n\n{ctx.author} Used Towers command\nID = {ctx.author.id}\n")
except ValueError:
mines = interactions.Embed(title=f"Mines", description=f"Invalid ID!", color=0xFC4431)
await ctx.send(embeds=mines, ephemeral=True)
else:
mines = interactions.Embed(title=f"Mines", description=f"Invalid ID!", color=0xFC4431)
await ctx.send(embeds=mines, ephemeral=True)
else:
mines = interactions.Embed(title=f"Mines", description=f"Invalid ID!", color=0xFC4431)
await ctx.send(embeds=mines, ephemeral=True)
else:
await ctx.send(f"Not Eligable! {ctx.author.mention}")
#Bot
bot.start()
Im not sure why its giving me any error, any suggestions on this?

How do you know exactly what causes the form not to be valid while processing form with model

Hey Mentors and Teachers, we appreciate having you, please help a young one here in this industry having not much experience this is one of my common challenges since I am still trying new ways, here I am using a model to save a form and also model form without having to use the form in the template. I am sure using the model form directly would have solved it quickly but I want the ability to be able to style my form, especially each individual field,
the version being used in this is django 3.1
Help me know how to make this code work
class Order(models.Model):
STATUS = (
('New', 'New'),
('Accepted', 'Accepted'),
('Completed', 'Completed'),
('Cancelled', 'Cancelled'),
)
user = models.ForeignKey(Account, on_delete=models.SET_NULL, null=True)
payment = models.ForeignKey(Payment, on_delete=models.SET_NULL, blank=True, null=True)
order_number = models.CharField(max_length=20)
first_name = models.CharField(max_length=50)
last_name = models.CharField(max_length=50)
phone = models.CharField(max_length=15)
email = models.EmailField(max_length=50)
address_line_1 = models.CharField(max_length=50)
address_line_2 = models.CharField(max_length=50, blank=True)
country = models.CharField(max_length=50)
state = models.CharField(max_length=50)
city = models.CharField(max_length=50)
order_note = models.CharField(max_length=100, blank=True)
order_total = models.FloatField()
tax = models.FloatField()
status = models.CharField(max_length=10, choices=STATUS, default='New')
ip = models.CharField(blank=True, max_length=20)
is_ordered = models.BooleanField(default=False)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
def full_name(self):
return f'{self.first_name}'
and here is a view that is am using:
def place_order(request, total=0, quantity=0,):
current_user = request.user
# If the cart count is less than or equal to 0, then redirect back to shop
cart_items = CartItem.objects.filter(user=current_user)
cart_count = cart_items.count()
if cart_count <= 0:
return redirect('store')
grand_total = 0
tax = 0
for cart_item in cart_items:
total += (cart_item.product.price * cart_item.quantity)
quantity += cart_item.quantity
tax = (2 * total)/100
grand_total = total + tax
if request.method == 'POST':
form = OrderForm(request.POST)
if form.is_valid():
# Store all the billing information inside Order table
data = Order()
data.user = current_user
data.first_name = form.cleaned_data['first_name']
data.last_name = form.cleaned_data['last_name']
data.phone = form.cleaned_data['phone']
data.email = form.cleaned_data['email']
data.address_line_1 = form.cleaned_data['address_line_1']
data.address_line_2 = form.cleaned_data['address_line_2']
data.country = form.cleaned_data['country']
data.state = form.cleaned_data['state']
data.city = form.cleaned_data['city']
data.more_address_details = form.cleaned_data['more_address_details']
data.order_note = form.cleaned_data['order_note']
data.order_note = form.cleaned_data['order_note']
data.order_total = grand_total
data.tax = tax
data.ip = request.META.get('REMOTE_ADDR')
data.save()
# Generate order number
yr = int(datetime.date.today().strftime('%Y'))
dt = int(datetime.date.today().strftime('%d'))
mt = int(datetime.date.today().strftime('%m'))
d = datetime.date(yr,mt,dt)
current_date = d.strftime("%Y%m%d") #20210305
order_number = current_date + str(data.id)
data.order_number = order_number
data.save()
order = Order.objects.get(user = current_user, is_ordered = False, order_number = order_number)
context = {
'order': order,
'cart_items': cart_items,
'total': total,
'tax': tax,
'grand_total': grand_total,
}
return render(request, 'orders/payments.html', {'context': context})
else:
return redirect('checkout')
else:
return redirect('store')
and here is what is in the template:
def place_order(request, total=0, quantity=0,):
current_user = request.user
# If the cart count is less than or equal to 0, then redirect back to shop
cart_items = CartItem.objects.filter(user=current_user)
cart_count = cart_items.count()
if cart_count <= 0:
return redirect('store')
grand_total = 0
tax = 0
for cart_item in cart_items:
total += (cart_item.product.price * cart_item.quantity)
quantity += cart_item.quantity
tax = (2 * total)/100
grand_total = total + tax
if request.method == 'POST':
form = OrderForm(request.POST)
if form.is_valid():
# Store all the billing information inside Order table
data = Order()
data.user = current_user
data.first_name = form.cleaned_data['first_name']
data.last_name = form.cleaned_data['last_name']
data.phone = form.cleaned_data['phone']
data.email = form.cleaned_data['email']
data.address_line_1 = form.cleaned_data['address_line_1']
data.address_line_2 = form.cleaned_data['address_line_2']
data.country = form.cleaned_data['country']
data.state = form.cleaned_data['state']
data.city = form.cleaned_data['city']
data.more_address_details = form.cleaned_data['more_address_details']
data.order_note = form.cleaned_data['order_note']
data.order_note = form.cleaned_data['order_note']
data.order_total = grand_total
data.tax = tax
data.ip = request.META.get('REMOTE_ADDR')
data.save()
# Generate order number
yr = int(datetime.date.today().strftime('%Y'))
dt = int(datetime.date.today().strftime('%d'))
mt = int(datetime.date.today().strftime('%m'))
d = datetime.date(yr,mt,dt)
current_date = d.strftime("%Y%m%d") #20210305
order_number = current_date + str(data.id)
data.order_number = order_number
data.save()
order = Order.objects.get(user = current_user, is_ordered = False, order_number = order_number)
context = {
'order': order,
'cart_items': cart_items,
'total': total,
'tax': tax,
'grand_total': grand_total,
}
return render(request, 'orders/payments.html', {'context': context})
else:
return redirect('checkout')
else:
return redirect('store')
I AM ALWAYS BLOWNED BY THE KIND OF PEOPLE WHO ALWAYS HELP WITHOUT EXPECTING ANYTHING IN RETURN, REALLY THANKS
Just found where the error was, had forgotten to add the name of a form field "more_address_details" in the template

ValueError: variable needs to have a value for field "id" before this many to many relationship can be used - Django

I created a datamodel in Django, and now I created a script to auto populate the models using web-scraped values. However when I run the script I get the following error:
ValueError: variable needs to have a value for field "id" before this many to many relationship can be used
Models.py
class Books(models.Model):
title = models.CharField(max_length=100)
def __str__(self):
return self.title
class Meta:
ordering = ['-title']
class Author(models.Model):
book = models.ManyToManyField(Books)
first_name = models.CharField(max_length=150)
last_name = models.CharField(max_length=200)
def __str__(self):
return "{} {}".format(self.first_name, self.last_name)
class Meta:
ordering = ['last_name','first_name']
class Book_details(models.Model):
book = models.ForeignKey(Books,
on_delete=models.CASCADE,
null=True) # models.SET_NULL weggehaald
pages = models.CharField(max_length=250)
publ_year = models.CharField(max_length=250)
edition = models.CharField(max_length=30) # paperback, hardcover, audiobook, etc
def __str__(self):
return "{} - pages: <{}>, edition: <{}>".format(self.book.title,
self.pages,
self.edition)#
class Cover(models.Model):
book = models.OneToOneField(Books,
on_delete=models.CASCADE)
path = models.CharField(max_length=500)
def __str__(self):
return "<Cover <path={}>".format(self.id, self.path)
populate_script
def add_book(title):
b = Books.objects.get_or_create(title = title)[0]
print(b)
b.save()
return b
def populate(scraped_tuple):
fake = Faker()
for _ in range(len(scraped_tuple)):
b_title = scraped_tuple[_][0][0]
new_book = add_book(b_title)
b_author_first = scraped_tuple[_][0][1].split(" ")[0]
b_author_last = scraped_tuple[_][0][1].split(" ")[1]
b_pages = scraped_tuple[_][0][2].split(" ")[0]
b_publ_year = fake.year()
b_edition = scraped_tuple[_][0][3].split(",")[0]
b_cover = scraped_tuple[_][0][4]
new_details = Book_details.objects.get_or_create(book = new_book, pages = b_pages, publ_year = b_publ_year, edition = b_edition)[0]
new_author = Author.objects.get_or_create(book = new_book, first_name = b_author_first, last_name = b_author_last)[0]
new_cover = Cover.objects.get_or_create(book = new_book, path = b_cover)[0]
The scraped_tuple is a return value from the webscraper containing the details.
(Part of) the Traceback:
Books.models.DoesNotExist: Author matching query does not exist.
File "C:\path\to\LibraryApp\Library_WebA
pp\Library\populate.py", line 45, in populate
new_author = Author.objects.get_or_create(book = new_book, first_name = b_author_first, last_nam
e = b_author_last)[0]
Followed by:
ValueError: "<Author: Mary McCarthy>" needs to have a value for field "id" before this many-to-many relationship can be used.
So, it seems that something goes awfully wrong when trying to execute the new_author statement, because of the many-to-many field "book" in the Author model. How can I resolve this. Do I need a similar function for an Author object like I have for the Book in add_book()?
It seems the new_details statement executes just fine (title and book_details appear correctly in the database in the admin part of Django).
As mentioned in the docs, user .add() to associate the records in many to many field.
def populate(scraped_tuple):
fake = Faker()
for _ in range(len(scraped_tuple)):
b_title = scraped_tuple[_][0][0]
new_book = add_book(b_title)
b_author_first = scraped_tuple[_][0][1].split(" ")[0]
b_author_last = scraped_tuple[_][0][1].split(" ")[1]
b_pages = scraped_tuple[_][0][2].split(" ")[0]
b_publ_year = fake.year()
b_edition = scraped_tuple[_][0][3].split(",")[0]
b_cover = scraped_tuple[_][0][4]
new_details = Book_details.objects.get_or_create(book = new_book, pages = b_pages, publ_year = b_publ_year, edition = b_edition)[0]
new_author = Author.objects.get_or_create(first_name = b_author_first, last_name = b_author_last)[0]
# add many to many fields this way:
new_author.book.add(new_book)
new_cover = Cover.objects.get_or_create(book = new_book, path = b_cover)[0]

Wagtail Snippets permissions per group

I have a Wagtail site where every group can work on a different page tree, with different images and documents permissions.
That is a multisite setup where I am trying to keep sites really separate.
Is that possible to limit the snippets permissions on a per-group basis?
I would like my groups to see just a subset of the snippets.
I was facing something similar when I wanted to use Site settings.
The only solution I found was to create a custom model and using ModelAdmin.
Some ‘snippets’ to get you on the run:
class SiteSettings(models.Model):
base_form_class = SiteSettingsForm
COMPANY_FORM_CHOICES = (
('BED', 'Bedrijf'),
('ORG', 'Organisatie'),
('STI', 'Stichting'),
('VER', 'Vereniging'),
)
site = models.OneToOneField(
Site,
unique = True,
db_index = True,
on_delete = models.CASCADE,
verbose_name = _('site'),
related_name = 'site_settings',
help_text = _('The sites these setting belong to.')
)
company_name = models.CharField(
_('company name'),
blank = True,
max_length = 50,
help_text = _('De naam van het bedrijf of de organisatie.')
)
company_form = models.CharField(
_('company form'),
max_length = 3,
blank = True,
default = 'COM',
choices = COMPANY_FORM_CHOICES
)
...
class MyPermissionHelper(PermissionHelper):
def user_can_edit_obj(self, user, obj):
result = super().user_can_edit_obj(user, obj)
if not user.is_superuser:
user_site = get_user_site(user)
result = user_site and user_site == obj.site
return result
class SiteSettingsAdmin(ThumbnailMixin, ModelAdmin):
model = SiteSettings
menu_label = _('Site settings')
menu_icon = 'folder-open-inverse'
add_to_settings_menu = True
list_display = ['admin_thumb', 'company_name', 'get_categories']
list_select_related = True
list_display_add_buttons = 'site'
thumb_image_field_name = 'logo'
thumb_col_header_text = _('logo')
permission_helper_class = MyPermissionHelper
create_view_class = CreateSiteSettingsView
...
class CreateSiteSettingsView(SiteSettingsViewMixin, CreateView):
#cached_property
def sites_without_settings(self):
sites = get_sites_without_settings()
if not sites:
messages.info(
self.request,
_('No sites without settings found.')
)
return sites
def dispatch(self, request, *args, **kwargs):
if request.user.is_superuser and not self.sites_without_settings:
return redirect(self.url_helper.get_action_url('index'))
return super().dispatch(request, *args, **kwargs)
def get_initial(self):
initial = super().get_initial().copy()
current_site = self.request.site
initial.update({
'company_name': current_site.site_name}
)
if self.request.user.is_superuser:
initial.update({
'site': current_site}
)
return initial
def get_form(self):
form = super().get_form()
flds = form.fields
if self.request.user.is_superuser:
fld = form.fields['site']
fld.queryset = self.sites_without_settings.order_by(
Lower('site_name')
)
return form
def form_valid(self, form):
instance = form.save(commit=False)
if not self.request.user.is_superuser:
instance.site = self.request.site
instance.save()
messages.success(
self.request, self.get_success_message(instance),
buttons=self.get_success_message_buttons(instance)
)
return redirect(self.get_success_url())

Django model inserting foreign key from same model

I am building a simple comment app in Django. The app allows replies to comments and uses the same model to store comments and replies. My issues is when I try to insert a new reply, the parentpost(FK to parent comment) inserts as NULL. When I use the admin interface to insert a reply, it properly stores the parentpost ID for the parentpost I choose. So I know the issue is not within my model but within my view.
/MODEL/
class UserPost(models.Model):
name = models.CharField(max_length=50)
slug = models.SlugField(max_length=50, unique=True,
help_text='Unique value for product page URL, created from name.', editable = False)
post = models.TextField()
is_active = models.BooleanField(default=True)
meta_keywords = models.CharField("Meta Keywords", max_length=255, blank = True, null = True,
help_text='Content for description meta tag')
meta_description = models.CharField(max_length = 255, blank = True, null = True,
help_text = 'Content for description meta tag')
created_at = models.DateTimeField(auto_now_add = True)
updated_at = models.DateTimeField(auto_now = True)
parentpost = models.ForeignKey('self', blank = True, null = True)
class Meta:
#app_label = ''
db_table = 'userposts'
ordering = ['created_at']
verbose_name_plural = 'UserPosts'
def __unicode__(self):
return self.name
#models.permalink
def get_absolute_url(self):
return ('lync_posts', (), {'posts_slug': self.slug})
def save(self):
if not self.id:
d = datetime.datetime.now()
s = d.strftime('%Y-%M-%d-%H-%M-%S-%f')
slugfield = str(self.name + s)
self.slug = slugfield
super(UserPost, self).save()
/VIEW/
def reply(request, slugIn):
parentpostIn = UserPost.objects.get(slug = slugIn)
pid = parentpostIn.id
template_name = 'reply.html'
if request.method == 'POST':
form = forms.ReplyPostForm(data = request.POST)
# create a new item
if form.is_valid(): # All validation rules pass
# Process the data in form.cleaned_data
# ...
if form.is_valid():
nameIn = form.cleaned_data['name']
postIn = form.cleaned_data['post']
newPost = UserPost(name = nameIn, post = postIn, parentpost = pid)
newPost.save()
return render_to_response(template_name, locals(), context_instance = RequestContext(request))
else:
# This the the first page load, display a blank form
form = forms.NewPostForm()
return render_to_response(template_name, locals(), context_instance=RequestContext(request))
return render_to_response(template_name, locals(), context_instance=RequestContext(request))
You are trying to set the parentpost ForeignKey by id.
You should either use:
newPost = UserPost(name = nameIn, post = postIn, parentpost = parentpostIn)
or (see Django: Set foreign key using integer?):
newPost = UserPost(name = nameIn, post = postIn)
newPost.parentpost_id = pid

Resources