Django how to make model for user model - python

I'm developing to-list app with registration . I have two models : Model for User and Model for Tasks . I add new task throw Ajax to one user it adding and displaying for every user. Is there any solutions ? Here some pictures
Here is my code:
models.py
class Task(models.Model):
title=models.IntegerField()
date = models.DateTimeField(default=datetime.now,blank=True)
is_published=models.BooleanField(default=True)
class CustomUser(models.Model):
user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
image=models.FileField(upload_to='photos/%Y/%m/%d/',null=True,blank=True)
views.py
if request.method == 'POST' and request.POST['form_type'] == 'task':
if request.is_ajax():
addtask = AddTask(request.POST)
if addtask.is_valid():
user = request.user.id
addtask.objects.filter(user=user).cleaned_data
addtask.objects.filter(user=user).save()
task_object = Task.objects.filter(user=user)(addtask)
return JsonResponse({'error': False, 'data': task_object})
else:
print(addtask.errors)
return JsonResponse({'error': True, 'data': addtask.errors})
else:
error = {
'message': 'Error, must be an Ajax call.'
}
return JsonResponse(error, content_type="application/json")
addtask = AddTask()
task = Task.objects.order_by('-date').filter(is_published=True)
html page
{% if task %}
{% for tas in task %}
Task content
{% endfor %}
{% else %}
{% endif %}

Maybe you should add relation to CustomUser in Task model and filter tasks by owner in view before to render data to template?
class Task(models.Model):
title=models.IntegerField()
date = models.DateTimeField(default=datetime.now,blank=True)
is_published=models.BooleanField(default=True)
user=models.ForeignKey(CustomUser)
class CustomUser(models.Model):
user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
image=models.FileField(upload_to='photos/%Y/%m/%d/',null=True,blank=True)
And in view:
...
addtask = AddTask()
task = Task.objects.filter(is_published=True, user_id=request.user.id).order_by('-date')

So the mistake is that you never connected your CustomUser model with your Task model. They should have a relationship like one to many. Once that is achieved, you have to retrieve only the tasks related to the user of interest from the database and send them to the HTML page. Then only the tasks related to one particular user will be displayed.

If you want to create CustomUser model, you should create a class and inherit it from AbstractBaseUser or AbstractUser(django documentation).
Your Task model hasn't relationships with CustomUser. You create AddTask(?) instance but didn't bind it with any user.
You did not submit a view which renders HTML template, but I think that your query is something like Tasks = Task.objects.all() which return all tasks.
This is how you should create CustomUser model
This is documentation about relationships in Django
This is about making queries in Django

Related

Can't display foreign key related object in Django DetailView

I've got a booking class which is related to Customer and Barber models. I can display all bookings using the detail view, however, can't figure out how to display a booking/bookings that a specific barber has. Basically, I want to get a booking or multiple bookings of a barber based on the ID given to the url.
Here is my model:
customer_id = models.ForeignKey(User, on_delete = models.CASCADE,)
barber_id = models.ForeignKey(Barber, on_delete = models.CASCADE)
timeslot = models.DateTimeField('appointment')
def __str__(self):
return f"{self.customer_id} {self.barber_id} {self.timeslot}"
def get_absolute_url(self):
return reverse("model_detail", kwargs={"pk": self.pk})
My view:
class GetBarberBooking(DetailView):
model = Booking
template_name = "barber_booking.html"
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['barber'] = Booking.objects.filter(
id=self.kwargs.get('<str:pk'))
return context
My url path:
path('barber-booking/<str:pk>/', views.GetBarberBooking.as_view(), name='barber-booking'),
You can remove this piece of code:
context['barber'] = Booking.objects.filter(
id=self.kwargs.get('<str:pk'))
And in template just use:
{{ object.barber_id }}
And show all the booking for barber:
{{ object.barber_id.booking_set.all }}
It will show all the the barber. This works because of FK relation between Booking and Barber model. More information can be found in Django documentation. For reverse relation (Many to one), please check this documentation.
FYI, you do not need to create a field name suffix with _id, because Django creates that automatically for you.
Also, if you want to query a Barber, then you should use Barber as the model in the DetailView. Then you can use a similar query mentioned above:
# view
class GetBarberBooking(DetailView):
model = Barber
# template
{{ object.booking_set.all }}

Poll's choices are not showing while accessing from view in template

I am building a Poll App and I am stuck on an Problem.
What i am trying to do :-
I am trying to access all three choices of poll from view in template BUT only one choices is showing. BUT when i access Poll object in view and access choice model from template then all three choices are successfully showing.
models.py
class Poll(models.Model):
user = models.ForeignKey(User, null=True, on_delete=models.CASCADE)
title = models.TextField()
def get_absolute_url(self):
return reverse('detail_poll', kwargs={'pk': self.pk})
class Choice(models.Model):
poll = models.ForeignKey(Poll, on_delete=models.CASCADE)
choice_text = models.CharField(max_length=30)
forms.py
class PollAddForm(forms.ModelForm):
choice1 = forms.CharField(label='Choice 1',max_length=100,min_length=2)
choice2 = forms.CharField(label='Choice 2',max_length=100,min_length=2)
choice3 = forms.CharField(label='Choice 3',max_length=100,min_length=2)
class Meta:
model = Poll
fields = ['title','choice1', 'choice2', 'choice3']
I am increasing choices from forms.
views.py
def detail_poll(request,poll_id):
poll = get_object_or_404(Poll, id=poll_id)
for choice in poll.choice_set.all():
printChoice = choice.choice_text
context = {
'printChoice ':printChoice ,
}
return render(request, 'detail_poll.html',context)
In view i am accessing all the choice from choice_text of the poll.
I am accessing three choices for vote with the same (choice_set) method in template.
AND When i create poll then poll is successfully saving with all three choices. When i vote then poll is successfully voting with choices.
BUT when i accessing the choices to calculate percentage from view then choices are not showing.
With the same method of poll.choice_text.all in template, it does work but not from view.
Any help would be much Appreciated.
Thank You in Advance.
It's only showing one choice because you are sending only one choice to context. i.e the last choice. Check your view thoroughly. When the for-loop stops, printChoice will have the last choice and you are sending that to context. So only one choice will be shown in template.
You should iterate over the choices and save them to a data structure like a dict, set, list etc, and then send it to the context.
It should be like this. I have used a list to store the choice_texts and pass it to context.
def detail_poll(request,poll_id):
poll = get_object_or_404(Poll, id=poll_id)
choice_set = []
for choice in poll.choice_set.all():
choice_set.append(choice.choice_text)
# You can use your percentage calculation here...
context = {
'printChoice ': choice_set ,
}
return render(request, 'detail_poll.html',context)
You can also send the entire queryset to context like this.
context = { 'printChoice': poll.choice_set.all() }
And then in template, show the choice_text like this
{% for choice in printChoice %}
<p>choice.choice_text</p>
{% endfor %}

