Want to make sure object not in queryset before adding it - django

My "Event" object has a "Name" field. There is the possibility that the name is wrong, so a user may suggest a new name. That name gets put into the event's "suggestedN" list. However, I don't want there to be duplicates of one suggestion in that list. I felt like this was a straightforward problem, but for some reason am not finding much success.
Here is how my view currently looks:
#login_required
def suggestName(request):
name = request.POST['name'].strip()
event_id = request.POST['event_id']
try:
e = Event.objects.get(event_id = event_id)
except Event.DoesNotExist:
e = customEvent.objects.get(event_id = event_id)
if name in e.suggestedN.all():
pass
else:
(some code)
Is my if name in e.suggestedN.all() statement wrong?
Here's a brief view of my Event's model:
class Event(models.Model):
def __unicode__(self):
return self.title
suggestedN = models.ManyToManyField('suggestedName', blank = 'TRUE', null = 'TRUE')
class suggestedName(models.Model):
def __unicode__(self):
return self.name
name = models.CharField(max_length=200, blank = 'TRUE', null = 'TRUE')
votes = models.IntegerField(default = 0)

You should use the name attribute on m2m not the m2m itself to compare
#login_required
def suggestName(request):
name = request.POST['name'].strip()
event_id = request.POST['event_id']
try:
e = Event.objects.get(event_id = event_id)
except Event.DoesNotExist:
e = customEvent.objects.get(event_id = event_id)
if name in e.suggestedN.values_list('name', flat=True):
pass
else:
(some code)

Related

How to fix QuerySet' object has no attribute issue?

I need to create the new object or just update if already existing. I receive: QuerySet' object has no attribute "seat". Don't know what I'm doing wrong.
models:
class rows_and_seats(models.Model):
movie = models.ForeignKey(Movies, on_delete=models.CASCADE)
row = models.CharField(max_length = 1)
number = models.IntegerField()
def __str__(self):
return f'{self.movie}'
class Reservation(models.Model):
customer = models.ForeignKey(User, on_delete=models.CASCADE)
movie = models.ForeignKey(Movies, on_delete=models.CASCADE)
seat = models.ManyToManyField(rows_and_seats)
ordered = models.DateTimeField(default=datetime.now().strftime("%Y-%m-%d %H:%M:%S"), blank=True, null=True)
def __str__(self):
return f'{self.customer.username}:{self.movie.title}:{self.ordered}'
views
#login_required
def buy_seats(request, pk):
if request.method == "POST" and request.session.get("seats"):
seats = request.session.pop("seats")
movie = Movies.objects.get(pk=pk)
customer = User.objects.get(pk=request.user.id)
for s in seats:
user_reserved_seats = rows_and_seats.objects.get(movie=movie, row=s[:1], number=int(s[2:]))
reservation_check = Reservation.objects.filter(customer=customer, movie=movie)
if reservation_check.exists():
reservation_check.seat.add(user_reserved_seats)
else:
new_reservation = Reservation.objects.create(customer=customer, movie=movie)
new_reservation.seat.add(user_reserved_seats)
messages.success(request,"You have succesfully reserved the seats.")
return redirect("home")
return redirect("home")
My goal is to keep rows_and_seat in manyTomany in order to display only one reservation of user in admin panel, instead of the list of repeating itself titles.
You can access the value after the exists() check:
if reservation_check.exists():
reservation_check.first().seat.add(user_reserved_seats)
else:
new_reservation = Reservation.objects.create(customer=customer, movie=movie)
new_reservation.seat.add(user_reserved_seats)
Maybe you can use something like get_or_create:
user_reserved_seats = rows_and_seats.objects.get(movie=movie, row=s[:1], number=int(s[2:]))
reservation, created = Reservation.objects.get_or_create(
customer=customer, movie=movie,
)
reservation.seat.add(user_reserved_seats)
Also you might be looping over the seats too many times, maybe you can add all the seats in only one assignment.

Value Error for Foregin key field

