I'm trying to autofill a form in django with the url variable that I set in urls.py, but I'm not really sure how I could be able to do this, I tried to use form.instance but apparently it only works with users, so here's the code so you can check out what I'm talking about.
views.py
class AddPostView(CreateView):
model = Post
form_class = PostForm
template_name = 'app1/createpost.html'
def form_valid(self, form, sym):
form.instance.author = self.request.user
form.instance.stock = self.request.sym
return super().form_valid(form)
models.py
class Post(models.Model):
title = models.CharField(max_length= 255)
header_image = models.ImageField(null = True, blank = True, upload_to = 'images/')
author = models.ForeignKey(User, on_delete=models.CASCADE)
body = RichTextField(blank = True, null = True)
#body = models.TextField()
post_date = models.DateField(auto_now_add=True)
category = models.CharField(max_length=255, default='coding')
snippet = models.CharField(max_length=255)
likes = models.ManyToManyField(User, related_name = 'blog_posts')
stock = models.ForeignKey(StockNames, null=True, on_delete = models.CASCADE)
def total_likes(self):
return self.likes.count()
def __str__(self):
return self.title + ' | ' + str(self.author)
def get_absolute_url(self):
return reverse('app1:article-detail', args=(self.id,))
class StockNames(models.Model):
name = models.CharField(max_length=255)
symbol = models.CharField(max_length=255)
def __str__(self):
return self.symbol
urls.py
urlpatterns = [
path('add_post/<str:sym>',AddPostView.as_view(), name='addpost'),
]
forms.py
class Meta:
model = Post
fields = ('title','category', 'body', 'snippet', 'header_image', 'stock')
widgets = {
'title': forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Title', 'length':'100px'}),
#'author': forms.TextInput(attrs={'class': 'form-control', 'value': '', 'id':'elder','type': 'hidden'}),
#'author': forms.Select(attrs={'class': 'form-control'}),
'category': forms.Select(choices = choice_list,attrs={'class': 'form-control', 'placeholder': 'Choices'}),
'body': forms.Textarea(attrs={'class': 'form-control'}),
'snippet': forms.Textarea(attrs={'class': 'form-control'}),
'stock': forms.Select(choices = choice_list,attrs={'class': 'form-control', 'placeholder': 'Choices'})
}
template
{% extends 'app1/base.html' %}
{% load static %}
{% block body_block %}
{% if user.is_authenticated %}
<h1>Add Blog Post</h1>
<br><br>
<div class="form-group">
<form action="" method="post" enctype = "multipart/form-data">
{% csrf_token %}
{{form.media}}
{{form.as_p}}
<button class= "btn btn-secondary">Post</button>
</form>
</div>
<script>
var name = "{{user.id}}";
document.getElementById("elder").value = name;
</script>
{% else %}
You need to log in
{% endif %}
{% endblock %}