1

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 %}

1 Answer 1

3

you can override the def get_initial() on your createview and add the values there so that is prepopulates your forms in the view.

example

def get_initial(self):
    """
    Returns the initial data to use for forms on this view.
    """
    initial = super().get_initial()

    initial['my_form_field1'] = self.request.something

    return initial

Add this to your view and update the fields of your form with the correct value and return the initial afterwards.

to get the value from the url to your get_initial do something like:

example

    """
def __init__(self, **kwargs):
    Constructor. Called in the URLconf; can contain helpful extra
    keyword arguments, and other things.
    """
    # Go through keyword arguments, and either save their values to our
    # instance, or raise an error.
    self.somevalue = kwargs.get('sym')
   

by overriding the def init() you can have access to the urlconf arguments that are being passed with it. So when you assign the sym to self.somevalue.

The self.somevalue becomes available. You can then call the self.somevalue in the get_initial() function and pass that value to the correct formfield.

Sign up to request clarification or add additional context in comments.

4 Comments

How can I override it?
In self.request.something how can I request the variable <str:sym> in urls.py?
thanks! One last question, where do I put that def init function?
oeps, my bad. also in your view class AddPostView(CreateView):

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.