how to implement an admin approval system for posting blogs in pythondjango

I am building a website where user come and login, after login user publish articles with admin approval . I do not know how to do it. I made a user authentication system where user can login. But i do not know how to make him post data with admin approval.
Therefor you need a condition in your model to be able to query the approved objects (blog posts) to display.
A basic approach could look as follows:
Create a model to store the blog posts and its logic to the database
# models.py
class Blog_Post(models.Model):
text = models.CharField(max_length=500)
is_approved = models.BooleanField(default=False)
def __str__(self):
return self.name
Register your model in the admin so you can approve them via django-admin
from django.contrib import admin
from myproject.myapp.models import Blog_Post
admin.site.register(Blog_Post)
Create a view to only fetch blog posts that have been approved by an admin
# views.py
def get_blog_post(request):
# Only fetch the blog posts that are approved
queryset = Blog_Post.objects.filter(is_approved=True)
return render(request, 'your_html.html', {'queryset' : queryset})
Render the blog posts in your template
# your_html.html
{% for blog_post in queryset %}
<div>{{ blog_post.text }}</div>
{% endfor %}
That's a Good one. You can enable this with adding a new column to your database like onapproval Set it as an boolean variable like 0 or 1 either true or false. Then check for it. If it's true you can set the status as approved and if it is not set it as not approved. The same process will also takes place in admin panel too.

Django: How to retrieve the logged in user's details

I am in the process of learning Django. I am trying to create a simple directory web app. I am able to print out all the users details for the main directory page. However, I want to add a feature that when a person logs into the directory app they are brought to their 'profile' page where they will be able to see all their own details e.g. business name, profile pic.
I know how to retrieve the default fields e.g. username and email. But cannot seem to retrieve the custom fields that I declared myself. Here is my attempts so far...
Models.py:
from django.db import models
from django.contrib.auth.models import User
# Create your models here.
class UserProfileInfo(models.Model):
user = models.OneToOneField(User,on_delete=models.DO_NOTHING)
#additional classes
business_name = models.CharField(max_length=191,blank=True)
trade = models.CharField(max_length=191,blank=True)
portfolio_site = models.URLField(blank=True)
profile_pic = models.ImageField(upload_to='profile_pics',blank=True)
def __str__(self):
return self.user.username
Views.py:
#login_required
def profile(request):
profile = UserProfileInfo.objects.filter(user=request.user)
context = { 'profile': profile }
return render(request, 'dir_app/profile.html',context)
Profile.html:
<div class="container-fluid text-center">
{% for p in profile %}
<h3>{{p.business_name}}</h3>
{% endfor %}
</div>
Since UserProfileInfo is related to User via OneToOneField, you can have one UserProfileInfo per User. So, instead of Filter, you can simply get your desired UserProfileInfo object through your current (logged in) User as follows.
views.py,
profile = UserProfileInfo.objects.get(user=request.user)
Also, before you can get a request.user object, you have to make sure that your user is authenticated and logged in. Otherwise, you might get None in place of a User object and therefore, no associated UserProfileInfo.
Since it is a OneToOneField there is only one Profile object for a User, you thus can obtain this with:
#login_required
def profile(request):
profile = request.user.userprofileinfo
return render(request, 'my_template.html',{'profile': profile})
Then in the template, you render it with:
{{ profile.business_name }}
you can use it directly on template without sending it f:
{{request.user.userprofile}}

How to show every user specific payment for them in django?

I have a problem. I have given some random numbers in admin page as a balance for users and connected it to database. Basically I want it to show for different users different payments. But I don't know what to write in views.py and html page so that it shows different payment for different users.
models.py
class Payment(models.Model):
payment_numbers = models.CharField(max_length=100)
views.py
def payment(request):
receiving1 = Payment.objects.all()
for field in receiving1:
field.payment_numbers
context = {
'receiving1': receiving1
}
return render(request, 'index.html', context)
HTML PAGE
{% for numbers1 in receiving1 %}
<li style="float: right;">Your Balance: Rs. {{numbers1.payment_numbers}}</li>
{% endfor %}
You need to modify your models so that payments have a relationship with your users.
A simple way to do that is a ForeignKey to your user model.
class Payment(models.Model):
payment_numbers = models.CharField(max_length=100)
owner = models.ForeignKey('yourusermodel')
Once this is done, you can update your views to pass only the right payments to the context.
receiving1 = Payment.objects.filter(owner=request.user)
This will of course require you to create new migrations and to ensure your users are properly logged in. Most of this is explained in the Django Tutorial

Categories