Save object from template - python

Im creating a music website. In this website, I would like to add the functionality of favorites so users could add songs to their favorite lists.
I have done everything but I don't know how to save it. Here is my code:
models.py
class Song(models.Model):
is_favorite = models.BooleanField(default=False)
def __str__(self):
return self.song_title
views.py
def song_detail(request,song_id):
song = Song.objects.get(pk=song_id)
favorite = song.is_favorite = True
return render(request, 'song_detail.html', {'favorite':favorite})
song_detail.html
<button onclick="{{favorite}}">Favourite</button>
While playing with the python shell, I found the problem:
Let s be the created song with pk=1,
d = Song.objects.get(pk=1)
d.is_favorite=True
d.save()
y = Song.objects.filter(is_favorite=True)
print(y)
->s
The problem was after making a song's is_favorite = True, we need to save it. But I don't know how to implement it in the code such that when a user clicks the button the boolean field changes to true. Thank you.

I solved it myself!
I changed the values of favorite from views to song.update(is_favorite=True).

Related

Excluding existed users in the ManyToManyField

I am building a small BlogApp and I build a feature of adding favorite users. User can search and add the user in his favorite users list
I am now building a feature if searched user is already in another's users favorite user list then exclude the user from the result
For example :- If user_1 added user_50 in his favorite user's list. and then if user_2 searched user_50 then it will not show in the search list.
BUT when i try to exclude then it is not excluding.
models.py
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE,unique=True)
full_name = models.CharField(max_length=100,default='')
friends = models.ManyToManyField("Profile",blank=True)
email = models.EmailField(max_length=60,default='')
class FavouriteUsers(models.Model):
adder = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE)
favouriteUser = models.ManyToManyField(User, related_name='favouriteUser', blank=True)
views.py
def search_users_favourite(request):
q = request.GET.get('q')
exclude_this = FavouriteUsers.objects.filter(favouriteUser=request.user)
results = Profile.objects.filter(user__username__icontains=q).exclude(exclude_this)
serialized_results = []
for result in results:
serialized_results.append({
'id': result.id,
'username': result.user.username,
})
return JsonResponse({'results': serialized_results})
BUT this is showing :-
TypeError: Cannot filter against a non-conditional expression.
I have tried many times but it is still that error.
Any help would be Appreciated.
Thank You in Advance.
Try this query:
Profile.objects.filter(user__username__icontains=q, user__favouriteUser__isnull=True)
This will exclude all profiles that are already mapped in FavouriteUsers (already has been a favorite)
I think you should be doing it this way
exclude_this = FavouriteUsers.objects.filter(favouriteUser=request.user).values_list('favouriteUser__username',flat=True)
results = Profile.objects.filter(user__username__icontains=q).exclude(user__username__in=exclude_this) here, i assume you want to exclude usernames matching the entire name.
For a better answer, please attach the log of the error.
I spent hours tearing my hair out over this issue, so I wanted to post a quick response here on what is actually causing this exception:
The problem is this (pseudo code):
query = Model.objects.filter(something=value)
result = Model.objects.filter(query).first()
This won't work (apparently). Django hates it big time.
The problem is that you can't pass a QuerySet to filter or exclude.
Instead, use your QuerySet directly:
query = Model.objects.filter(something=value)
result = query.first()

Changing user data in django python

guys! I'm new to django and I'm developing simple web site with user registration. I want to test some things, for example: on user profile page I added picture:
and by pressing on it picture should change to:
And by pressing on red one it should be changed to grey.
Condotion of this picture should be saved. I have seven pictures for every day of the week and user should be able to change every picture.
I've created a model like this (if you have any better ideas it would be great):
class Week1(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
utr_ust0 = models.IntegerField(default=0, max_length=3)
utr_ust1 = models.IntegerField(default=0, max_length=3)
utr_ust2 = models.IntegerField(default=0, max_length=3)
...
utr_ust0 = 0 (grey)
utr_ust0 = 1 (red)
But I cant't really understand how to work with this model in views. I think that during registration I should do something like this:
auth.login(request, user)
Week1.objects.create(utr_ust0=0, utr_ust1=0, utr_ust2=0, utr_ust3=0,
utr_ust4=0, utr_ust5=0, utr_ust6=0, user_id=username)
But I get this error: invalid literal for int() with base 10: 'test5'
And in the function that loads page with the calendar I'm returning dict like this:
if request.user.is_authenticated:
content['smiles'] = [Week1.utr_ust0, Week1.utr_ust1, Week1.utr_ust2,
Week1.utr_ust3, Week1.utr_ust4, Week1.utr_ust5, Week1.utr_ust6]
And of course I should add some ajax script but I dont' now yet how to do this.
Any ideas or advices? Thank you a lot.
...utr_ust6=0, user_id=username)
user_id should be a user ID, an int, or pass the object:
week1.objects.create(..., user=user)
check the type of user in auth.login(..) or pick it from the request if it's available: request.user

Django view not working for project

Context:
I am creating a website to house some webcomics I made as a project to practice Django. I am adapting Django's tutorial to create the site (https://docs.djangoproject.com/en/2.0/intro/tutorial03/ About halfway down the page under "Write views that actually do something"). I am having some difficulty getting part of my view to work as expected.
Expectation:
What I see when I go to http://127.0.0.1:8000/futureFleet/ : latest_comic
What I want to see: A dictionary of my 2 comics.
Question:
I think I am doing something wrong at this line
context = {'latest_comic': latest_comic}. I am adapting this line from the tutorial. What do I do? What am I missing?
Models.py
class Comic(models.Model):
#title
comic_title_text = models.CharField(max_length=200)
#date
comic_pub_date = models.DateTimeField('comic date published')
#image
comic_location = models.CharField(max_length=200)
#explanation
comic_explanation_text = models.CharField(max_length=400, blank=True)
def __str__(self):
return self.comic_title_text
def was_published_recently(self):
return self.comic_pub_date >= timezone.now() - datetime.timedelta(days=1)
views.py
def index(request):
latest_comic = Comic.objects.order_by('-comic_pub_date')[:2]
context = {'latest_comic': latest_comic}
return HttpResponse(context)
# return render(request, 'futureFleet/index.html', context) This sends to the template but doesn’t work at the moment
Database
"Welcome Aboard" "2018-01-15 21:02:54" "/home/user/Desktop/django/djangoFutureFleet/mysite/futureFleet/static/futureFleet/images/1.JPG" "this is the first comic"
"Space Vaccine" "2018-01-15 23:02:22" "/home/user/Desktop/django/djangoFutureFleet/mysite/futureFleet/static/futureFleet/images/2.JPG" "This is comic 2"
The problem is with:
Comic.objects.order_by('-comic_pub_date')[:2]
You are asking Django for all Comic objects sorted by publication date. You then take the first two with [:2]. Here's a simple example of this syntax:
>>> a = [0,1,2,3,4]
>>> print(a[:2])
[0, 1]
What you're probably looking for is:
Comic.objects.order_by('-comic_pub_date').first()
That would only return the first result.
Have you connected the view to your urls.py? In order to access the view, you need to connect it to a URL. In your urls.py file, add
path('/',<your app name>.views.index),
or if you're using the old django:
url(r'', <your app name>.views.index),
After that, try this:
latest_comic = Comic.objects.all().order_by('-comic_pub_date')[:2]
You could try:
def index(request):
latest_comic = Comic.objects.order_by('-comic_pub_date')[:2]
dictionary = {'comic_1':latest_comic[0], 'comic_2':latest_comic[1]}
return HttpResponse(dictionary)
Note: latest_comic[0]
will return the first field value of the model, in your case: Welcome Aboard
If you want to access other fields you will need to do the following:
latest_comic[0].field_name

Combining a Django model + modelform as a single unit

My friends and I play a sports picking style game via a clumsy spreadsheet, and I decided to learn about Django by implementing the game as a webapp. I've gone through the Django tutorial and I've been working on the basics of passing data between the database, views, and templates.
I'm trying to display information from one model alongside a different model form, then handle saving that form to the database based on the displayed model. Here's what I have for my models:
class Sheet(models.Model):
user = models.ForeignKey(User)
... other stuff
class Game(models.Model):
home_team = models.CharField(max_length=100, default='---')
away_team = models.CharField(max_length=100, default='---')
... other stuff
class Pick(models.Model):
sheet = models.ForeignKey(Sheet)
game = models.ForeignKey(Game)
... other stuff
As you can see, Picks have both a Sheet and a Game- so a users Sheet can have multiple Picks (due to the format of the game), and each Game can have multiple picks (since multiple users might pick any given game).
My intention is to display Game information with a PickForm, so that the user can make the pick based on the displayed information. Then on POST, the pick would be appropriately foreign keyed to the correct game. I'm experimenting right now, hence the static object ID below:
class GameDetail(DetailView):
model = Game
template_name = 'app/games.html'
context_object_name = 'game_detail'
def get_object(self):
game = get_object_or_404(Game, id=5)
return game
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['pickform'] = PickForm()
return context
def post(request):
form = PickForm(request.POST)
if form.is_valid():
pick = Pick(sheet = form.cleaned_data['sheet'],
game = form.cleaned_data['game'],
amount = form.cleaned_data['amount'],
pick_type = form.cleaned_data['pick_type'],
pick_team = form.cleaned_data['pick_team']
)
pick.save()
return HttpResponseRedirect('/games/')
What I'm wondering is, should I accomplish this by creating a separate form class that combines the PickForm with the Game? Or does it make more sense to tie them together dynamically? One option I'm looking at for the latter is using the Form.initial capability with the following change to get_context_data:
context['pickform'] = PickForm(initial={'game':self.game})
This errors out when I try to load the page
AttributeError at /games
'GameDetail' object has no attribute 'game'
In get_context_data(), has get_object() not been run already? I thought that was first, followed by get_context_data().
I could have gone about this in the entirely wrong way, so I'll be very appreciative of any advice for this issue or on how I've structured the entire thing.
EDIT: I just realized self.game would likely only work if it was defined as a field at the top of GameDetail, so I tried this:
context['pickform'] = PickForm(initial={'game':kwargs['game']})
But that doesn't work either:
KeyError at /games
'game'
context['pickform'] = PickForm(initial={'game':context['game_detail']})
https://docs.djangoproject.com/en/1.9/ref/class-based-views/mixins-single-object/#django.views.generic.detail.SingleObjectMixin.get_context_data
It returns a dictionary with these contents:
object: The object that this view is displaying (self.object).
In your form you have set context_object_name = 'game_detail'

