Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
4.4k views
in Technique[技术] by (71.8m points)

python - How to add custom method in django forms

I am new to django, and I am creating a vacation application. I want to be able to when I create a new trip, the user that created the trip becomes a member of that trip.

here is my models.py file:

class Trip(models.Model):
    trip_name = models.CharField(max_length=255,unique=False)
    start_date = models.DateField(default=datetime.date.today)
    end_date = models.DateField(default=datetime.date.today)
    slug = models.SlugField(allow_unicode=True,unique=True)
    members = models.ManyToManyField(User,through='TripMember')


def __str__(self):
    return self.trip_name

def save(self,*args,**kwargs):
    self.slug = slugify(self.trip_name)
    super().save(*args,**kwargs)

def get_absolute_url(self):
    return reverse('trips:single',kwargs={'slug':self.slug})

class Meta:
    ordering = ['start_date']


class TripMember(models.Model):
    trip = models.ForeignKey(Trip,null=True,related_name='memberships',on_delete=models.SET_NULL)
    user = models.ForeignKey(User,null=True,related_name='user_trips',on_delete=models.SET_NULL)

def __str__(self):
    return self.user.username

class Meta:
    unique_together = ('trip','user')

this is my forms.py file:

class TripCreateForm(forms.ModelForm):
    class Meta:
        fields = ('trip_name','start_date','end_date')
        model = Trip

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields["trip_name"].label = "Trip Name"
        self.fields["start_date"].label = "Start Date"
        self.fields["end_date"].label = "End Date"

here is my views.py file:

class CreateTrip(CreateView):
    form_class = TripCreateForm
    template_name = 'trips/trip_form.html'

and my trip_form.html page:

<form action="{% url 'trips:create' %}" method="post" id='tripForm'>
    {% csrf_token %}
    {% bootstrap_form form %}
    <input type="submit" class="btn btn-primary btn-large" value="Create">
</form>

Where would I put the code to set the user as a tripmember and why?Also, if there is a better way to have set this up please let me know! I was gonna put it in the save part of the model but I am not quite sure if that is correct. Thanks!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can override the form_valid() method of the CreateTrip class in your view:

def form_valid(self, form):
    """If the form is valid, save the associated model."""
    self.object = form.save()

    # add the current user to the members list of the trip
    user = self.request.user
    self.object.members.add(user)

    return super().form_valid(form)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...