0

today I'm trying to get and print all my users emails, who had chose selection "Value1".

This is how my model.py looks like:

from django.db import models

class Vartotojas(models.Model):
    email = models.EmailField()
    option = models.CharField(max_length=30)

Forms.py :

from django import forms
from emailai.models import Vartotojas

class VartotojasForm(forms.Form):
    email = forms.EmailField(max_length=100)
    my_field = forms.MultipleChoiceField(choices=(('Value1','Value1'),('Value2','Value2')), widget=forms.CheckboxSelectMultiple())
    
    def save(self):
        mymodel = Vartotojas(
        email=self.cleaned_data['email'],
        option=self.cleaned_data['my_field'],
        )
        mymodel.save()

And finally my views.py "

from django.shortcuts import render
from django.http import HttpResponse
from django.http import HttpResponseRedirect
from emailai.models import Vartotojas
from renginiai.forms import VartotojasForm

def name(request):
    if request.method == 'POST':
        form = VartotojasForm(request.POST)
        if form.is_valid():
            a = Vartotojas.objects.filter(option="u'Value1'") # How to do it right?
            # Now How To Get those object emails?
            new_user = form.save()
            return render(request, "Vartotojas-result.html", {
        'form': form, #BLABLABLA,
    })
    else:
        form = VartotojasForm()
    return render(request, "Vartotojas-form.html", {
        'form': form,
    })

I commented my questions inside my views.py. I hope you will be able to help me. Thank you in advance!


I re-write my code with getlist. Now it looks like this:

views.py :

if form.is_valid():
            email = form.cleaned_data['email']
            option = request.POST.getlist('my_field')
            new_user = form.save(email, option)

forms.py:

email = forms.EmailField(max_length=100)
my_field = forms.MultipleChoiceField(choices=(('Value1','Value1'),('Value2','Value2')), widget=forms.CheckboxSelectMultiple())
    
    def save(self, email, option):
        mymodel = Vartotojas(
        email=email,
        option = option,
        )
        mymodel.save()

As you see I pasted just most important places. By the way, users can choose 2 values, that's why I use checkbox. But still it not working.

Community
  • 1
  • 1
Irmantas Želionis
  • 2,194
  • 3
  • 17
  • 30

1 Answers1

2

I believe you want to use the values_list property like so:

Vartotojas.objects.filter(option=u"Value1").values_list("email", flat=True)

to get a list of all email addresses. You may also want to apply a distinct() to that if you're not already preventing duplicates. On a side note, look into ModelForms: it looks like that would save you a fair bit of the time/ code you have written for dealing with this. You could create a ModelForm based on your Vartotojas object and not have to write the explicit save() method you have.

Tom
  • 22,301
  • 5
  • 63
  • 96
  • Thanks, you get me on the way. However, somewhere is mistake. In my opinion: option="u'Value1'". I think, i have to write "u'Value1'" somehow different, because now I get empty list, but I know that in it should be atleast 5 emails. – Irmantas Želionis Feb 24 '14 at 20:10
  • Sorry, I should have caught that: you want the `u` on the outside of the string, not inside it. I've updated my code to reflect that. – Tom Feb 24 '14 at 20:23
  • [`distinct()`](https://docs.djangoproject.com/en/dev/ref/models/querysets/#distinct) adds `DISTINCT` to the query, which is standard SQL and supported in all the databases Django typically works with. – Tom Feb 24 '14 at 20:27
  • Open your database table and see if there are records with that value in them. It might be helpful to play with the query filtering in the [Django shell](https://docs.djangoproject.com/en/dev/ref/django-admin/#shell) rather than trying to figure it out in the view. Alternatively, you can try using [pdb](http://stackoverflow.com/questions/4228637/getting-started-with-the-python-debugger-pdb) and a breakpoint to debug the problem. – Tom Feb 24 '14 at 20:30
  • Using the shell, it would be good to find out if `Vartotojas.objects.filter(option=u"Value1")` returns any records. Also try it without the `u`, `Vartotojas.objects.filter(option="Value1")` – Tom Feb 24 '14 at 20:31
  • mhm it returns empty list, but in my admin interface I have objects with value1 http://www.part.lt/perziura/5df19523db16eb221991da731d7a8dd9392.png – Irmantas Želionis Feb 24 '14 at 20:39
  • Ah, no you don't: you have a record with a list in it. I'm guessing `self.cleaned_data['my_field']` refers to checkboxes in the form. If they are checkboxes with the same name, Django will organize that into a list. To properly handle the checkboxes, you'd want [getlist](http://stackoverflow.com/questions/10276753/get-the-list-of-checkbox-post-in-django-views), but I think you may want to change to radio buttons on the front-end if users are only supposed to select one. – Tom Feb 24 '14 at 21:25