Need Help with Django Forms/Models

Hi there! I need help, Obi-Wan!

So, I have created a Model class that is supposed to be a Comment Model for posting comments on listings. I have a Form that takes all of these fields and only shows one field to the user to fill in. All the rest should be filled in automatically. I am not sure how to do this step. I obviously don’t want the user to be able to manipulate “date posted” or “listing id” etc. But when I get the Django Comment Form back I just get the body field back and either stuff the View full of things that aren’t working.

I feel like I should just be able to pull the individual “comment_body” attribute from the Django form and the model should populate the rest of the information. I am so lost I’ve been working on this for two days. Sorry if this is already answered you’d think it’d be easy to find but I’ve watched 15 tutorials, read documentation until my brain turned into primordial soup and can’t find help on Discord. So thank you to anyone who helps out.

Code Below.

Models:

class Comment(models.Model):
    # this is the comment's listing it's tied to, 
    # the comment body, the date, and the author posting it.

    comment_listing = models.ForeignKey(Listing, on_delete=models.CASCADE, related_name="comments")
    comment_body = models.CharField(max_length=800)
    comment_date = models.DateTimeField(editable=False)
    comment_author = models.ForeignKey(editable=False)

    class Meta:
        ordering = ['comment_date']

Forms:

from .models import Comment
from django import forms
from django.db import models


class CommentForm(forms.ModelForm):
    class Meta:
        model = Comment
        fields = '__all__' 

# I'm having to put fields= all because when I just try to do
# fields = ('body,',) or fields=['body',] or any alternative
# i get errors all over the place. the only solve i found after hours
# was to make the form have all the fields and only display the 
# comment.comment_body attribute in the template. 

Views:

def listing_view(request, listing_id):
    item_listing = Listing.objects.get(pk=listing_id)
    comments = item_listing.comments.all()
    new_comment = None

    if request.method == "POST":

        time = timezone.now
        data = {'comment_listing': listing_id, 
                'comment_date':time,
                'comment_author':'_', 
            # ('_' is a placeholder, haven't solved getting the user yet)
                'id_comment_body':request.POST['comment_body']
}

       comment_form = CommentForm(data=request.POST)
# first attempt, ^^ this did not work because i only get back the body 
# and have trouble adding the other fields to this form)

        comment_form=CommentForm(data) 
# (this was my final method, ^^ 
# but this does not work either. Both adding those dict values to the form
# AND using request.POST to add 'comment_body' to the form.)


        if comment_form.is_valid():
            new_comment = comment_form.save(commit=False)
            new_comment.item_listing = item_listing
            new_comment.save()
    else:
        comment_form = CommentForm(initial={'comment_listing': listing_id, 'comment_date':timezone.now,
        'comment_author':User})
# this ^^ is a little later on, I tried pre-populating the form with 
# all of the other attributes and only adding # the 'body' attribute. 
# this failed as well.


    return render(request, "auctions/listing_page.html", {
    "item":item_listing,
    "comments":comments,
    "newcomment":new_comment,
    "comment_form":comment_form,
    })
template - just the form section

    <form method="POST">
        {{ comment_form.comment_body }}
        {% csrf_token %}
        <br><br>
        <input type="submit" value="Submit" class="btn btn-primary">
    </form>

Many issues to be addressed here.

  • Your comment_author field isn’t defined properly.

  • You have:

No, you don’t need (or want) fields='__all__'. The errors you’re getting as a result of specifying the individual field name indicate something else is wrong. (Note: Your field name is comment_body, not body.)

  • You have:

All unnecessary and should be removed.

  • You have:

Yes, this is what works and should be what you have.

  • You have:

Remove this.

  • You have:

Very close to being on the right track here.

However, the field in your Comment model you’re referencing above is not called item_listing, it’s comment_listing.

For the comment_date field, look at the auto_now attribute.

Then identify what you want the comment_author field to be and set it.

Then save the new and modified object.

Wow, awesome! I got Ken to answer! I asked for Obi-Wan and I got him! Awesome. Thanks for responding, you’re just the pro I was hoping for.

