所以我有这个帖子模块:
using System;
using System.Linq;
using System.IO;
namespace ConsoleApp
{
class Program
{
static string path = @"path\to\csv_file.csv";
public class Person
{
public int Id { get; set; }
public string Name { get; set; }
public string PreferredFood { get; set; }
public override string ToString()
{
// Matches what a csv line looks like
return $"{Id},{Name},{PreferredFood}";
}
}
static void Main(string[] args)
{
var lines = File.ReadAllLines(path); // Read all lines of a csv file
var groups = lines
.Skip(1) // Skip header line
.Select(line => line.Split(',')) // Split by comma
.Select(column => new Person
{
Id = int.Parse(column[0]),
Name = column[1],
PreferredFood = column[2]
})// Convert to Person
.GroupBy(person => person.PreferredFood); // Group by preferred food
foreach (var group in groups)
{
var foodPath = Path.Combine(Path.GetDirectoryName(path), $"{group.Key}.csv"); // Create unique filename for each csv
var foodOutput = new string[] { lines[0] } // Add header line
.Concat(group.ToList().Select(person => person.ToString())); // Concatenate all other lines
File.WriteAllLines(foodPath, foodOutput); // Write output to csv foodPath
}
Console.ReadKey();
}
}
}
和此评论模块:
class Post(models.Model):
title = models.CharField(max_length=50)
content = models.TextField(max_length=255)
author = models.ForeignKey(User, on_delete=models.CASCADE)
date_pub = models.DateTimeField(timezone.now)
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse('blog-home')
这是我对此发表的看法:
class Comment(models.Model):
post = models.ForeignKey(Post, on_delete=models.CASCADE)
comment_author = models.ForeignKey(User, on_delete=models.CASCADE)
content = models.TextField(max_length=255)
def get_absolute_url(self):
return reverse('blog-home')
关于网址:
/ post / 1 ===>将是1号帖子
/ post / 1 / comment ===>是发布新评论的形式
我希望form.instance.post_id是评论所属的帖子ID。
我该怎么做?
答案 0 :(得分:0)
我猜测您的网址格式与此类似:
path('post/<int:pk>/comment', CreateComment.as_view(), name='create_comment')
这就是我要做的(假设SingleObjectMixin与CreateView结合使用):
from django.views.generic.detail import SingleObjectMixin
class CreateComment(LoginRequiredMixin, CreateView, SingleObjectMixin):
model = Comment
template_name = 'my_blog/create_post.html'
fields = ['content']
def form_valid(self, form):
form.instance.comment_author = self.request.user
form.instance.post = self.get_object()
return super().form_valid(form)
答案 1 :(得分:0)
form.instance.post_id = self.kwargs['pk']
是我要找的东西