2

I have two models for store and city:

class City(models.Model):
    name = models.CharField()
    slug = models.SlugField()


class Store(models.Model):
    name = models.CharField()
    slug = models.SlugField()
    city = models.ForeignKey(City)

If I have my Add Store url designed as

r^'mysite.com/city/(?[-\w]+)/venue/add$'

where the represents the City.slug field can I initialize a StoreForm that automatically populates the Store.city field from the url data?

0

1 Answer 1

2

In your template, define your link as follows.

{%url somename relevant_slug_text%}

Or :

href='/mysite.com/city/{{slug_text}}/venue/add'

In your url conf, define your url like:

url(r^'mysite.com/city/(?P<slug_text>\w+)/venue/add$', 'func_name', name='somename')

So, you can pass the value of relelvant_slug_text variable to your url as slug_text, and in your function definiton:

def func_name(request, slug_text):

So , you can pass text value to your funcrtion with slug_text parameter...

EDIT: There are tow ways...

One:

Crete your city selection form using ModelForm..., then inthe second step, use posted data to populate your form again like:

form = StoreForm(request.POST)

then you can render this form to your template...

But if it is not possible o use this, yo ucan do the following...

Since you are using ModelForm to create your forms:

class StoreForm(forms.ModelForm):
    # your form field definitions are here

im your function, just override city field, but at this point, since you use modelform, your form thml will be created as

<select>
    <option value="id of record">"unicode value of record"</option>

So, you have record id's as option values. And you have slug_field values to initialize your field. So you have to get related city to use it...

my_city = City.objects.get(slug=<your_slug_value>)

Now you can override the form, but you must do it before you pass your form to a variable to render to your template...

StoreForm.base_fields['city'] = forms.ModelChoiceField(queryset=City.objects.all(), initial=my_city)
form = StoreForm()
Sign up to request clarification or add additional context in comments.

1 Comment

How do I get the variable into the actual StoreForm instance? Can I initialize a StoreForm model with the city field populated via the url data and then get the rest of the info from an html form?

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.