Maybe the comments I added made it unclear what I was communicating in the code I posted- I wasn’t trying to do all of those individual things those were just the methods I tried. I will refactor the code and report back. I really really appreciate your input.

In response:

You were so right. I was using ‘body’ instead of ‘comment_body’. DOH #1.
comment_date is now auto_now_add, way easier than the datetime thing. DOH #2
saving item_listing not comment_listing… DOHHHH #3
wow. you rock!!!

Here is the code I’ve refactored:

class Comment(models.Model):
    # user = models.ForeignKey('User', on_delete=models.CASCADE)
    comment_listing_id = models.ForeignKey(Listing, on_delete=models.CASCADE, related_name="comments")
    comment_body = models.CharField(max_length=800)
    comment_date = models.DateTimeField(auto_now_add=True)
    comment_author = models.ForeignKey(User, on_delete=models.SET_NULL, null=True)
    # listing_rating = models.PositiveIntegerField(default=1, validators=[MinValueValidator(1), MaxValueValidator(5)])
    class Meta:
        ordering = ['comment_date']
def listing_view(request, listing_id):
    item_listing = Listing.objects.get(pk=listing_id)
    comments = item_listing.comments.all()
    new_comment = None

    if request.method == "POST":
        comment_form = CommentForm(data=request.POST)
        if comment_form.is_valid():
            new_comment = comment_form.save(commit=False)
            new_comment.comment_listing_id = item_listing
            new_comment.comment_author = request.user
            new_comment.save()
    else:
        comment_form = CommentForm()

    return render(request, "auctions/listing_page.html", {
    "item":item_listing,
    "comments":comments,
    "newcomment":new_comment,
    "comment_form":comment_form,
    })

from .models import Comment
from django import forms
from django.db import models


class CommentForm(forms.ModelForm):
    class Meta:
        model = Comment
        fields = ['comment_body',] 

I really appreciate your help! It’s working now! Now I’m trying to figure out how to allow myself to delete comments in the admin panel without deleting the listing. I’m guessing it’s the on_delete attribute. I’ve tried setting comment_author to “on_delete:SET_NULL” so that if the user is deleted, their comments won’t delete. But that has no effect on untying the comments from the listing. I like that they’re tied together in a manytomany table but is there a way to be able to delete a comment from a listing without deleting the listing? that’s how it’s working right now. Thanks again Ken!!

I’ve marked this as solved, and you don’t have to respond, but if you could since you’re such a pro, maybe you could help me understand how to address these concerns:

  1. if you delete a comment, you must delete an entire listing. This is a major issue. Lol.

  2. if you delete a user, their comments stay: excellent. it says “deleted_user”, since i have {{ comment_author | default: “deleted_user” }}. excellent. in our database, it says “NULL”. Not excellent. we want to retain the commenter’s info but delete their username on the website, protecting ourselves and for posterity internally.

  3. in admin, if you’re in listing #1 and look at the comments, you can see other listing’s comments. This is a problem. I can delete listing #2’s comments while in listing #1. they’re all in one major comments pool. This needs to be fixed. Each comment group should be grouped together with a listing, not with each other in a group in the admin interface. maybe this is unavoidable for now but should be addressed.

any ideas here, ken? or others? thanks a million again, really invaluable that I can get such incredible help so quickly.

No(?) How are you trying to delete a comment such that the listing is being deleted?

Actually, “standard” practices are to never “delete” a user. The standard Django User model has the is_active attribute that can be used to deactivate a user without removing their entry from the database. (Now, if you’re subject to GDPR requirements, you might still want to delete a user, but in that case you’d want all their information to go away anyway.)

That’s likely an issue with how you have your ListingAdmin class defined.

