Changing user data in django python - 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

Related

Django queryset annotation, charfield with choices and trying to get the display value

The relevant bits of my model:
class AnalyticRecord(models.Model):
APP = "APP"
WEB = "WEB"
DASH = "DASH"
SOURCE_CHOICES = (
(APP, "Mobile Application"),
(WEB, "Website"),
(DASH, "User Dashboard"))
user = models.ForeignKey(User, blank=True, null=True)
event = models.ForeignKey(Event)
source = models.CharField(max_length=25, choices=SOURCE_CHOICES)
I am trying to run an aggregation command. It works just fine like this:
data = event.analyticrecord_set.all().values("source").\
annotate(label=Concat("source", Value(None), output_field=CharField()))
However, the problem is the annotation label returns "APP", "WEB", "DASH" instead of the actual display value. I know I can use get_FOO_display() normally, but how can I pull in the display value into my annotation call? I am looking to get the display values of my source field. Thanks!
queryset = event.analyticrecord_set.all().values("source").\
annotate(label=Concat("source", Value(None), output_field=CharField()))
for query in queryset:
print(queryset.model(source=query['source']).get_source_display())
can you try above code snippet, hope this helps

Save object from template

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).

Using ManyToManyFields() with Django

I'm building a social network where user are supposed to be able to follow each other. So I define a class user with a field: ManyToMany to stock the users that follow this user. This is what I have done in my model.py:
followings = models.ManyToManyField('self', blank=True)
This is my view.py:
#login_required
def follow_test(request):
name = request.POST.get('name', '')
user_followed = Dater.objects.get(username=name)
current_user = Dater.objects.get(id=request.user.id)
print current_user.followings # display my_app.Dater.None
current_user.followings.add(user_followed)
print current_user.followings # display my_app.Dater.None
I retrieve correctly my users (current (The one who follow someone) and the followed one) but I can't add the followed user in the set followings of the current user. Can you see something I don't do properly in my view?
followings is a manager; to show the members of that relationship, you need to call .all() on it (or another manager/queryset method like order_by).
print current_user.followings.all()

Allow only editing the current selected Foreign Key in Django Admin

So currently I have something like this:
Model:
class ConfirmEmail(models.Model):
report = models.ForeignKey(Report)
owner = models.CharField(max_length = 100)
emails = models.ManyToManyField(Sdm)
Admin:
#admin.register(ConfirmEmail)
class ConfirmEmailAdmin(admin.ModelAdmin):
change_form_template = 'admin/phone/index.html'
readonly_fields = ('owner',)
filter_horizontal = ('emails',)
list_display = ('owner','report')
I create these objects in code - meaning I set the report object. But what I would like in the Django admin is if I could allow a user to edit that report object but only the one set. They would be allowed to change it (so hopefully the drop down menu would no longer be there) so the nice pencil icon would still be there, but things like that "+" icon would be gone.
And this is not to say the user can't edit all reports, it's just that in the ConfirmEmail Admin they can only view that specific report attached to it.
I've been smacking away at this and can't seem to get it work.
I would also be inclined to just have the current Report Form embedded into the ConfirmEmail form - but don't know how I would go about doing that.
You should first introduce a model admin for your Report model, then override the has_add_permission function of your ReportAdmin.
#admin.register(Report)
class ReportAdmin(admin.ModelAdmin):
# whatever you want here
def has_add_permission(self, request):
return False
You can also remove/disable the + button using javascript in the page, but be aware that the user can cause damage if he knows the add url, or disables javascript.

How to populate choice form from db in Django?

I can't figure out how to populate choice form from db. I know about ModelChoiceForm but the problem seems to be slightly different.
I want user to choose which sector does he work in. For example: 'Finance','Electronics' etc. which I would do simple:
SECTOR_CHOICES = (('finance',_('Finance'),
'electronics',_('Electronics')...
))
But the problem is that I want admin of the web to be able to add new choices, remove choice etc.
What came to my mind is to create a simple Model called Sector:
class Sector(models.Model):
name = models.CharField(max_length=40)
and User would have new attribute sector = models.ModelChoice(Sector).
But I'm scared what would happend when admin changes or removes a sector which is already used, and more, what if he removes it and the sector attribute is required?
How to solve this problem?
I would just override the delete_model as custom action and there check if the selected sector object is in use.
def delete_model(modeladmin, request, queryset):
for obj in queryset:
if UserModel.objects.filter(sector=obj).exists():
# do not delete, just add some message warning the admin about it
else:
obj.delete()
class UserModelAdmin(admin.ModelAdmin):
actions = [delete_model]
# ...

Categories

Resources