I'm doing an app with Django Non Rel on GAE, and i want to show the Profile Image of the user in the template but i can't here is the model:
from django.db import models
from django.contrib.auth.models import User
# Create your models here.
class userProfile(models.Model):
def url(self, filename):
url = "MultimediaData/Users/%s/%s"%(self.user.username, filename)
return url
user = models.OneToOneField(User)
email_public_user = models.EmailField(blank=True, null=True)
url_user = models.CharField(max_length=200, blank=True, null=True)
company_user = models.CharField(max_length=200, blank=True, null=True)
position_user = models.CharField(max_length=200, blank=True, null=True)
photo_user = models.ImageField(upload_to=url)
def __unicode__(self):
return self.user.username
For now i'm adding the photo via admin to see if i can show the image, here is the template
<div class="navbar-header nav-img">
{% if user.get_profile.photo_user %}
<img class="navbar-brand" src="{{user.get_profile.photo_user}}">
<p class="navbar-brand">{{user.get_username}}</p>
{% else %}
<img class="navbar-brand" src="/media/img/principal_html/img1.png">
<p class="navbar-brand">{{user.get_username}}</p>
{% endif %}
It shows the username, but not the image, i put the user.get_profile.photo_user in a and i got this
ahRkZXZ-c29mdHN5c3RlbWFuYWdlcnIiCxIVX19CbG9iVXBsb2FkU2Vzc2lvbl9fGICAgICAzKYKDA/MultimediaData/Users/[username]/img.jpg
There's no view yet because im uploading the image using the django admin and when i save the user with his photo shows the same url
How can i solve this? I need to show the image...plz help
Related
just looking for some detailed pointers on how to hx-push-url as I have come across some problems and looking for some direction. I am a relative beginner at Django and just started using HTMX.
The aim. I'm building a simple image gallery and have a grid of thumbnails, I am using HTMX to load the list of images within that gallery when a uses click a thumbnail.
This works well, I am using Django-HTMX and a if conditional in the View to deal with the HTMX request which serves the partial HTML into the thumbnail page.
The problem was that my URL did not change. My thumbnail is http://127.0.0.1:8000/gallery/ and when I click on a gallery to view images within, the url remains the same, so, I used htmx-push-url so that URL would appear something like http://127.0.0.1:8000/gallery/news. This works and the URL changes.
Anyway, onward.
I have a button on my images list page that take you back to the thumbnail page, but when using this I get a 404 error, and also when I refresh my image list page I get a 404. Obviously there is no URL and view for http://127.0.0.1:8000/gallery/news. I Just have little idea how to solve this.
When I look in the console I get a HTMX-target error when clicked the back button, and nothing happens. And, as I say, a refresh gets a 404.
Code below should explain things better.
Models
name = models.CharField(max_length=200, null=True)
description = models.CharField(max_length=200, null=True, blank=True,
help_text="Gallery description on gallery page")
slug = AutoSlugField(populate_from='name')
created = models.DateTimeField()
visable = models.BooleanField(default=False)
type = models.ForeignKey(Category, on_delete=models.CASCADE, null=True, blank=True)
image = models.ForeignKey('Media', on_delete=models.CASCADE)
album_images = models.ManyToManyField('Media', related_name="album_pictures")
class Media(models.Model):
timestamp = models.DateTimeField()
image = models.ImageField(upload_to="media")
order = models.IntegerField(default=0)
visable = models.BooleanField(default=True)
categories = models.ForeignKey(Category, on_delete=models.CASCADE, null=True, blank=True)
URLS (relevant)
path("gallery/", views.GalleryView, name="gallery"),
Views
def GalleryView(request):
if request.htmx:
slug = request.GET.get('slug')
pics = get_object_or_404(Albums, slug=slug)
context = {'pictures': Media.objects.filter(album_pictures=pics),
'description': Albums.objects.filter(slug=slug)}
return render(request, 'main/gallery-detail.html', context=context)
context = {'objects_list': Albums.objects.all()}
return render(request, 'main/gallery.html', context=context)
Gallery HTML {relevant code)
<div class="gallery-body">
{% for img in objects_list %}
<div class="item col-xs-6 col-sm-6 col-md-4">
<figure class="overlay"> <a hx-post="{{ request.path }}?slug={{ img.slug }}"
hx-target=".gallery-body"
hx-swap="outerHTML"
hx-push-url="/gallery/{{ img.slug }}"
hx-headers='{"X-CSRFToken": "{{ csrf_token }}"}'>
{% endfor %}
The partial that gets called showing the images within the galleries.
<button class="btn btn-primary"
hx-get="{% url 'main:gallery' %}"
hx-target=".gallery-body"
hx-push-url="/gallery"
hx-headers='{"X-CSRFToken": "{{ csrf_token }}"}'>
<h6>Back to Gallery page</h6></button></div>
I am building an ecommerce website with Django and having some difficulties to transfer data from the admin page to the database and then html. I am new to Django and I would love your help.
I added 7 "products" (class Product) via Django admin page.
models.py
from django.db import models
from django.contrib.auth.models import User
class Customer(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE, null=True, blank=True)
name = models.CharField(max_length=200, null=True)
email = models.CharField(max_length=200, null=True)
def __str__(self):
return self.name
class Product(models.Model):
name = models.CharField(max_length=200)
price = models.FloatField()
def __str__(self):
return self.name
class Order(models.Model):
customer = models.ForeignKey(Customer, on_delete=models.SET_NULL, null=True, blank=True)
date_ordered = models.DateTimeField(auto_now_add=True)
complete = models.BooleanField(default=False)
transaction_id = models.CharField(max_length=100, null=True)
def __str__(self):
return str(self.id)
class OrderItem(models.Model):
product = models.ForeignKey(Product, on_delete=models.SET_NULL, null=True)
order = models.ForeignKey(Order, on_delete=models.SET_NULL, null=True)
quantity = models.IntegerField(default=0, null=True, blank=True)
date_added = models.DateTimeField(auto_now_add=True)
class ShippingAddress(models.Model):
customer = models.ForeignKey(Customer, on_delete=models.SET_NULL, null=True)
order = models.ForeignKey(Order, on_delete=models.SET_NULL, null=True)
address = models.CharField(max_length=200, null=False)
city = models.CharField(max_length=100, null=False)
country = models.CharField(max_length=100, null=False)
postcode = models.CharField(max_length=100, null=False)
date_added = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.address
views.py
from django.shortcuts import render
from .models import *
def products(request):
products = Product.objects.all()
context = {'products':products}
return render(request, 'store/products.html')
def cart(request):
context = {}
return render(request, 'store/cart.html')
def checkout(request):
context = {}
return render(request, 'store/checkout.html')
def home(request):
context = {}
return render(request, 'store/home.html')
admin.py
from django.contrib import admin
from .models import *
admin.site.register(Customer)
admin.site.register(Product)
admin.site.register(Order)
admin.site.register(OrderItem)
admin.site.register(ShippingAddress)
In settings.py, the default database is sqlite3
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
}
}
Screen shot of Django admin page with products successfully added
I have done the migrations and the database db.sqlite3 exits in my project folder.
However, when I check the values of the table "store_product", it seems empty...
prompt
SQLite version 3.33.0 2020-08-14 13:23:32
Enter ".help" for usage hints.
sqlite> .width
sqlite> .mode markdown
sqlite> select * from store_product
...>
In my html page where I want to display the products, nothing displays ... The variable products is empty :
products.html
{% if products is defined %}
value of variable: {{ products }}
{% else %}
variable is not defined
{% endif %}
it displays nothing ...
Thanks a lot for your help.
You never pass the context to your view. It should be like:
def products(request):
products = Product.objects.all()
context = {'products':products}
return render(request, 'store/products.html', context)
Also that {% if products is defined %} would not make any sense. So simply render the products:
{% for product in products %}
Product: {{ product.name }}
Price: {{ product.price }}
{% empty %}
No products to display!
{% endfor %}
Your template code looks wrong - is defined is not python.
The following is sufficient:
{% if products %}
<ul>
{% for product in products %}
<li>{{ product.name }}: {{ product.price }}
{% endfor %}
</ul>
{% else %}
No products.
{% endif %}
The Django Admin shows exactly whatever is in its connected database, there is no cache.
If you cannot see the data in the sqlite client or your other view, this makes me suspect that you are not using the same database or that the sqlite lost the data in the meanwhile (deleting the file will recreate it the next time you start your local server, and the data will be lost).
You might want to start using the DB you are planning to use in production, to rule these issues out, and to be closer to your production setup when developing.
I have this web app, created with Django framework and I'm struggling with one particular issue. I would like to create formset with file attachment (Attachment is related to Document vie FK relationship), and I would like to provide url to mentioned file in frontend.
model.py
class Attachment(models.Model):
name = models.CharField(max_length=100, verbose_name='name')
file = models.FileField(upload_to='attachments', null=True,
verbose_name='file')
class Document(models.Model):
attachment = models.ForeignKey(
'Attachment', null=True, on_delete=models.CASCADE)
date = models.DateField(blank=True, null=True,)
title = models.CharField(max_length=250, null=True, blank=False)
def get_attachment_file(self):
return self.attachment.file.url
def get_attachment_filename(self):
return str(self.attachment.file)[12:]
form.py
class DocumentForm(forms.ModelForm):
class Meta:
model = Contract
fields = ('attachment', 'date', 'title', 'approved')
DocumentFormset = modelformset_factory(Document, form=DocumentForm, extra=0)
view.py
def documents(request):
... some logic and filtering, get doc_id
documents = Document.objects.filter(document=doc_id)
formset = DocumentFormset(queryset=documents)
return render(request, 'documents.html', {'formset': formset})
template: documents.html
{% for form in formset %}
<div class="form-group">
<label for="{{ form.attachment.id_for_label }}">Title</label>
{{ form.attachment}}
</div>
{% endfor %}
I have hard time to access file url in attachment object, in template engine I cant call get_attachment_file() function, form.attachment.file.url is empty.
Is there a way to get file url from attachment object?
Thank you.
I'm trying to show all the image correlated to a chapter.
I cannot figure out what is wrong, base on what I found online it should work, but no images are display.
Only the outer div is coming out on html source.
By debugging the template I also notice that the for loop is taking all the chapters in the DB, not only the chapter I selected.
I think I need to restrict the ChapDetail view query somehow.
Can someone advise me on this two issue?
model.py
def image_dir_path(instance, filename):
book = instance.chap.book.slug
chapter = instance.chap.slug
return os.path.join(book, chapter, str(uuid.uuid4().hex))
class Chapter(models.Model):
user = models.ForeignKey(
settings.AUTH_USER_MODEL,
on_delete=models.CASCADE,
default=settings.AUTH_USER_MODEL
)
book = models.ForeignKey(
Book,
related_name='chapters',
on_delete=models.CASCADE,
default=''
)
title = models.CharField(max_length=130, unique=True)
slug = models.SlugField(max_length=150, blank=True)
created_at = models.DateField(auto_now_add=True)
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse('chap_detail')
class ShowImages(models.Model):
chapter =models.ForeignKey(
Chapter,
on_delete=models.CASCADE,
default='',
related_name="pics"
)
picture = models.FileField(upload_to=image_dir_path, default='')
def __str__(self):
return self.picture.name
view.py
class ChapDetail(generic.ListView):
model = Chapter
template_name = 'chapters/chapter_detail.html'
urls.py
app_name = 'chapters'
urlpatterns = [
path('<str:book>', views.BookChaps.as_view(), name='chap_list'),
path('<str:book>/<str:slug>/', views.ChapDetail.as_view(), name='chap_detail'), # both slug fields
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
settings.py
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
template
<div style="padding-top: 10px; display: block;">
{% for i in chapter.picture_set.all %}
<div>
<img src="{{ i.picture.url }}" alt="Not found">
</div>
{% endfor %}
</div>
media folder:
For restricting you query you can use the methode .filter() Filter Django Docs
It would be something along the line Chapter.objects.filter(id=id).
You can get the id (or other filter param) from you path params in the url.
For the missing pictures, are you sure your MEDIA URL is set correct in the settings?
I have the following model in my Django project:
from django.contrib.auth.models import User
class Project(models.Model):
project_title = models.CharField(max_length=200)
project_description = models.CharField(max_length=200, default="")
created_date = models.DateTimeField('date created')
owner = models.ForeignKey(User)
def __str__(self):
return self.project_title
This view uses the Project model as follows:
class ProjectView(generic.edit.UpdateView):
model = Project
fields = ['project_title','project_description']
template_name = 'steps/project.html'
success_url = reverse_lazy('steps:index')
My question is how can I bring the User's fields into my ProjectView so I can then use them in templates? In particular, I would like to display the logged-in user's name and email.
user information placed on request, not on views. So you can write in template {{user.username}}, or {{user.email}}. and you'll get it. Of course if user.is_authenticated
in your template write:
{% if request.user.is_authenticated %}
{{ request.user.username }}
{{ request.user.email }}
{% endif %}