(Otherwise, I’m not sure of what you mean by “if you’re in listing #1 and look at the comments,”.)

If I’m in the admin panel and click into “Listings” it has all comments for all listings listed- so if i’m in listing #1 in admin I can see the comments for Listing #2, etc. and If i try to select the comments I want to delete it makes me delete the whole listing it’s associated with

Please post your admin classes here.

1 Like
from django.contrib import admin

# Register your models here.

from .models import Listing, Comment, User

admin.site.register(Listing)

admin.site.register(User)


# (not active)
# admin.site.register(ListingBids)

# admin.site.register(Comments)

I think I figured it out. I was in “Listing” in Admin panel and since the comment is tied to the listing it would cascade that delete. If i set the attribute to Do_nothing then it is not tied. Also I was trying to delete the comment by selecting it in the field and hitting “delete” but that needs to happen from the registered Comment class in Admin. Thank you again Ken.

AGH! I need help!

Here’s what I’m trying to do:

I’m trying to look in a Bids database, look up the item’s key, and if there aren’t any bids, set the minimum bid to the starting bid. If there are bids tied to that key, I’d like to return the max (highest) bid in the bid list. I have tried this 10 different ways and I know I’m doing something wrong because I can’t figure out how to get it to work. Any ideas?

View for listing/bidding view

def listing_view(request, listing_id):
    item_listing = Listing.objects.get(pk=listing_id)
    testbid = ListingBids(pk=listing_id)

    if testbid.auction_id == None:
        print('no bids exist! setting to starting bid!')
        minimum_bid = item_listing.starting_bid
    else:
        print('bid(s) exist!')
        minimum_bid = max(item_listing.listing_bids)


    if request.method == "POST":
        bidform = BidForm(data=request.POST)
        submitted_bid = request.POST['bid']
        submitted_bid = float(submitted_bid)
        if submitted_bid < minimum_bid:
            errormessage = 'Bid is too low!'
            return render(request, "auctions/listing_page.html", {
                                    "item":item_listing,                                                                   
                                    "bid_form":bidform,
                                    'bid_amount':minimum_bid,
                                    'message':errormessage
                                    })        
        else:
            if bidform.is_valid():
                newbid = bidform.save(commit=False)
                newbid.bid_author = request.user
                print('bidform is valid!')
                newbid.auction_id = item_listing 
                newbid.save()
                bidform = BidForm()
                minimum_bid = submitted_bid+1
    else:
        bidform = BidForm()

    return render(request, "auctions/listing_page.html", {
    "item":item_listing,
    "bid_form":bidform,
    'bid_amount':minimum_bid,
    })

Models:

class ListingBids(models.Model):
    bid = models.FloatField(null=True)
    auction_id = models.ForeignKey(Listing,on_delete=models.DO_NOTHING, related_name="bids")
    bid_author = models.ForeignKey(User, on_delete=models.DO_NOTHING, null=True, related_name='bidder')

class Listing(models.Model):
    listing_author = models.ForeignKey(User, on_delete=models.CASCADE, related_name="user_listings")
    listing_title = models.CharField(max_length=80)
    listing_description = models.CharField(max_length=800)
    starting_bid = models.FloatField()
    listing_image = models.URLField(default='https://tinyurl.com/yjzvdy7t')
    category = models.CharField(max_length=80, choices=auction_categories)
    listing_comments = models.ManyToManyField('Comment', blank=True)
    listing_bids = models.ManyToManyField('ListingBids', blank=True, related_name='bid_list')



Using the automatically created related object manager, the set of all ListingBids related to a Listing named listing, based on the related name, would be listing.bids.all().

Of course you don’t need to use all, you can use exists to determine whether or not any related items are present, or order_by to sort the related queryset by a field in the related table.

Wow, awesome. This totally solved my problem. Thanks Ken!

Now I’m working on adding a Watchlist. I have bids down, and comments down (thanks to your help!)

I have the model worked out I think, but I’m stuck handling multiple forms on the listing page. I’m structuring the view how I’ve seen suggested online, but getting errors, like MultiValueDictKeyError, etc.

Any ideas?

TL;DR: Trying to update Watchlist/Comment/Bid without triggering any other forms, just isolate post data and save it.

i’m not even trying to figure out if the item is on a user’s watchlist and then dynamically display add/remove yet, just trying to figure out how to save it without throwing an error.

I’m restricting myself to no class views and no JS/Ajax. This is for a class and we aren’t supposed to know that stuff so I’m trying to do this this way so I can learn all this functionality. ps. you are a rockstar

View

def listing_view(request, listing_id):
    item_listing = Listing.objects.get(pk=listing_id)
    minimum_bid = item_listing.starting_bid # set minimum bid at starting bid, then if bids exist, adjust minimum bid to max of bids + $1
    bid_message = ''
    total_bids = item_listing.bids.all()
    total_length = len(total_bids)
    if total_length == 0:
        print('its empty')
        # it's empty, leave minimum bid as is.
    else:
        print('there be bids')
        highest = (item_listing.bids.latest('bid'))
        minimum_bid = highest.bid + 1

        print('current bid of user:')
        print(highest.bid_author) # this is the user who has the highest bid. give access to this in the template.
        if request.user == highest.bid_author:
            bid_message = 'Your bid is the current highest bid.'
        

    if request.method == "POST":
        if 'watchlist_button' in request.POST: 
            watch_switch = request.POST['watchlist_button']
            watch_message = 'This item is on your watch list'
            watchlist = Watchlist.objects.create(watchlist_user=request.user, item=item_listing)
        else:
            watch_switch = False

## i'm not even trying to figure out if the item is on a user's watchlist and then dynamically display add/remove yet, just trying to figure out how to save it without throwing an error. 

        if request.POST['bid'] in request.POST:
            bidform = BidForm(data=request.POST)
            submitted_bid = request.POST['bid']
            submitted_bid = float(submitted_bid)         
            if submitted_bid < minimum_bid:
                errormessage = 'Bid is too low!'
                return render(request, "auctions/listing_page.html", {
                                        "item":item_listing,                                                                   
                                        "bid_form":bidform,
                                        'bid_amount':minimum_bid,
                                        'num_of_bids':total_length,
                                        'message':errormessage,
                                        'bid_message':bid_message
                                        })        
            else:
                if bidform.is_valid():
                    newbid = bidform.save(commit=False)
                    newbid.bid_author = request.user
                    print('bidform is valid!')
                    newbid.auction_id = item_listing 
                    newbid.save()
                    bidform = BidForm()
                    minimum_bid = submitted_bid+1
                    highest = (item_listing.bids.latest('bid'))
                    if request.user == highest.bid_author:              # give user update on their bid, let them know they are in the lead.
                        bid_message = 'Your bid is the current highest bid.' 
                    total_bids = item_listing.bids.all()            # re do the math of total bids, update number
                    total_length = len(total_bids)

    else:
        bidform = BidForm()
    print(minimum_bid)
    return render(request, "auctions/listing_page.html", {
    "item":item_listing,
    "bid_form":bidform,
    'num_of_bids':total_length,
    'bid_message':bid_message,
    'bid_amount':minimum_bid,
    })

So what specifically are you having problems with here?

If you’re encountering an error message, please post the complete traceback.

Otherwise, please describe what’s not happening that you expect to have happen - or what’s not happening that you’re expecting to see.

I’m sure you’ve tried a number of different things, but I can only work from what you post, and it’s generally not helpful to try and diagnose multiple attempts in parallel. So lets pick one starting point and work forward from there.

(Also, unless I’m overlooking it, I don’t see your listing_page.html template in this thread - seeing that will help.)

Ok! Man it sure makes my day seeing you in my notifications still gung ho to help :slight_smile:

So, I’ve fixed my multi dict key error and I have the ability to enter a bid or enter a comment, both form fields on the page, working great (for now. LOL).

Here is my current problem:

I have a third Django form on the page, hidden, submitting a value with a button: Add to Watchlist. This fires a model signal to save this item to someone’s watchlist. This works right now. It isn’t querying the model to see if it’s already on or able to take it off, but it is sending it and saving it. I’m pausing there. I was just trying to get to the place where I could save it. Now it is doing that. But I’m sort of stuck here because the actual model/object isn’t looking how I thought it would.

I am really worried I’m mucking up my models because I’m struggling to understand ManyToMany or ForeignKey and when the right time to implement is… poking around on the net it seems using a Watchlist Model in django, people use both! I’ve implemented mine using ForeignKeys for the User whose watchlist it is, and the item on the list.

Here are my problems:

When I’m in the admin panel, and click on “Watchlists”, I’m expecting to see a list of users, I click on the user, it lists all the items, says “yes” or “no” essentially. But instead, I see “Watchlist objects” and when I click into one, it shows a dropdown field of all the other auctions on the site. I just am not getting this. I feel i’m slightly grasping templating and django variables and even views stuff… slightly. but the models are difficult for me. I’ll post my models and view below. Thanks again Ken, if you want I’ll send you some Christmas cookies we got some peanut butters baking right now! haha

My View:

def listing_view(request, listing_id):
    item_listing = Listing.objects.get(pk=listing_id)
    minimum_bid = item_listing.starting_bid # set minimum bid at starting bid, then if bids exist, adjust minimum bid to max of bids + $1
    bid_message = ''
    current_user = User.objects.get(username=request.user)
    watch_message = ''
    comments = item_listing.comments.all()
    new_comment = None
    comment_form = CommentForm()
    watchform = WatchForm()
    bidform = BidForm()
    total_bids = item_listing.bids.all()
    total_length = len(total_bids) # total number of bids for given item/listing

    if total_length == 0:
        print('its empty')
        # it's empty, leave minimum bid as is.
    else:
        highest = (item_listing.bids.latest('bid'))
        minimum_bid = highest.bid + 1
        if request.user == highest.bid_author:
            bid_message = 'Your bid is the current highest bid.'

    if request.method == "POST":
        if 'comment_body' in request.POST:      # if comment is being posted, do this
            comment_form = CommentForm(data=request.POST)
            if comment_form.is_valid():
                # Create Comment object but don't save to database yet
                new_comment = comment_form.save(commit=False)
                # Assign the current post to the comment
                new_comment.comment_listing_id = item_listing
                new_comment.comment_author = request.user
                # Save the comment to the database
                new_comment.save()
                comment_form = CommentForm()
        if 'bid' in request.POST:               # if bid is being posted, do this
            bidform = BidForm(data=request.POST)
            submitted_bid = request.POST['bid']
            submitted_bid = float(submitted_bid)
            print('printing bidform bid:')
            print(submitted_bid)
            if submitted_bid < minimum_bid:
                errormessage = 'Bid is too low!'
                print(errormessage)
                return render(request, "auctions/listing_page.html", {
                                        "item":item_listing,                                                                   
                                        "bid_form":bidform,
                                        'bid_amount':minimum_bid,
                                        'num_of_bids':total_length,
                                        'message':errormessage,
                                        'bid_message':bid_message,
                                        'watch_message':watch_message,
                                        'watch_form':watchform
                                        })        
            else:
                if bidform.is_valid():
                    newbid = bidform.save(commit=False)
                    newbid.bid_author = request.user
                    print('bidform is valid!')
                    newbid.auction_id = item_listing 
                    newbid.save()
                    bidform = BidForm()
                    minimum_bid = submitted_bid+1
                    highest = (item_listing.bids.latest('bid'))
                    if request.user == highest.bid_author:              # give user update on their bid, let them know they are in the lead.
                        bid_message = 'Your bid is the current highest bid.' 
                    total_bids = item_listing.bids.all()            # re do the math of total bids, update number
                    total_length = len(total_bids)
        
        
        if 'watchlist_button' in request.POST: 
            w = WatchForm(data=request.POST)      #get the item ID
            w = watchform.save(commit=False)
            w.watchlist_user = request.user       # assign the user to it.
            w.save()
            watch_message = 'This item is on your watch list'
            watchform = WatchForm()
            watch = Watchlist()

    else:
        bidform = BidForm()
        comment_form = CommentForm()
    return render(request, "auctions/listing_page.html", {
    "item":item_listing,
    "bid_form":bidform,
    "comments":comments,
    "newcomment":new_comment,
    "comment_form":comment_form,
    'num_of_bids':total_length,
    'bid_message':bid_message,
    'bid_amount':minimum_bid,
    'watch_message':watch_message,
    'watch_form':watchform
    })
Models:

class Watchlist(models.Model):
    watchlist_user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='user_watchlist')
    item = models.ForeignKey(Listing, null=True, on_delete=models.CASCADE, related_name='watchlist')





