S
S
Sergey Nizhny Novgorod2016-06-18 03:25:55
Django
Sergey Nizhny Novgorod, 2016-06-18 03:25:55

User feedback, how to do it right?

Hello.
Situation:
There is a Course model (course) - there is a Creview model (Course Review) - There is a standard User model (user). The task is to make sure that authorized users can leave their reviews.
How I did:
models.py

class Course(models.Model):
    ....

class Creview(models.Model):
    creview = models.ForeignKey(Course, on_delete=models.CASCADE, default=1)
    userview = models.ForeignKey(User, on_delete=models.CASCADE, default=1)   
    review = models.TextField(help_text="Отзыв", verbose_name="Сам отзыв о курсе")

forms.py
class CreviewForm(forms.Form):
    review = forms.CharField(widget=forms.Textarea, label='Ваш отзыв', required=False)

html.page
<form action="/addcreview{{ courseitem.id }}" method="post">
                                        {% csrf_token %}
                                        <input type="hidden" name="userfromform" value="{{ user.id }}">
                                        {{ form.as_p }}
                                        <input type="submit" class="expanded button" value="ОПУБЛИКОВАТЬ">
                                    </form>

view.py
def addcreview(request, add_id):
    token = csrf(request)
    if request.POST:
        course = Course.objects.get(id = add_id)
        user_id =  request.POST.get('userfromform', '')
        user = User.objects.get(id = user_id)
        form = CreviewForm(request.POST)
        if form.is_valid():
            review = form.cleaned_data['review']
            review_obj = Creview(creview=course, userview=user, review=review)
            review_obj.save()
            return redirect('/course'+ add_id, token)

And this whole thing works like this:
I manually pass the ID of the current user to the html, and the form. When clicking on the "Add" button, I also pass the id of the current course and:
  1. Finding the object of the current course
  2. Find the object of the current user
  3. I take the text from the form.
  4. I create a new feedback object, into which I pass all the data.

It works, but it seems to me that somehow I'm doing it wrong. How can this whole thing be done right?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
R
Roman Kitaev, 2016-06-18
@Terras

Of course something is wrong. Look at the names of classes and attributes.
And also transfer the user in a hidden field ... So you can write reviews from other people. You get the user through request.user

O
Oscar Django, 2016-06-18
@winordie

models.py

class Creview(models.Model):
    ...
    def get_absolute_url(self):
        return reverse('course_review', kwargs={'pk': self.id})

url.py
...
url(r'^creview/(?P<pk>\d+)/$', DetailCourseReview.as_view(), name='course_review'),
url(r'^creview/(?P<course_id>\d+)/create/$', login_required(CreateCourseReview.as_view()), name='create_course_review'),
...

forms.py
class CourseReviewForm(forms.ModelForm):
    class Meta:
        model = Creview
        fields = ['review']

    def __init__(self, user, course, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.instance.creview = course
        if user and user.is_authenticated():
            self.instance.userview = user

views.py
class DetailCourseReview(DetailView):
    model = Creview


class CreateCourseReview(CreateView):
    model = Creview
    form_class = CourseReviewForm
    template_name = 'course_review.html'

    def dispatch(self, request, *args, **kwargs):
        course_id = kwargs.get('course_id')
        self.course = get_object_or_404(Course, pk=course_id)

        super().dispatch(request, *args, **kwargs)

    def get_form_kwargs(self):
        kwargs = super().get_form_kwargs()

        kwargs['user'] = self.request.user
        kwargs['course'] = self.course

        return kwargs

course_review.html
<form action="{% url "create_course_review" course_id=course.id %} method="post">
    {% csrf_token %}
    {{ form }}
    <input type="submit" value="{% trans "Send" %}">
</form>

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question