Wednesday, July 25, 2012

Re: render a models slug field as a url



On Wednesday, 25 July 2012 02:42:45 UTC+1, Matthew Meyer wrote:
Hello all,

I'm trying to load the url of a model created with get_absolute_url() programmatically in my view. There are basically three steps I need to accomplish this:

1. make sure @permalink is working correctly. This step I am fairly confident I have completed. Here is the model I use: http://dpaste.org/nH0cZ/

2. make sure I am rendering the url correctly in my view: http://dpaste.org/FOGjs/ 

This view is fairly involved. The return statement on line 12 is where I am trying to load the url. In a nutshell, if the request is GET this view renders a form for the user which they can use to fill some fields in a model. one of the fields they fill ("name") I want to use as my the rendered url, which is why I am trying to pass {'event': Event} on line 12 when request.method == 'POST' and the user has submitted the form. Right now when the user submits the post, the event_page.hml loads but without the event object url.

3. make sure my urlconfs are working:: http://dpaste.org/LPdfK/ Not positive here, but I know this is fairly simple to most. I just tried to follow what the docs had for get_absolute_url and @permalink (https://docs.djangoproject.com/en/dev/ref/models/instances/?from=olddocs#django.db.models.permalink) Something is wrong though because the "view on website" button in admin is leading to a permalinked url that doesn't match.

As you can see, I am quite a bit lost and could really use some guidance. Any help is appreciated. Thanks!


Your problem is in step 2. `Event` is the model class itself, but you want to render the URL for a particular instance of that class. Presumably you want the event that has been created by the form. I don't understand why you are using a formset though: that implies you are creating multiple events, whereas you talk about showing the URL for a single event, which makes more sense. Sounds like you should use a simple ModelForm, and if it's valid do `event = form.save()` - now you can pass that `event` object to the template.

Finally, note that rendering a template directly after a POST is a bad idea, as the documentation explains. You should always redirect to a new page: you could redirect directly to the new event's URL if you like.
--
DR.

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To view this discussion on the web visit https://groups.google.com/d/msg/django-users/-/z3oM38TtTCMJ.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to django-users+unsubscribe@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/django-users?hl=en.

No comments:

Post a Comment