Problems with implementing inviting feature - python

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'),

Related

How Can I Integrate Flutterwave Paymwnt Gate Way with Django

I am working on a Django Project where I want to collect payment in Dollars from Applicants on the portal, and I don't know how to go about it. Though I have been following an online tutorial that shows how to do it but the result I am having is different with the recent error which says 'module' object is not callable.
Remember that I have tested my configured environment and also imported it into my views on top of the page.
Profile model code:
class Profile(models.Model):
applicant = models.OneToOneField(User, on_delete=models.CASCADE, null = True)
surname = models.CharField(max_length=10, null=True)
othernames = models.CharField(max_length=30, null=True)
gender = models.CharField(max_length=6, choices=GENDER, blank=True, null=True)
nation = models.CharField(max_length=255, choices=NATION, blank=True, null=True)
state = models.CharField(max_length=20, null=True)
address = models.CharField(max_length=200, null=True)
phone = models.CharField(max_length=16, null=True)
image = models.ImageField(default='avatar.jpg', upload_to ='profile_images')
def __str__(self):
return f'{self.applicant.username}-Profile'
Education/Referee Model code:
class Education(models.Model):
applicant = models.OneToOneField(User, on_delete=models.CASCADE, null = True)
qualification = models.CharField(max_length=60, choices=INSTITUTE, default=None, null=True)
instition = models.CharField(max_length=40, null=True)
reasons = models.CharField(max_length=100, null=True)
matnumber = models.CharField(max_length=255, null=True)
reference = models.CharField(max_length=100, null=True)
refphone = models.CharField(max_length=100, null=True)
last_updated = models.DateTimeField(auto_now_add=False, auto_now=True)
def __str__(self):
return f'{self.applicant}-Education'
Submitted Model code:
class Submitted(models.Model):
applicant = models.OneToOneField(User, on_delete=models.CASCADE, null=True)
application = models.UUIDField(primary_key = True, editable = False, default=uuid.uuid4)
confirm = models.BooleanField()
approved = models.CharField(max_length=20, null=True)
date = models.DateTimeField(auto_now_add=True)
def save(self, *args, **kwargs):
self.application == str(uuid.uuid4())
super().save(*args, **kwargs)
def __unicode__(self):
return self.applicant
def __str__(self):
return f'Application Number: {self.application}-{self.applicant}'
Scholarship Model code:
class Scholarship(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE, null = True)
name = models.CharField(max_length=100, null = True)
description = models.CharField(max_length=200, null = True)
category = models.CharField(max_length=60, choices=INSTITUTE, default=None, null=True)
amount = models.FloatField()
date = models.DateTimeField(auto_now_add=True)
def __str__(self):
return f'WASU Scholarship: {self.name}-{self.name}'
My View for printing slip:
def AppSlip(request):
check_submited = Submitted.objects.get(applicant=request.user)
check_education = Education.objects.get(applicant = request.user)
candidate_edu = check_education.qualification
scholarship = Scholarship.objects.get(category=candidate_edu)
context = {
'candidate_edu':candidate_edu,
'scholarship':scholarship,
}
return render(request, 'user/slip.html', context)
My view for applicant to fill form for payment which I want their Profile captured automatically in the form:
def scholarship_detail(request, pk):
data = Scholarship.objects.get(id=pk)
if request.method=='POST':
form = PaymentForm(request.POST)
if form.is_valid():
user = Profile.objects.get(applicant=request.user)
name= user.surname
email = form.cleaned_data['email']
amount = form.cleaned_data['amount']
phone = form.cleaned_data['phone']
context = {'applicant':name, 'email':email, 'amount':amount, 'phone':phone}
return process_payment(request, context)
else:
form = PaymentForm()
ctx={
'form':form,
'product':data,
}
return render(request, 'user/scholarship.html', ctx)
My form code for Payment: How can query logged in user profile and fill into name, email, phone, amount from Scholarship Model into amount form filled.
class PaymentForm(forms.Form):
name = forms.CharField(label='Your name', max_length=100)
email = forms.EmailField()
phone=forms.CharField(max_length=15)
amount = forms.FloatField()
View code for processing Payment (Where I am suspecting the error). Though I have configured my env using django-dotenv with the Flutterwave Secret Key in it.
#login_required(login_url='user-login')
def process_payment(request, newContext={}):
auth_token= dotenv('SECRET_KEY')
hed = {'Authorization': 'Bearer ' + auth_token}
data = {
"tx_ref":''+str(math.floor(1000000 + random.random()*9000000)),
"amount":amount,
"currency":"KES",
"redirect_url":"http://localhost:8000/callback",
"payment_options":"card",
"meta":{
"consumer_id":23,
"consumer_mac":"92a3-912ba-1192a"
},
"customer":{
"email":email,
"phonenumber":phone,
"name":name
},
"customizations":{
"title":"WASU Scholarship 2022",
"description":"Best store in town",
"logo":"https://getbootstrap.com/docs/4.0/assets/brand/bootstrap-solid.svg"
}
}
url = ' https://api.flutterwave.com/v3/payments'
response = requests.post(url, json=data, headers=hed)
response=response.json()
link=response['data']['link']
return link
My payment Response View:
#require_http_methods(['GET', 'POST'])
def payment_response(request):
status=request.GET.get('status', None)
tx_ref=request.GET.get('tx_ref', None)
print(status)
print(tx_ref)
return HttpResponse('Finished')
Anticipating your prompt answers. Thanks

How do I perform a dependent Select Form using two models with pagination in Django

I am work on a Django Project where I have Profile and submited_apps models. The profile model holds details such as applicant, nation, state, phone etc whereas the submited_apps models only records the users whose application were submitted successfully with a applicant field, Universal Unique International Id and date.
How do I have a dependent search form for nation and state and be able to search submited_apps model for selected nation, state and display the result in pagination.
Profile Model Code below
class Profile(models.Model):
applicant = models.OneToOneField(User, on_delete=models.CASCADE, null = True)
surname = models.CharField(max_length=10, null=True)
othernames = models.CharField(max_length=30, null=True)
gender = models.CharField(max_length=6, choices=GENDER, blank=True, null=True)
nation = models.CharField(max_length=10, choices=NATION, blank=True, null=True)
state = models.CharField(max_length=20, null=True)
address = models.CharField(max_length=200, null=True)
phone = models.CharField(max_length=11, null=True)
image = models.ImageField(default='avatar.jpg', upload_to ='profile_images')
Submitted Model Code below"
class submited_apps(models.Model):
applicant = models.OneToOneField(User, on_delete=models.CASCADE, null=True)
application = models.UUIDField(primary_key = True, editable = False, default=uuid.uuid4)
confirm = models.BooleanField()
date = models.DateTimeField(auto_now_add=True)
def save(self, *args, **kwargs):
self.application == str(uuid.uuid4())
super().save(*args, **kwargs)
def __unicode__(self):
return self.applicant
def __str__(self):
return f'Application Number: {self.application}-{self.applicant}'
ModelForm code below:
class Applicant_Search_Form(forms.ModelForm):
class Meta:
model = submited_apps
fields = ['applicant']
Here is my view for the search
def SearchApplicants(request):
context = {}
searchForm = Applicant_Search_Form(request.POST or None)
if searchForm:
list_applicants = submited_apps.objects.filter(applicant__iexact=[searchForm['applicant'].value()])
else:
list_applicants= submited_apps.objects.all()
paginator = Paginator(list_applicants, 5)
page = request.GET.get('page')
paged_listApps = paginator.get_page(page)
context.update({
'list_applicants':paged_listApps,
'searchForm':searchForm,
})
return render(request, 'user/search_applicants_nation.html',context)
My problem is that I am getting this error message upon load of the plage.
Related Field got invalid lookup: icontains

created_by not working with ManyToManyField django

Hello everyone I'm trying top build a task manager web app using django, I need to assign task to one or multiple users I'm using manytomany relation in models.py and in views.py I'm adding created_by user automatically.
My problem is that when I do that I see that no users selected in assigned users but if I add created by user from the form it worked well.
class Task(models.Model):
task_id = models.AutoField(primary_key=True)
shortcode = models.CharField(max_length=15, unique=True, blank=True, null=True)
task_name = models.CharField(max_length=200)
task_progress = models.ForeignKey(TaskProgressStatus, on_delete=models.CASCADE, blank=True, null=True)
customer_name = models.ForeignKey(Customer, on_delete=models.CASCADE, blank=True, null=True)
task_priority = models.ForeignKey(TaskPriority, on_delete=models.CASCADE)
assigned_to_employee = models.ManyToManyField(User)
paid = models.BooleanField(default=False)
on_account = models.BooleanField(default=False)
currency = models.ForeignKey(Currency, on_delete=models.CASCADE, blank=True, null=True)
net_amount = models.DecimalField(decimal_places=2, max_digits=20, blank=True, null=True)
vat = models.IntegerField(default=11)
quote_validity = models.CharField(max_length=200, default='1 Month from offer date')
delivered = models.BooleanField(default=False)
delivered_date = models.DateTimeField(null=True, blank=True)
creation_date = models.DateTimeField(auto_now_add=True)
modified_date = models.DateTimeField(auto_now=True)
due_date = models.DateTimeField(null=True, blank=True)
created_by = models.ForeignKey(User, related_name='created_by_username', on_delete=models.CASCADE, null=True, blank=True)
project = models.ForeignKey(Project, null=True, blank=True, on_delete=models.CASCADE)
file_name = models.FileField(upload_to='projects_files', null=True, blank=True)
notes = models.TextField()
def __str__(self):
return str(self.task_name)
#login_required
def addtask(request):
form = taskForm()
if request.method == 'POST':
form = taskForm(request.POST)
if form.is_valid():
newform = form.save(commit=False)
newform.created_by = request.user
newform.save()
return HttpResponseRedirect(request.path_info)
else:
context = {'form':form}
return render(request, 'tasks/add_task.html', context)
Update
As well pointed out by Ahmed I. Elsayed there is some inconsistency in the title of the question, since the created_by field is actually a ForeignKey, not a ManyToManyField.
That being said, your issue is actually with the foreign key.
My suggestion is to first of all be sure that your form is actually valid. You can do that by printing something inside the if form.is_valid() block.

given a clinic_id, how do I get the mods belonging the profile of the user

I am really stuck here and I am considering changing my models and starting fresh
I have these models
class CustomUser(AbstractBaseUser):
email = models.EmailField(max_length=255, unique=True)
password2 = models.CharField(max_length=128)
first_name = models.CharField(max_length=50)
last_name = models.CharField(max_length=50)
active = models.BooleanField(default=True) # Able to login
practitioner = models.BooleanField(default=False) # has access to a clinc
admin = models.BooleanField(default=False) # superuser
staff = models.BooleanField(default=False) # staff
timestamp = models.DateTimeField(auto_now_add=True)
class Modalities(models.Model):
name = models.CharField(max_length=50)
def __str__(self):
return self.name
class Profile(models.Model):
user = models.OneToOneField(User,
related_name='prof_user',
on_delete=models.CASCADE)
bio = models.TextField(max_length=5000)
mods = models.ManyToManyField(Modalities)
phone = PhoneNumberField()
clinics = models.ManyToManyField(Clinic)
personnummer = models.CharField(max_length=12)
street = models.CharField(max_length=50)
city = models.CharField(max_length=50)
consent = models.BooleanField()
class Clinic(models.Model):
practitioner = models.OneToOneField(User,
related_name='prac_user',
on_delete=models.CASCADE)
lat = models.FloatField(null=True, blank=True)
lng = models.FloatField(null=True, blank=True)
name = models.CharField(max_length=128, )
phone = PhoneNumberField()
description = models.TextField(max_length=5000)
street = models.CharField(max_length=128, )
city = models.CharField(max_length=128, )
From my view I am trying to get the mods from the Profile model, starting with the clinic_id
something like
clinic = Clinic.objects.filter(pk=clinic_id)
profile = get_object_or_404(Profile, user=request.user)
mods = profile.mods
I have tried so many things over the last few hours and I just can't figure this out.
Do I need to change my models or am I going about accessing this wrong?
profile = Profile.objects.filter(user=Clinic.objects.get(pk=clinic_id).practitioner)
mods = profile[0].mods.all() if profile else []
clinic = Clinic.objects.get(clinic_id)
profile = get_object_or_404(Profile, user=request.user)
mods = profile.mods.filter(name__startswith=clinic.pk)
but not that if the clinic_id is 1
the mods starting with 10,11,111 etc will also be selected unless you have a particular way of entering modality name.
I believe your view needs to look something like:
clinic = clinic.objects.get(pk=clinic_id)
profile = profile.objects.get(clinic.practitioner)
mods = mods.objects.filter(pk__in=profile.mods.values_list('pk'))

How to combine queryset via ManyToManyField in django

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.

Categories