0

I'm building simple Course Management App. I want Users to sign up for Course. Here's sign up model:

class CourseMembers(models.Model):
    student = models.ForeignKey(Student)
    course = models.ForeignKey(Course)

    def __unicode__(self):
        return unicode(self.student)

Student model is extended User model - I'd like to fill the form with request.user. In Course model most important is course_id, which i'm passing into view throught URL parameter (for example http://127.0.0.1:8000/courses/course/1/).

What i want to achieve, is to generate 'invisible' (so user can't change the inserted data) form with just input, but containing request.user and course_id parameter.

Malyo
  • 1,990
  • 7
  • 28
  • 51
  • Do you want to show them the fields at all? Are you using class based views or just function based views? – Timmy O'Mahony Sep 27 '13 at 12:47
  • No i don't want to show any field, just input button that sends request.user and course_id through post. I'm using function based views. – Malyo Sep 27 '13 at 13:38

2 Answers2

0

You want hidden inputs:

<input type="hidden" name="user" value="{{request.user}}"/>

I'd pass in the course_id as a context variable personally, not in the GET:

<input type="hidden" name="course_id" value="{{course_id}}"/>

Or you can get the value from the url string using {{request.get_full_path}}, and some slicing.

professorDante
  • 2,290
  • 16
  • 26
  • Well it's not exactly my problem. Thing is i don't really need any input fields, since both values are present in my view, i just don't know how to save those values trough django form helper and POST request – Malyo Sep 27 '13 at 18:01
  • This is exactly how you do it - these are hidden form values - the only way to pass that data through the form in a POST. – professorDante Sep 27 '13 at 18:07
0

I've found answer to my own question. So here's step by step: First we need to remove all the fields in ModelForm:

class AddCourseMemberForm(forms.ModelForm):

    class Meta:
        model = CourseMembers
        fields = {}

As there's no data we want to get through user input, we just send empty POST request, and then insert the data directly to our form model, and then save it:

if request.method == 'POST':
    form = AddCourseMemberForm(request.POST)
    if form.is_valid():
        form = form.save(commit=False)
        form.student_id = user.id  #from request.user
        form.course_id = course.id #from url parameter i.e courses/course/1/
        form.save()
        return redirect('index')

As I'm still learning I need to know if this is the safe way of doing things, as well as if is_valid method() makes sense. I think I need to clean course.id just in case and maybe validate right before save?

CDMP
  • 310
  • 4
  • 10
Malyo
  • 1,990
  • 7
  • 28
  • 51