简体   繁体   中英

Django create an object when enter its link

the title probably doesn't tell my problem, sorry about it.

I have a models.py like this:

class Baslik(models.Model):
    user = models.ForeignKey(User, null=True, blank=True)
    title = models.CharField(max_length=50)
    timestamp = models.DateTimeField(auto_now_add=True, auto_now=False)
    updated = models.DateTimeField(auto_now_add=False, auto_now=True)
    active = models.BooleanField(default=True)

I have a function to add object to Baslik model. I just enter a title and it works fine. This is my forms.py :

class BaslikForm(ModelForm):
    class Meta:
        model = Baslik
        fields = ('title',)

My urls for every object is like this: url(r'^(?P<title>.*)/$', 'tek', name = "tek_baslik") I want to create a new object when user enter its future link if it isn't already created. For instance when user enters /baslik/stack I want to create a "stack" object immediately and render its page that defined in views.py for every object. How can I do this. Any idea would help. Thanks.

Here's an approach you can take:

1) Define a new url structure:

url(r'^baslik/(?P<title>.*)/$', views.baslik_handle, name = "tek_baslik")

2) You don't need the modelform, you can directly handle it through the views. Use get_or_create in views.baslik_handle. eg

def baslik_handle(request, title):
   baslik, created = Baslik.objects.get_or_create(title=title)

The ModelForm is unnecessary, try this:

view

def create_baslik(request, title):
    context = RequestContext(request)
    context_dict = {}

    baslik, created = Baslik.objects.get_or_create(title=title, user=request.user)
    context_dict['baslik'] = baslik

    return render_to_response('baslik.html', context_dict, context)

template

{% if baslik %}
    {{ baslik.title }}
    ...
{% endif %}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM