Django displaying each object in a button - python

Good day, I have a page to test where tickets are created and where all created tickets (titles) are listed. Now you should be able to click on the title of a created ticket.
The button then redirects to an extra page where all the information of the specific ticket is.
I've always had trouble displaying user specific stuff, so what needs to be done so that the href="" of each link redirects in HTML to the specific ticket?
I did the following
\\forms.py
{% for i in request.user.addtitle_set.all %}
<div>
{% if i.user == request.user %} {{ i.title }} {% endif %}
<form action="{% url SOMETHING_HERE i.id}" style="display: inline">
<button type="submit">View Ticket</button>
</form>
</div>
<br />
{% endfor %}
\\urls.py
path('dashboard/user/ticket', ticket_view),
path('dashboard/user/ticket/<int:id>/',
ticket_system_view, name="view_ticket"),
\\ models.py
class Ticket(models.Model):
user = models.ForeignKey(
settings.AUTH_USER_MODEL,
default=None,
null=True,
on_delete=models.CASCADE,
)
title = models.CharField(max_length=200)
description = models.TextField()
creator_adress = models.GenericIPAddressField(null=True)
start_date = models.DateTimeField(default=timezone.now)
def __str__(self):
return str(self.title)
\\views.py
#login_required
def ticket_view(request, id, *args, **kwargs):
try:
obj = Ticket.objects.get(id=id)
except Ticket.DoesNotExist:
return redirect('/')
if request.method == 'POST':
form = TicketForm(request.POST, instance=Ticket(user=request.user))
if form.is_valid():
obj = form.save(commit=False)
obj.creator_adress = get_client_ip(request)
obj.save()
return redirect('/dashboard/user/ticket')
else:
form = TicketForm()
return render(request, 'ticket.html', {'form': form})
def ticket_system_view(request, id, *args, **kwargsw):
# Here I will put all the stuff for the specific ticket page
return render(request, 'ticket_system.html', {})
Edit:
I can not even access the page because of the error
TypeError at /dashboard/user/ticket
ticket_views() missing 1 required positional argument: 'id'
Edit 2.0:
Solution:
path('dashboard/user/ticket/', ticket_view),
path('dashboard/user/ticket/<int:id>/',
ticket_system_view, name="view_ticket"),
{% for i in request.user.ticket_set.all %}
<a href="{% url 'view_ticket' i.id %}"
>{% if i.user == request.user %} {{ i.title }} {% endif %}</a
>
<br />
{% endfor %}

Your urls.py
path('dashboard/user/ticket', ticket_view),
path('dashboard/user/ticket/<int:id>/',
ticket_system_view, name="view_ticket"),
Should be
path('dashboard/user/ticket/<int:id>', ticket_view, name="some_name"),
path('dashboard/user/ticket/<int:id>/',
ticket_system_view, name="view_ticket"),
As ticket_view expects an id

ticket_views() missing 1 required positional argument: 'id'
In your views.py you are getting argument id so it must be passed.
Change your urls.py as
path('dashboard/user/ticket/<int:pk>', ticket_view, name='ticket_view'),
path('dashboard/user/ticket/<int:id>/',
ticket_system_view, name="view_ticket"),
Also your urlnamespace in your form as
<form action="{% url 'ticket_view' i.id %}" style="display: inline">
There must be spaces before and after % in your url template tag. You were missing ending % add that too.

Related

(Django) Can't Update Post On My Blog (function based view)

After displaying my posts, I don't manage to Edit any of them.
When I print the instance variable which is in views.py in my terminal, it displays only the title and the author like this title - author, which is the method defined in models.py.
Help please!
Views.py
#login_required(login_url='login_view')
def update_post_view(request, post_id, slug=None):
instance = Article.objects.get(id = post_id)
if request.method == 'POST':
form = UpdatePostForm(request.POST, request.FILES, instance=instance)
if form.is_valid():
form.save()
return redirect('posts_view')
else:
form = UpdatePostForm(instance=instance)
return render(request,'update_post.html', {'form':form})
forms.py
class UpdatePostForm(forms.ModelForm):
class Meta:
model = Article
fields = ('author',)
title = forms.CharField(max_length=255, label='username',
widget= forms.TextInput(attrs= {'placeholder':'Title...', 'class': 'title'}))
body = forms.CharField(max_length=255, label='body', required=True, widget=forms.Textarea(attrs={'placeholder':'Start writing your post...'}))
urls.py
path('update_post/<int:post_id>/<slug:slug>', views.update_post_view, name='update_post_view')
update_post.html
{% extends 'base.html' %}
{% block title %}Update Post{% endblock %}
{% block content %}
<h2>Update Posts...</h2>
<form action="" method="POST">
{% csrf_token %}
<div>
<h3>{{form.title}}</h3>
<small>{{form.author}}</small>
<p>{{form.body}}</p>
</div>
<button class="btn btn-secondary">Update</button>
</form>
{% endblock %}