class User(AbstractUser):
    user_comments = models.ManyToManyField('Comment', blank=True, related_name="user_comments")
    user_auctions = models.ManyToManyField('Listing', blank=True, related_name='auctions')

## comments / deprecated fields below
    # user_bids = models.ManyToManyField()
    # user_watchlist = models.ForeignKey('Listing', null=True, on_delete= models.CASCADE, related_name='watchlist')
    # user watchlist could be a model of its own... 
    # watchlist holds a field for the user that owns the watchlist, with all items that are on the watchlist.



class Listing(models.Model):
    auction_categories = [
    ("FASHION", "Fashion"),
    ("TOYS", "Toys"),
    ("ELECTRONICS", "Electronics"), 
    ("HOME", "Home"),
    ("SHOES", "Shoes"),
    ("OTHER", "Other",)
]


    listing_author = models.ForeignKey(User, on_delete=models.CASCADE, related_name="user_listings")
    listing_title = models.CharField(max_length=80)
    listing_description = models.CharField(max_length=800)
    starting_bid = models.FloatField()
    listing_image = models.URLField(default='https://tinyurl.com/yjzvdy7t')
    category = models.CharField(max_length=80, choices=auction_categories)
    listing_comments = models.ManyToManyField('Comment', blank=True)
    listing_bids = models.ManyToManyField('ListingBids', blank=True, related_name='bid_list')

    def __str__(self):
        return f"Listing #{self.id}: {self.listing_title}, starting bid is ${self.starting_bid}. Category: {self.category}\
        \n Listing Image {self.listing_image} Listing Description {self.listing_description}"

