2

I was wondering how I would be able to create an object in a database based the URL a user is going to.

Say for example they would go to /schedule/addbid/1/ and this would create an object in the table containing the owner of the bid, the schedule they bidded on and if the bid has been completed. This here is what I have for my model so far for bids.

class Bids(models.Model):
   id = models.AutoField("ID", primary_key=True, editable=False,)
   owner = models.ForeignKey(User)
   biddedschedule = models.ForeignKey(Schedule)
   complete = models.BooleanField("Completed?", default=False)

The biddedschedule would be based on the number in the URL as the 1 in this case would be the first schedule in the schedule table

Any ideas on how to do this?

3 Answers 3

6

You should get the id parameter using urls.py:

#urls.py
from appname.views import some_view

urlpatterns = patterns('',
    url(r'^schedule/addbid/(?P<id>\d+)$', some_view),
    ...
)

Take a look at the documentation about capturing parameters in the urlconf.

And then, in views.py you should construct a Bids Object using the id passed in the URL, the currently logged in user (request.user), and the biddschedule from your DB. For example:

#views.py
def some_view(request, id):
    if request.user.is_authenticated():
        # get the biddschedule from your DB
        # ...
        bids = models.Bids(id=id, owner=request.user, biddedschedule=biddedschedule)
        bids.save()
        return HttpResponse("OK")
    return Http404()
Sign up to request clarification or add additional context in comments.

Comments

2

Catch the number via the urlconf. Get the current user via request.user. Create a model instance by calling its constructor, and save it to the database via its save() method.

Comments

-1
`#view.py under a post or get method`

    new_bird, created = Bids.objects.get_or_create(
         owner = user_obj,
          biddedschedule = biddedschedule_obj,                
          complete = bool
          )
    new_bird.save()

1 Comment

Please explain what the code does and how it does it.

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.