Form not submitting to the DataBase when using HTMX

I have the following models, and as you can see they are related to each other
class Leads(models.Model):
project_id = models.BigAutoField(primary_key=True, serialize=False)
created_at = models.DateTimeField(auto_now_add=True)
expected_revenue = MoneyField(decimal_places=2,max_digits=14, default_currency='USD')
expected_licenses = models.IntegerField()
country = CountryField(blank_label='(select_country)')
status = models.CharField(choices=[('Open', 'Open'), ('Closed', 'Closed'), ('Canceled', 'Canceled'),
('Idle', 'Idle')
], max_length=10)
estimated_closing_date = models.DateField()
services = models.CharField(choices=[('Illumination Studies', 'Illumination Studies'),
('Training', 'Training'),('Survey Design Consultancy', 'Survey Design Consultancy'),
('Software License', 'Software License'),
('Software Development','Software Development')], max_length=40)
agent = models.ForeignKey(Profile, default='agent',on_delete=models.CASCADE)
company = models.ForeignKey(Company,on_delete=models.CASCADE)
point_of_contact = models.ForeignKey(Client, default='agent',on_delete=models.CASCADE)
updated_at = models.DateTimeField(auto_now=True)
application = models.CharField(choices=[('O&G','O&G'),('Renewables','Renewables'),('Mining','Mining'),
('Other','Other'),('CSS','CSS')],
default='O&G',max_length=20)
sub_category = models.CharField(choices=[('Wind','Wind'),('Geo-Thermal','Geo-Thermal'),('Solar','Solar'),
('Tidal','Tidal')], max_length=20, blank=True)
#property
def age_in_days(self):
today = date.today()
result = self.estimated_closing_date - today
return result.days
def __str__(self):
return f'{self.project_id}'
class LeadEntry(models.Model):
revenue = MoneyField(decimal_places=2,max_digits=14, default_currency='USD',blank=True)
date = models.DateField()
lead_id = models.ForeignKey(Leads,on_delete=models.CASCADE)
id = models.BigAutoField(primary_key=True, serialize=False)
probability = models.DecimalField(max_digits=2, decimal_places=2, default=0, blank=True)
#property
def est_revenue(self):
result = self.revenue * probabiity
return result
Essentially a lead entry is related to the lead, and I'm using HTMX to essentially add data to LeadEntry database using a form.
Form
class LeadEntryForm(forms.ModelForm):
class Meta:
model = LeadEntry
fields = ('lead_id','date','revenue','probability')
widgets = {'date': DateInput()}
I have 2 views, one that will simply pass an HTML with a button for the user to add entries to the database, and another view with the actual form
views
#login_required
def add_to_forecast(request):
id = request.GET.get('project_id')
request.session['lead_id'] = id
return render(request, 'account/lead_forecast.html')
#login_required
def forecast_form(request):
if request.method=='POST':
form = LeadEntryForm(data=request.POST or None)
if form.is_valid():
form.save(commit=False)
messages.success(request,"Successful Submission")
return redirect('add_to_forecast')
lead_id = request.session['lead_id']
data = {'lead_id':lead_id}
context = {
"form":LeadEntryForm(initial=data)
}
return render(request, 'account/lead_entry_forecast.html', context)
Lastly, there are 2 HTML pages, the first one is associated with add_to_forecast and renders a simple page, this is where the HTMX happens and this adds the form from the next HTML page
{% extends "base.html" %}
{% load crispy_forms_tags %}
{% load static %}
{% block title %}Client Information {% endblock %}
{% block content %}
<h1> Add Lead to Sales Forecast </h1>
<p>Click the Button below to add a Payment Date</p>
<button type="button" hx-get="{% url 'lead_entry_forecast' %}" hx-target="#leadform" hx-swap="beforeend" >
Add Lead </button>
<div id="leadform">
<br>
</div>
{% endblock %}
The form that is added by the user as many times they want to do so
{% load crispy_forms_tags %}
{% load static %}
{% block content %}
<div class="container-fluid">
<form method="post" enctype="multipart/form-data" action=".">
{% csrf_token %}
<div class="row justify-content-center">
<div class="col-sm-1">
{{ form.lead_id|as_crispy_field }}
</div>
<div class="col-sm-2">
{{ form.date|as_crispy_field }}
</div>
<div class="col-sm-2">
{{ form.revenue|as_crispy_field }}
</div>
<div class="col-sm-1">
{{ form.probability|as_crispy_field }}
</div>
<div class="col-sm">
<input type="submit" value="Submit" >
</div>
</div>
</form>
</div>
<hr>
{% endblock %}
The problem I have is that after submitting the form, everything seems to be working, obviously, at the moment you can only submit one lead, as I still have to add more logic, but at the moment the form is not sending data to the DB, after some debugging, I was not able to pass the POST, it seems like is just not submitting anything.
Any help will be highly appreciated
Update - 12/4/2021
I have tried to submit data using the form and it actually works, so there is nothing wrong with the form submitted the POST.request, if I go directly to the URL, it works fine, so the form is submitted correctly and the database is updated.
I still don't understand why is not working when the form is rendered by the htmx, so it has something to do with that.
When you are designing an HTMX page, you have to be careful with the post request, so I was processing the form in the wrong view, please see below the views:
#login_required
def add_to_forecast(request):
form = LeadEntryForm(data=request.POST or None)
if request.method == 'POST':
if form.is_valid():
form.save()
return HttpResponse("Success")
else:
return render(request, 'account/lead_entry_forecast.html', {"form": form})
id = request.GET.get('project_id')
request.session['lead_id'] = id
return render(request, 'account/lead_forecast.html')
#login_required
def forecast_form(request):
lead_id = request.session['lead_id']
data = {'lead_id':lead_id}
context = {
"form":LeadEntryForm(initial=data)
}
return render(request, 'account/lead_entry_forecast.html', context)
Now it works as it should