This time I’ll include my template as well, don’t think that’ll help here but you’re the wizard!

{% extends "auctions/layout.html" %}

{% block body %}
<div class="listing-heading-div">
<h1>
Listing: {{item.listing_title}}
</h1>
</div>
<div class="container-fluid">
    <div class="row pt-1" id="listing-image-div">
        <img src="{{item.listing_image}}" width="300" height="300">
    </div>

    <div class="row pt-1" id="item-description-div">
        <h6>{{item.listing_description}}</h6>
    </div>

    <div class="row pt-2" id="bid-div">
        <div class="listing-message-div">
        {% if message %}
        {{ message }}
        {% endif %}
        <br>
        </div>
        <div>
       <br> <br><h2>${{bid_amount|floatformat:2 }}</h2>
        </div>
    </div>
    <div class="row pt-2" id="num-of-bids-div">
        {{ num_of_bids }} bid(s) so far. {% if bid_message %} {{bid_message}} {% endif %}
    </div>
    <div class="row pt-2" id="bid-field-div">
        <form method="POST">
            {{ bid_form }}
            {% csrf_token %}
        <div class="col-2">
            <input type="submit" value="Submit Bid" class="btn btn-primary">
            </div>
        </form>

        <div class="col-2">
        <form method="POST">
            {{ watch_form.as_hidden  }}
            {% csrf_token %}
            <button type='submit' name='watchlist_button' value="{{ item.id }}" class="btn btn-primary">Add to Watchlist</button>
        </form>
        {% if watch_message %}
        {{ watch_message }}
        {% endif %}
        </div>
    </div>





    <div class="row pt-2" id="listing-page-details-div">
        <h2>
            Details
        </h2>
    </div>
    <div class="row" id="listing-page-details-list">
            <ul>
            <li>
                Listed by: <a href="{% url 'user_listings' listing_owner=item.listing_author  %}">{{ item.listing_author }}</a>
            </li>
            <li>
                Category: <a href="{% url 'category_detail' category=item.category  %}">{{ item.category|lower|capfirst }}</a>
            </li>
            </ul>
    </div>

        <div class="col-2 pt-4 pl-5">       
        </div>
        
        <div class="col-6 pt-5">
        </div>

        <div class="col-3">
        </div>


