Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 713445
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 14, 20262026-05-14T04:57:43+00:00 2026-05-14T04:57:43+00:00

I have a form that edits an instance of my model. I would like

  • 0

I have a form that edits an instance of my model. I would like to use the form to pass all the values as hidden with an inital values of username defaulting to the logged in user so that it becomes a subscribe form. The problem is that the normal initial={'field':value} doesn’t seem to work for manytomany fields. how do i go about it?

my views.py

@login_required
def event_view(request,eventID):
    user = UserProfile.objects.get(pk=request.session['_auth_user_id'])
    event = events.objects.get(eventID = eventID)
    if request.method == 'POST':
        form = eventsSusbcribeForm( request.POST,instance=event)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect('/events/')

    else:
        form = eventsSusbcribeForm(instance=event)

    return render_to_response('event_view.html', {'user':user,'event':event, 'form':form},context_instance = RequestContext( request ))

my forms.py

class eventsSusbcribeForm(forms.ModelForm):
    eventposter = forms.ModelChoiceField(queryset=UserProfile.objects.all(), widget=forms.HiddenInput())
    details = forms.CharField(widget=forms.Textarea(attrs={'cols':'50', 'rows':'5'}),label='Enter Event Description here')
    date = forms.DateField(widget=SelectDateWidget())


    class Meta:
        model = events
        exclude = ('deleted')

    def __init__(self, *args, **kwargs):
        super(eventsSusbcribeForm, self).__init__(*args, **kwargs)
        self.fields['username'].initial = (user.id for user in UserProfile.objects.filter())

my models.py

class events(models.Model):
    eventName  = models.CharField(max_length=100)
    eventID =  models.AutoField(primary_key=True)
    details = models.TextField()
    attendanceFee = models.FloatField(max_length=99)
    date = models.DateField()
    username = models.ManyToManyField(UserProfile, related_name='user', blank=True)
    eventposter = models.ForeignKey(UserProfile, related_name='event_poster')
    deleted = models.BooleanField()

    def __unicode__(self):
        return u'%s' % (self.eventName)
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-14T04:57:43+00:00Added an answer on May 14, 2026 at 4:57 am

    Can you post your Event model? It’s too hard to guess what you are trying to do without that. I have to assume a few things without it, so I’m sorry if I’m wrong.

    First off, I’m guessing that you should not be using an Event ModelForm for the EventSubscriptionForm. That doesn’t really make sense. Hopefully, you created a through class for Event and User, so in your Event model, you have something like

    subscriber_users = models.ManyToManyField(User, through="Subscription")
    

    and

    class Subscription(models.Model):
        user = models.ForeignKey(User, related_name="events",)
        event = models.ForeignKey(Event, related_name="subscribers")
    

    Then you can use a Subscription ModelForm.

    Is there any reason you’re using eventID instead of the django idiom, event_id? You should also import your Event and EventSubcribeForm classes with Pythonic casing. One very important thing is that you should be linking everything to User and not UserProfile.

    Technically, it makes more sense to set initial in the view rather than the form init, because you would have to pass request.user to init anyway.

    I think you should try this for your view…

    @login_required
    def event_view(request, event_id=None):
        user = request.user.get_profile()
        event = Event.objects.get(id=event_id)
        initial = {'user': request.user}
    
        form = EventSubcriptionForm(request.POST or None, instance=event, initial=initial)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect(reverse('event_list'))
    
        return render_to_response('event_view.html', {
            'event': event,
            'form': form
        }, context_instance = RequestContext(request))
    

    A few notes

    • use request.user.get_profile() for the current user’s profile object
    • you can use request.POST or None to avoid the request.method cases
    • always use named urls so you can reverse on names instead of hard-coding urls into views
    • if you want user in your template context, just setup a context processor (see pinax for example on how to do this) instead of passing it in every single view. You can always use request.user also.

    Keep in mind that this code will only work if you have that through class setup like I said and you use a form like

    class EventSubcriptionForm(forms.ModelForm):
        class Meta:
            model = Subscription
            exclude = ('event')
    

    EDIT
    Thanks a bunch for the ups. I’m not new to django, but somehow very new to SO.

    Okay, you should really read some of the PEPs about Python conventions http://www.python.org/dev/peps/pep-0008/ or some SO posts about it What is the naming convention in Python for variable and function names?.

    Here’s what I recommend for your event app models.py:

    class Event(models.Model):
        name  = models.CharField(max_length=100)
        details = models.TextField()
        attendance_fee = models.FloatField(max_length=99)
        date = models.DateField()
        poster = models.ForeignKey(User, related_name='events_posted')
        deleted = models.BooleanField()
    
        attendee_users = models.ManyToManyField(User, through="Attendance")
    
        def __unicode__(self):
            return self.name
    
    class Attendance(models.Model):
        user = models.ForeignKey(User, related_name="events",)
        event = models.ForeignKey(Event, related_name="attendees")
    

    Notes

    • The name of a class is capitalized and singular. You are not describing events, you are the blueprint for an Event.
    • you never need the name of the class in its attributes, i.e. event_name can just be name.
    • all variables are lowercase_and_underscored
    • always link to User, not your profile model. A lot of django code expects this.

    So now you can access the users attending the event with event.attendees.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have a form that has label values that I would like to pass
I have this function to edit all fields that come from the form and
I have a complex form for a model Schedule that belongs to a parent
I have a simple Django-Piston Handler that creates a new instance of a model
I know that I can pass object values through a URL pattern and use
I'm trying to put together a form_tag that edits several Shift objects. I have
I currently have form that checks if a user has unsubmitted changes when they
I have a form that I'm submitting through AJAX. The form includes many fields,
I have a form that I want to be validated before showing it initially.
I have a form that sends money value e.g <input type=text name=amount value=N50,000.00 NGN

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.