Like button is working but not changing to Unlike in django

I've been trying to debug this issue for a day together with my expert coder but we were unable to identify the issue here. The like button works perfectly all right and I am able to query the total likes, but the Clap button does not change to unlike and we are unsure why. I believe the error lies in either the html line:
{% if liked and post.slug == blog_post.slug %} Unlike {% else %} Like {% endif %}
or the django line:
context["liked"] = True if blog_post.likes.filter(id=request.user.id).exists() else False
Big thanks if you can identify the issue here!
views.py
def home_feed_view(request, *args, **kwargs):
context = {}
blog_posts = BlogPost.objects.all()
context['blog_posts'] = blog_posts
if request.method=="POST":
slug=request.POST["submit_slug"]
blog_post = get_object_or_404(BlogPost, slug=slug)
context['blog_post'] = blog_post
context["liked"] = True if blog_post.likes.filter(id=request.user.id).exists() else False
context['total_likes'] = blog_post.total_likes()
type_of_post = TypeofPostFilter(request.GET, queryset=BlogPost.objects.all())
context['type_of_post'] = type_of_post
paginated_type_of_post = Paginator(type_of_post.qs, 13 )
page = request.GET.get('page')
post_page_obj = paginated_type_of_post.get_page(page)
context['post_page_obj'] = post_page_obj
return render(request, "HomeFeed/snippets/home.html", context)
def LikeView(request, slug):
context = {}
user = request.user
if not user.is_authenticated:
return redirect('must_authenticate')
post = get_object_or_404(BlogPost, slug=slug)
liked = False
if post.likes.filter(id=request.user.id).exists():
post.likes.remove(request.user)
liked = False
else:
post.likes.add(request.user)
liked = True
return redirect(request.META.get('HTTP_REFERER', ''))
<td class="table-primary">
<form action="{% url 'HomeFeed:like_post' post.slug %}" method="POST">
{% csrf_token %}
<button type="submit" name="submit_slug" value="{{ post.slug }}" class='btn btn-primary btn-sm'>
{% if liked and post.slug == blog_post.slug %} Unlike {% else %} Like
{% endif %}
</button>
{{ post.total_likes }} Clap {{ post.total_likes|pluralize }}
</form>
</td>
urls.py
path('<slug>/like/', LikeView, name='like_post'),
models.py
class BlogPost(models.Model):
chief_title = models.CharField(max_length=50, null=False, blank=False)
body = models.TextField(max_length=5000, null=False, blank=False)
likes = models.ManyToManyField(settings.AUTH_USER_MODEL, related_name='blog_posts', blank=True)
author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
slug = models.SlugField(blank=True, unique=True)
Ok so here's a much simpler way to perform a check if a model exist in a m2m field in another model:
html
{% if request.user in blog_post.likes.all %} Unlike {% else %} Like {% endif %}
view
if request.user in blog_post.likes.all():
P.S. In your model you should rename the field likes to likers since its a relation with a User model not a Like model :)
EDIT
So, to easily display a list of posts and their like buttons accordingly on a single page you wanna do this in your template:
views.py
def posts(request):
blog_posts = BlogPost.objects.all()
return render(request, 'index.html', {'blog_posts': blog_posts})
index.html
{% for post in blog_posts %}
<h1>{{ post.chief_title }}</h1>
<p>{{ post.author }} says: </p>
<b>{{ post.body }}</b>
<p> This post is liked by: </p>
{% for user in post.likes %}
<p>{{ user.username }}</p>
{% endfor %}
{% if request.user not in post.likes.all %}
Like
{% else %}
Unlike
{% endif %}
{% endfor %}