</div>
    


<div class="commentdiv">
    <br>    
    variables on this page:
    <br>
    "newcomment"
    "comment_form"
    <br>
    <h1>Comments:</h1>
    {% for comment in comments %}

    <div class="individualcomment"> 
        {{ comment.comment_author| default:"deleted_user" }} 
        <br>
        {{ comment.comment_date}}  
        <br>
        {{ comment.comment_body}}
        <br><br>
    
    
    </div>
    {% empty %}
    
    {% endfor %}

    <br>
    <br>
    <h2>Leave a Comment:</h2>
    <br>
    <form method="POST">
        {{ comment_form.comment_body }}
        {% csrf_token %}
        <br><br>
        <input type="submit" value="Submit" class="btn btn-primary">
    </form>


</div>
{% endblock %}

ps. I also think my listing model is messed up as well because when I go into both users in the admin their “user auctions” both say all the listings, even though only one user listed them and is the listing author in the sqlite file. So if user_id “2” is the auction author in the sqlite table why are all the listings listed on all user page as user auctions? I feel like Beaker after a bad experiment…

I’ll include an image that shows clearly what I mean in the admin view as well.



No, when you click on the name of a model in the Admin, you’re going to get a list of the instances of that model. If you select a specific instance of a model in the list display, you’re going to see the fields of that instance of the model.

