How to combine queryset via ManyToManyField in django - python

I'm trying to build an Instagram clone.
I need to pass user's posts and follow's to the dashboard.
The dashboard is received posts whose owner is the requesting user.
I'd like to combine posts written by the user who requested it with posts by other users who were followed by the user for ordering posts.
But I don't know how to
I am not sure you understand what i mean. Sorry about my english.
For example.
User1 has posts
(title='First', created_at='19-01-01', author='user1')
(title='Third', created_at='19-01-03', author='user1')
User2 has a post
(title='Second' created_at='19-01-02', author='user2')
and user1 follow user2.
And then If user1 access his dashboard.
The dashboard shows you posts like this below.
(title='First', created_at='19-01-01', author='user1')
(title='Second' created_at='19-01-02', author='user2')
(title='Third', created_at='19-01-03', author='user1')
models.py
class Insta(models.Model):
title = models.CharField(max_length=255)
body = models.TextField()
image = models.ImageField(upload_to='images/', blank=True)
video = models.FileField(upload_to='videos/', blank=True)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
likes = models.ManyToManyField(User, related_name='likes', blank=True, default='')
owner = models.ForeignKey(User, on_delete=models.CASCADE)
class User(AbstractBaseUser, PermissionsMixin):
username = models.CharField(max_length=100, unique=True)
user_fullname = models.CharField(max_length=255)
is_active = models.BooleanField(default=True)
is_superuser = models.BooleanField(default=False)
thumbnail = models.ImageField(upload_to='thumbnail/')
follows = models.ManyToManyField('self', related_name='followers', symmetrical=False)
views.py
def list(self, request, *args, **kwargs):
if not request.user.is_authenticated:
return redirect('insta:signup')
else:
user = request.user
response = Insta.objects.filter(owner=user.id)
return Response({'posts': response, 'user': user})
Thank you in advance.

Related

Send id from one table to another automatically in form with ForeignKey in Django

#HELP in python (DJANGO 4)
I send this message here because I have not been able to find an answer elsewhere.
Currently I’m on a project where I have to create a booking form.
The goal is that when the user submit the Reservation form, I send the data in BDD, and I retrieve the user's id by a relation (ForeignKey).
And my difficulty is in this point precisely, when I send my form in BDD I recover the information, except the id of the user…
I did a Foreignkey relationship between my 2 tables and I see the relationship in BDD but I don’t receive the id of the User table, but null in the place….
Does anyone of you know how to help me please?
Thank you all.
--My model.py --
class Reservation(models.Model):
fullName = models.CharField('Nom Complet', max_length=250, null=True)
adress = models.CharField('Adresse', max_length=100, null=True)
zip_code = models.IntegerField('Code Postal', null=True)
city = models.CharField('Vile', max_length=100, null=True)
email = models.EmailField('Email', max_length=250, null=True)
phone = models.CharField('Telephone', max_length=20, null=False)
date = models.CharField('Date', max_length=20, null=True, blank=True)
hour = models.CharField('Heure', max_length=20, null=True, blank=True)
message = models.TextField('Message', null=True)
accepted = models.BooleanField('Valide', null=True)
created_at = models.DateTimeField('Date Creation', auto_now_add=True, null=True)
modified_at = models.DateTimeField('Date Mise Jour', auto_now=True, null=True)
user = models.ForeignKey(User, null=True, on_delete=models.SET_NULL)
def __str__(self):
return self.fullName
-- my views.py --
#login_required()
def user_new_reservation(request, pk=None):
user = User.objects.get(id=pk)
if request.method == 'POST':
form = ReservationForm(request.POST)
if form.is_valid():
form.save()
messages.success(request, 'Votre réservation a bien été envoyé!')
return redirect('reservation:user_reservation', pk=request.user.id)
else:
form = ReservationForm()
context = {'form': form}
return render(request, 'reservation/new_reservation.html', context)
-- My Form.py --
class ReservationForm(forms.ModelForm):
class Meta:
model = Reservation
fields = [
'fullName',
'adress',
'zip_code',
'city',
'email',
'phone',
'date',
'hour',
'message',
]
Thank you all.
Inside your form.save use:
user = form.save(commit=False)
user.user = request.user
user.save()
user=your field name in your model
request user= in django when you use authentication you can access some of information based on request like user and other
Good luck

Django: NOT NULL constraint failed: account_tutorvalidator.user_id

I am new to django and I created this "apply now form" exclusively for tutors that when they submit the form it will appear to the admin site, and I will manually check it if they are a valid tutor. And if they are a valid tutor, I will check the is_validated booleanfield in the admin site to the corresponding tutor that sent the form, so that he/she will have access to other things in the site. But I am having this problem that when you submit the form this comes up..
NOT NULL constraint failed: account_tutorvalidator.user_id
I have search for some solutions and also read similar questions here but I still couldn't understand what to do.. could someone help me out with this?
here is my models.py
class User(AbstractUser):
is_student = models.BooleanField(default=False)
is_tutor = models.BooleanField(default=False)
first_name = models.CharField(max_length=100)
last_name = models.CharField(max_length=100)
phone_number = models.CharField(max_length=11, blank=False, null=True)
current_address = models.CharField(max_length=100, null=True)
image = models.ImageField(default='default-pic.jpg', upload_to='profile_pics')
def __str__(self):
return f'{self.first_name} {self.last_name}'
class TutorProfile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE, null=True,
related_name='tutor_profile')
bio = models.CharField(max_length=255, blank=True)
is_validated = models.BooleanField(default=False)
def __str__(self):
return f"{self.user.first_name} {self.user.last_name}'s Profile"
class TutorValidator(models.Model):
user = models.ForeignKey(TutorProfile, on_delete=models.CASCADE)
first_name = models.CharField(max_length=100)
last_name = models.CharField(max_length=100)
dbs = models.ImageField(upload_to='dbs_pics')
driving_license = models.ImageField(upload_to='drivers_license_pics', null=True, blank=True)
national_id = models.ImageField(upload_to='national_id_pics', null=True, blank=True)
def __str__(self):
return f"{self.first_name}'s application form"
my forms.py
class TutorValidationForm(forms.ModelForm):
class Meta:
model = TutorValidator
fields = ['first_name', 'last_name', 'driving_license', 'national_id']
labels = {
'national_id': _('National ID')
}
my views.py
class TutorValidatorView(LoginRequiredMixin, FormView):
template_name = 'account/tutor_validator.html'
form_class = TutorValidationForm
success_url = '/'
The error is because TutorValidator requires that you set the user profile foreign key which your form currently does not support, so you need a way to set this to the object you are creating, and use the current logged in user (the one who is submitting the form).
You can do this by overriding form_valid. Try with:
class TutorValidatorView(LoginRequiredMixin, FormView):
...
def form_valid(self, form):
tutor_validator = form.save(commit=False)
tutor_validator.user = self.request.user.tutor_profile
tutor_validator.save()
return HttpResponseRedirect(self.get_success_url())
Note that the current user needs to already have an existing TutorProfile. Otherwise you need to create that first to connect it to TutorValidator

Django admin queryset foreign key to user django-allauth

I have an e-commerce development and I'm looking to send an email to the client from the admin site, I can´t the queryset correclty to do this. I have the following model:
models.py:
class Orden(models.Model):
cliente = models.ForeignKey(
User, on_delete=models.CASCADE, verbose_name='Usuario')
productos = models.ManyToManyField(OrdenProducto)
fecha_orden = models.DateTimeField(auto_now_add=True)
completada = models.BooleanField(default=False, null=True, blank=True)
id_transaccion = models.CharField(max_length=20, null=True)
correo_enviado = models.BooleanField(default=False, null=True, blank=True)
datos_pedido = models.ForeignKey(
'DatosPedido', on_delete=models.SET_NULL, blank=True, null=True)
pago = models.ForeignKey(
'Pago', on_delete=models.SET_NULL, blank=True, null=True)
cupon = models.ForeignKey(
'Cupon', on_delete=models.SET_NULL, blank=True, null=True)
class Meta:
verbose_name_plural = "Orden"
def __str__(self):
return self.cliente.username
cliente has a foreign key to the User model and I want to get the email address, I have tried many ways but I just can´t get it.
admin.py:
class OrdenAdmin(admin.ModelAdmin):
list_display = ('cliente', 'completada', 'correo_enviado')
actions = ['enviar_correo']
def enviar_correo(self, request, queryset):
queryset.update(correo_enviado=True)
a = queryset.get(cliente=self.user.email)
send_mail('test', 'test', 'xxxxxx#mail.com',
['a], fail_silently=True)
You can try iterating the queryset to access the specific data in the rows.
Try the following code.
class OrdenAdmin(admin.ModelAdmin):
list_display = ('cliente', 'completada', 'correo_enviado')
actions = ['enviar_correo']
def enviar_correo(self, request, queryset):
queryset.update(correo_enviado=True)
for obj in queryset:
email = obj.cliente.email
send_mail('test', 'test', email,
['a], fail_silently=True)
I hope this code helps you
Unless you have extended the default user model or have created Your Own user model, django default user model does not have an email field.
So if you have extended or created Your Own model you can do
myordenobj.cliente.email
But if you're using the default user model and your username is an email then do.
myordenobj.cliente.username

How to check the status field in models django and send mail to the user?

I wrote a fullstack django ticketing system for a company. Everything works, login, register, posting a ticket, database, send mail to admin. Only thing that is left is to check the status field of the ticket and if its true send an email to the user who posted it.
class tickets(models.Model):
name = models.ForeignKey(devices, on_delete=models.CASCADE, blank=True, null=True)
location = models.CharField(max_length=200)
company = models.CharField(max_length=200)
serial_number = models.CharField(max_length=200)
problem = models.CharField(max_length=1000)
contact_number = models.CharField(max_length=200)
status = models.BooleanField(default=False)
author = models.ForeignKey(User, on_delete=models.CASCADE, r elated_name="authorname", null=True)
executive = models.ForeignKey(executives, on_delete=models.CASCADE, blank=True, null=True)
def __str__(self):
return self.problem
you can do like this
from django.core.mail import send_mail
class tickets(models.Model):
email_as_send = models.BooleanField(default=False)
...
def save(self):
if self.status and self.email_as_send:
send_mail("subject", "message","your_website#email.fr", [self.author.email])
self.email_as_send = True
super().save()

Problems with implementing inviting feature

I am working on the social network project and want to create feature that will give me opportunity to invite users to communities with invite url(UUID).Who can explain how to do that, i have tried to do that with context processors,but it doesn't work
models.py
class Room(models.Model):
title = models.CharField(max_length=100, unique=True)
slug = models.SlugField(max_length=100, null=True, blank=True)
description = models.TextField(max_length=500)
students = models.ManyToManyField(User,related_name='room_students',blank=True)
created = models.DateTimeField(default=timezone.now)
subjects = models.ManyToManyField(Subject,related_name='room_subjects',blank=True)
stream_time = models.TimeField()
max_students_amount = models.PositiveIntegerField()
room_type = models.CharField(max_length=10,choices=TYPES)
invite_url = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
is_active = models.BooleanField(default=True)
views.py
#login_required
def submit_invite(request,room):
invite_url = request.get.GET['key']
room = get_object_or_404(Room,slug=room)
user = request.user
if room.invite_url != invite_url:
return HttpResponseNotFound
room.students.add(user)
return room.get_absolute_url()
#login_required
def join_room(request,room):
room = get_object_or_404(Room,slug=room)
user = request.user
room.students.add(user)
return HttpResponse(room.students.count())
urls.py
path('rooms/<room>/invite?key=<invite_url>/',submit_invite,name='sumbit_invite'),

Categories