Comment form in django didn't save the new comments

I've created a new form for comments the articles on a website. When I add the new comment from django admin everything works ok, but when I try to add the new comment directly from detail page nothings happen and I'am redirecting to the page with list of articles.
here are my files
models.py:
class Komentarz(models.Model):
post = models.ForeignKey(Wpisy, related_name="komentarze", verbose_name="Komentarze do artykułu", on_delete=models.CASCADE)
name = models.CharField(max_length=80, verbose_name="Imię")
email = models.EmailField(verbose_name="Email")
content = models.TextField(verbose_name="Treść komentarza")
created_date = models.DateTimeField(verbose_name="Utworzono", auto_now_add=True)
active = models.BooleanField(verbose_name="Aktywny?", default=True)
class Meta:
ordering = ('created_date',)
verbose_name="Komentarz"
verbose_name_plural="Komentarze"
def __str__(self):
return 'Komentarz dodany przez {} dla strony {}'.format(self.name, self.post)
vies.py with the function of details
from django.shortcuts import render, get_object_or_404
from .models import Wpisy, Komentarz
from .forms import KomentarzeForma
....
def detale_bajki(request, slug, ):
detale_bajki = get_object_or_404(Wpisy, slug=slug)
komentarze = detale_bajki.komentarze.filter(active=True)
if request.method == 'POST':
formularz_komentarza = KomentarzeForma(data=request.POST)
if formularz_komentarza.is_valid():
nowy_komentarz = formularz_komentarza.save(commit=False)
nowy_komentarz.detale_bajki = detale_bajki
nowy_komentarz.save()
else:
formularz_komentarza = KomentarzeForma()
return render(request, 'bajki/detale_bajki.html', {'detale_bajki': detale_bajki, 'komentarze': komentarze, 'formularz_komentarza': formularz_komentarza})
forms.py
from .models import Komentarz
from django import forms
class KomentarzeForma(forms.ModelForm):
class Meta:
model = Komentarz
fields = ('name', 'email', 'content')
and detail.html
...
{% with komentarze.count as total_komentarze %}
<h2>
{{ total_komentarze }} komentarz{{ total_komentarze|pluralize:"y" }}
</h2>
{% endwith %}
{% for komentarz in komentarze %}
Komentarz dodany przez <strong>{{komentarz.name}}</strong>
{{komentarz.created_date}}
<p>
{{ komentarz.content|linebreaks }}<br>
{% empty %}
<p>Nie dodano jeszcze żadnych komentarzy</p>
{% endfor %}
{% if nowy_komentarz %}
<h2>Twój komentarz został dodany</h2>
{% else %}
<h2>Dodaj nowy komentarz</h2>
<form action="." method="post">
{{formularz_komentarza.as_p}}
{% csrf_token %}
<p><input type="submit" value="Dodaj komentarz"></p>
</form>
{% endif %}
clas Wpisy in models.py
class Wpisy(models.Model):
title = models.CharField(max_length=400, verbose_name="Tytuł")
slug = models.SlugField(unique=True, max_length=400,verbose_name="Przyjazny adres url")
content = models.TextField()
status_audio = models.BooleanField(default=False, verbose_name="Czy dostępny będzie plik audio?")
audio_file = models.FileField(upload_to='uploads/',verbose_name="Plik audio")
created_date = models.DateTimeField(blank=True, null=True, verbose_name="Data utworzenia")
category = models.ForeignKey(Kategorie, verbose_name="Kategoria", on_delete=models.CASCADE)
class Meta:
verbose_name="Wpis"
verbose_name_plural="Wpisy"
def __str__(self):
return self.title
Your url pattern is
path('bajki/<slug>', views.detale_bajki, name='detale_bajki')
Note that it doesn't have a trailing slash. Your form's action is "."
<form action="." method="post">
That means you are submitting to /bajki/, which is the wrong URL.
You could fix this by adding a trailing slash to the url (which is common in Django URLs)
path('bajki/<slug>/', views.detale_bajki, name='detale_bajki')
Or you could change the form action to "" instead of ".". In the comments it looks like you fixed the issue by changing the form action to {{ detale_bajki.slug }}.
However these changes to the form action are fragile, and could break if you change your URL patterns again. The best approach is to use the {% url %} tag to reverse the correct URL.
<form action="{% url 'detale_bajki' detale_bajki.slug %}" method="post">
Try out:
nowy_komentarz.post = detale_bajki
...
return render(request, 'html page', {'key': 'what you want to return to your context'}) # don't fornget to add some return to your view.