So given your model Watchlist, I would expect to see a select box by default with one user selected.

The admin images you’ve posted look exactly as I would expect them to look.

Keep in mind that the admin is an application that is completely separate from your templates and views that you create for your application. Your listing_view has nothing to do with what the admin is going to generate.

If anything, it appears to me like you’re confusing views and templates that you are writing with what the admin automatically generates out of the box. They’re really two very separate things.

Ok. Thank you for the response. I appreciate all your help. I’ve got most of the app and functions working correctly now.

Final question for you- I’m using the login_required decorator on entire pages that require an authenticated user, but within the listing view where all these forms and models are, I am allowing anyone to view, but only logged-in users to POST data.

I have a system now that currently redirects them to login inside of the view but best case scenario would be to send the POST data along with them, redirect to the original page, AND post that original data (e.g. comment/bid/watchlist).

Also, in my current method, they’re getting redirected to the index page, not the original page. And that’s if I use the login_required AND the redirect method in the view, on all views, they get redirected to the index even if it says "/?next=/'…blahblahblah.

I can’t figure out what I’m missing. Thanks again, redirect is below.

    if request.method == "POST":
        if not request.user.is_authenticated:
            current_path = request.path
            updated_path = '/login/?next=' + current_path
            return HttpResponseRedirect(updated_path, {
                'package':request.POST
            })

First, you’re not going to be able to do what you describe as your “best case” without a bit of additional work. You’re not going to be able to just keep passing the post data through the login page - the redirect results in the browser doing a GET on the destination, not a POST.

You may not even be able to store the data in session - I believe there are circumstances where authentication will result in a new session ID being generated, losing whatever was stored in the original session.

I think one option would be to store the data itself in a custom cookie that you can check after the authentication occurs. (Or, if it’s too much data to be reasonably saved in a cookie, you could create a custom cookie just to store an ID for the temporary storage of that submitted data.)
A third option would be to perform the entire authentication process through AJAX requests using a modal dialog box that wouldn’t affect the original page or the data in the form. So you’ve got some options, but none of them are trivial.

Regarding the redirect, I’d need a bit more information to even begin to diagnose that.
What view is /login/? mapped to in your urls.py? What are you seeing as the url being sent to the browser? (What are the full contents of the next query variable?) What requests are you seeing on the server log? What requests are you seeing in your browser’s developer tools? (What is your LOGIN_URL setting?)