How to create a very simple search view for one column of mysql data in Django?

I have searched around and see that most are pointing to a search that was created by Julien Phalip: http://julienphalip.com/post/2825034077/adding-search-to-a-django-site-in-a-snap
Also the answer seems to be here: Very simple user input in django
However I am very new to Django and wanted to create a view where I actually understand what is happening so I have been going through the official Django and the Tango with Rango tutorials but I do not see a straightforward example of what I am trying to understand in regards to a simple form search. The main question I have is why is POST used in the example instead of GET? I thought POST was used to "create" data entries in mysql whereas GET is used to lookup/search for data entries? Am I missing something fundamental about using one vs the other?
I have the following simple example from my app:
models.py
class hardware(models.Model):
text = models.CharField(max_length=200, unique=TRUE)
pub_date = models.DateTimeField(default=timezone.now)
def __unicode__(self):
return self.text
class Barcode(models.Model):
hardware = models.ForeignKey(Hardware)
text = models.CharField(max_length=50)
pub_date = models.DateTimeField(default=timezone.now)
def __unicode__(self):
return self.text
forms.py
class HardwareForm(forms.modelForm):
class Meta:
model = Hardware
fields = ['text'}
views.py
def hardware_search(request):
if request.method == 'POST':
search_id = request.POST.get('textfield', None)
try:
hardwarename = Hardware.objects.get(text = search_id)
html = ("<H1>%s</H1>", hardwarename)
return HttpResponse(html)
except Hardware.DoesNotExist:
return HttpResponse("no such hardware found")
else:
return render(request, 'search.html')
search.html
<form method="POST" action="/hardware_search.html">
{% csrf_token %}
<input type="text" name="textfield">
<button type="submit">Upload text</button>
</form>
My questions are is this the most simple way to request user input to search for and generate the search results? Why is POST used? I plugged in this code and it does seem to work but i just can't understand why.
Secondly how can I display asssociated foreignkey class along with the main class 'hardware' search results? Does the ForeignKey association give a shortcut way of displaying that data as well?
thanks!
The W3 has an excellent introduction to POST vs GET here. There is a lot to be said for why someone might use POST or GET, and what their roles should be. You are probably more interested in the differences from the user's (browser's) perspective. The biggest differences between using POST and GET in a browser, is that the GET request will display the parameters in the URL. Change your form to GET to see for yourself. The user will be taken to:
/hardware_search.html?textfield=Upload%20text
As opposed to where they are taken to when the form action is POST:
/hardware_search.html
The value of the textfield field is still sent to the server, but is not visible in the URL.
There are quite a few other differences in the behavior of GET and POST in form submission. I would highly recommend reading over that introduction by the W3.
You're right, POST is not really appropriate for a search form. Using GET here would be better.
The other thing wrong is that there's no need at all for a ModelForm, or really for any kind of Django form. You're not doing any validation, you're not even using the form for output, so it would be better to leave that out altogether. That makes the view look like this:
def hardware_search(request):
query = request.GET.get('textfield', None)
if query:
try:
hardwarename = Hardware.objects.get(text = query)
html = ("<H1>%s</H1>", hardwarename)
return HttpResponse(html)
except Hardware.DoesNotExist:
return HttpResponse("no such hardware found")
else:
return render(request, 'search.html')
and you can change the form action to GET.

Categories

Resources