Question

I'm new to django. I have such models:

class Category(models.Model):
    category = models.CharField(max_length=20)

    def __unicode__(self):
        return self.category

class Tag(models.Model):
    tag = models.CharField(max_length=30, blank=True)


    def __unicode__(self):
        return self.tag

class News(models.Model):
    title = models.CharField(max_length=80)
    category = models.ForeignKey(Category)
    author = models.ForeignKey(User)
    news_body = models.CharField(max_length=5000)
    pub_date = models.DateField(default = datetime.datetime.now())
    tags = models.ManyToManyField(Tag, blank=True)

    def __unicode__(self):
        return self.title

And form, for adding news:

class AddNewsForm(ModelForm):
    class Meta():
        model = News

I have a problem with ModelChoiceField representation in template. I want use <select>/<option> tags like so:

<select id="id_category" name="category">
<option value="" selected="selected">---------</option>
{% for cat in form.category  %}
<option>{{cat}}</option>
{% endfor %}
</select>

But it's don't work. How can I get category-field choices (to iterate through them). It's an easy question, but I'm confused and can't find working solution.

With {{ form.as_p }} it works well, but I need to hide author field (author - logged in user).

Was it helpful?

Solution

A cleaner way to hide the author from the form would be

class AddNewsForm(ModelForm):
    class Meta:
        model = News
        exclude = ('author', )

and in the views:

@login_required
def myView(request):
    #some code here
    if request.POST:
        form = AddNewsForm(request.POST)
        if form.is_valid():
            news = form.save(commit=False)
            news.author = request.user
            news.save()

     #rest of the code

and let the template load the default way {{ form.as_p }}

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top