I am trying to insert data but am getting ValueError while inserting due to ForeignKey.
class Test(models.Model):
test_name = models.CharField(max_length=20, unique=True)
test_code = models.SlugField(max_length=10, name='Code',unique=True)
referance_value = models.CharField(name='Referance', max_length=20)
def __str__(self):
return self.test_name
class TestTaken(models.Model):
app_code = models.CharField(max_length=20,unique=True)
user_name = models.CharField(name='Username',max_length=20)
test_names = models.ForeignKey(Test, on_delete=models.CASCADE)
result_value = models.CharField(name='ResultValue',max_length=20)
def __str__(self):
return self.app_code
Below is my View.py
def alltestdata(request):
if request.method == 'POST':
app_code = request.POST.getlist('app_code')
test_name = request.POST.getlist('name')
test_list = request.POST.getlist('test_list')
for i, j , k in zip(app_code, test_name, test_list):
book = TestTaken(app_code=i, ResultValue=j, test_names=k, Username=request.user.username)
book.save()
return redirect('lab:Dashboard')
Am geting following error
ValueError: Cannot assign "'eeeee'": "TestTaken.test_names" must be a "Test" instance.
The error holds the answer to your question: test_names is a ForeignKey, not a string. To set it from a name, you first need to find the key into the Test table. This can be done with a get or get_or_create, depending on how you want to handle missing tests.
NOTE: test_names is not a very good name for that ForeignKey field and probably caused this confusion. It shouldn't be plural, and points to a Test object, not just a name. You probably want something more like test
There is some additional confusion in your code. First, you seem to have swapped values in your inner iteration (j gets its value from test_name and is then applied to ResultValue, while k comes from test_list but goes to test_names instead). You can avoid confusion like this by using more explicit variable names. The second source of confusion is in the variable names app_code, test_name, and test_list, all of which seem to be lists, but only one of them has a name that seems to reflect this.
Combining these points into code, try something like the following. Note that I have changed some of the names of variables to reflect what I think you intended, and I have used a simple get_or_create, while you might want something else. Adjust to suit your needs:
# in your model
class Test(models.Model):
test_name = models.CharField(max_length=20, unique=True)
test_code = models.SlugField(max_length=10, name='Code',unique=True)
referance_value = models.CharField(name='Referance', max_length=20)
def __str__(self):
return self.test_name
class TestTaken(models.Model):
app_code = models.CharField(max_length=20,unique=True)
user_name = models.CharField(name='Username',max_length=20)
test = models.ForeignKey(Test, on_delete=models.CASCADE)
result_value = models.CharField(name='ResultValue',max_length=20)
def __str__(self):
return self.app_code
# in View.py
def alltestdata(request):
if request.method == 'POST':
app_codes = request.POST.getlist('app_code')
test_names = request.POST.getlist('name')
scores = request.POST.getlist('test_list')
for code, test_name, score in zip(app_codes, test_names, scores):
test_obj, _ = Test.objects.get_or_create(test_name=test_name)
book = TestTaken(app_code=code, ResultValue=score, test=test_obj, Username=request.user.username)
book.save()
return redirect('lab:Dashboard')

Django 'Post' object has no attribute '__getitem__'

I'd like to append a quoted pots to user's post before saving it.
Here is the view:
#login_required
def quote_reply(request, quote_id):
tform = PostForm()
print 'quote_id is:' + quote_id
quote = Post.objects.get(pk = quote_id)
topic_id = quote.topic_id
topic = Topic.objects.get(id= topic_id)
print 'quote is' + quote.body
args = {}
if request.method == 'POST':
post = PostForm(request.POST)
if post.is_valid():
p = post.save(commit = False)
p.topic = topic
p.title = post.cleaned_data['title']
p.body = post.cleaned_data['body']
p['body'].append(str(quote)) #problematic line
p.creator = request.user
p.user_ip = request.META['REMOTE_ADDR']
if len(p.title)< 1:
p.title=p.body[:60]
p.save()
tid = int(topic_id)
return HttpResponseRedirect('/forum/topic/%s' % topic_id)
else:
args.update(csrf(request))
args['form'] = tform
args['post'] = quote
args['topic_id'] = topic_id
return render_to_response('myforum/qoute_reply.html', args,
context_instance=RequestContext(request))
I tried also tried
p['body'].append(unicode(quote))
but gives the same error.
Appreciate your help to resolve this.
Update: Here is the Post model
class Post(models.Model):
title = models.CharField(max_length=75, null=True, blank=True)
created = models.DateTimeField(auto_now_add=True)
creator = models.ForeignKey(User, blank=True, null=True)
updated = models.DateTimeField(auto_now=True)
topic = models.ForeignKey(Topic)
body = models.TextField(max_length=10000)
user_ip = models.GenericIPAddressField(blank=True, null=True)
def __unicode__(self):
return u"%s - %s - %s" % (self.creator, self.topic, self.title)
def short(self):
return u"%s - %s\n%s" % (self.creator, self.title, self.created.strftime("%b %d, %I:%M %p"))
short.allow_tags = True
Not sure what to do.
The main problem here is that p is a model instance, which does not support dict-style attribute access syntax. To access the post attribute, use the standard dot syntax, p.post.
The second problem is that you can't use append to change a Unicode or string object - they're immutable. Instead, you should create a new Unicode object containing the content you want and assign that. For instance:
p.post = post.cleaned_data['body'] + unicode(quote)