Page not save forms data in django

I am trying to do exercise 7 in tango with django where i must save new page to specific category by adding information to forms.
So I write new code to forms.py
class PageForm(forms.ModelForm):
title = forms.CharField(max_length=128, help_text="Please enter the title of the page.")
url = forms.CharField(max_length=200, help_text="Please enter the url of the page.")
views = forms.IntegerField(widget=forms.HiddenInput(), initial=0)
class Meta:
model = Page
def clean(self):
cleaned_data = self.cleaned_data
url = cleaned_data.get('url')
if url and not url.startswith('http//'):
url = 'http://' + url
cleaned_data['url'] = url
return cleaned_data
fields = ('title', 'url', 'views')
def save_form(self):
if self.is_valid():
page = self.save(commit=False)
try:
cat = Category.objects.get(name=category_name)
page.category = cat
except:
return render_to_response('rango/add_category.html', {}, context)
page.views = 0
page.save()
return True
else:
return False
Then I edit views.py
def add_page(request, category_name_url):
context = RequestContext(request)
category_name = decode_url(category_name_url)
if request.method == 'POST':
form = PageForm(request.POST)
if form.save_form():
return category(request, category_name_url)
else:
print form.errors
else:
form = PageForm()
return render_to_response( 'rango/add_page.html',
{'category_name_url': category_name_url,
'category_name': category_name,
'form': form},
context)
def decode_url(element):
return element.replace(' ', '_')
def encode_url(element):
return element.replace('_', '')
Then I created template:
Rango
<body>
<h1>Add page to category</h1>
<form id="page_form" method="post" action="/">
{% csrf_token %}
{% for hidden in forms.hidden_fields %}
{{ hidden }}
{% endfor %}
{% for field in form.visible_fields %}
{{ field.errors }}
{{ field.help_text }}
{{ field }}
{% endfor %}
<input type="submit" name="Submit" value="Add a page" />
</form>
</body> </html>
I have made reference to new page in category.html
Add page to this category
And of course a edit urls.py
> url(r'^rango/category/(?P<category_name_url>\w+)/add_page/$',
> views.add_page, name='add_page'),
Everything is visible and I am able to fill form. But when i confirm data by clicking on button, page is return to home and not in category and new page is not save in database. So please someone, where a have error?
Your <form> element has the action set to action="/". This makes the form submit send a POST request to the homepage not the current page. You can correct this by making the form action empty action="" to submit to the current URL or be explicit and use the {% url %} template tag for the required form action.

Categories