How can I compare 2 fields and input a result in Django

I know this is probably very basic stuff but I'm really having a tough time figuring it out. I have an app that stores sports forecasts for users, so they input the home team, it's score and the visiting team with it's score. The idea is for the app to determine whether the result was a home win, a tie or an away win by comparing the scores on both input boxes.
This is my view:
def inicio(request):
if request.method == "POST":
form = Pronosticos(request.POST)
if form.is_valid():
pronostico = PartidosUsuarios.objects.get_or_create(idUsuario=request.user, idPartido=request.POST.get("idPartido", ""), PaisL=request.POST.get("PaisL", ""), Local=request.POST.get("Local", ""), Visita=request.POST.get("Visita", ""), PaisV=request.POST.get("PaisV", ""), Capturado="Si")
if pronostico.Local > pronostico.Visita:
pronostico.Resultado = "Local"
elif pronostico.Visita > pronostico.Local:
pronostico.Resultado = "Visita"
elif pronostico.Local == pronostico.Visita:
pronostico.Resultado = "Empate"
return render(request, "brasil/inicio.html")
partidos_fifa = PartidosFifa.objects.order_by("Partido")[:64]
context = {"partidos_fifa": partidos_fifa}
return render(request, "brasil/inicio.html", context)
The form:
class Pronosticos(ModelForm):
class Meta:
model = PartidosUsuarios
fields = ["idPartido", "PaisL", "Local", "Visita", "PaisV"]
and the model:
class PartidosUsuarios(models.Model):
idUsuario = models.OneToOneField(User)
idPartido = models.CharField(max_length=20)
PaisL = models.CharField(max_length=250)
Local = models.IntegerField(max_length=11, default=0)
Visita = models.IntegerField(max_length=11, default=0)
PaisV = models.CharField(max_length=250)
Resultado = models.CharField(max_length=250)
Puntos = models.IntegerField(max_length=11, default=0)
Capturado = models.CharField(max_length=10, default="No")
def __unicode__(self):
return unicode(self.idPartido)
The field in question aka where i want the result to be stored is called "Resultado"
Everything works as it should except for this part where i've been getting this error:
AttributeError at /inicio/
'tuple' object has no attribute 'Local'
It's complaining about this line:
if pronostico.Local > pronostico.Visita:
Any help will be greatly appreciated, thanks!
The problem here is the return value from get_or_create(). From the documentation:
Returns a tuple of (object, created), where object is the retrieved or created object and created is a boolean specifying whether a new object was created.
So try this instead:
pronostico, _ = PartidosUsuarios.objects.get_or_create(...)

IntegrityError error while saving value of to foreign key in django

Hey folks i am getting integrity error while saving my views .Please tell me what i am doing wrong
Here is my django model
class Ruleinfo(models.Model):
rule = models.IntegerField(null=False)
From = models.IPAddressField(null=True)
to = models.IPAddressField(null=True)
priority = models.ForeignKey('Priority',related_name='pri_no')
cisp =models.ForeignKey('Priority',related_name = 'CISP_no')
def __unicode__(self):
return u'%s' %(self.rule)
class Priority(models.Model):
pri = models.IntegerField(null = True)
Ruleno = models.ForeignKey('Ruleinfo',related_name = 'ruleno_no')
CISP = models.IntegerField(null = True)
def __unicode__(self):
return u'%s ' % (self.priority)
My model form is looking like .
class RuleInfoForm(ModelForm):
class Meta:
model = Ruleinfo
fields = ("rule","From","to")
here is my views.py
def multiwanrule_info(request):
data = {}
no_of_isp = MultiWAN.objects.all()
try:
form = RuleInfoForm(request.POST)
except:
pass
print "----------------------------printing form"
print form
if form.is_valid():
rl_frm = form.save(commit=False)
get_priorities = request.POST.getlist('priority')
get_cisp_info = request.POST.getlist('cisp')
rule_object = Ruleinfo()
for get_pri,get_ci in zip(get_priorities,get_cisp_info,):
pri_object = Priority.objects.get_or_create(Ruleno = rule_object)
pri_object.pri = get_pri
pri_object.CISP = get_ci
rl_frm.save()
else:
form = RuleInfoForm()
data['form'] = form
data['number_of_isp'] = no_of_isp
return render_to_response('networking.html',data)
I am getting the above error along this
networking_priority.Ruleno_id may not be NULL
help me out so that i could get back on track .
rule_object = Ruleinfo()
This just instantiates a new model object. It is not saved or assigned values. Since it is not saved it does not have an id value.
assigning your rule_object values: rule, from, to, priority, and cisp values, should fix your problem.