Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django: Python variable data as background image

Details and Problem:

I am making a website which uses steam's social authentication and API, it saves users data in the database, and makes the session cookie that contains two main data, username and logged in cookies.

The data which the variable contains is the url to the image, which leads me to the problem, i want to show the picture of user on the index page, but css static file would not allow me to use the variable.

so i tried some other options:

  1. Using HTML <style> tag:
    <a class="profile_picture" href="/profile" style="background-image: url({{ picture }})"></a> # would not work, as it takes every character as string.

  2. Using HTML <img> tag:

    <img class="profilepicture" src="{{ picture }}"></img> # same problem here, takes every character as unicode string.

Question:

Is there any other way to do this with the setup i have? ( Django, CSS, HTML, Python ), i am trying to do this without installing something extra, i have seen sass, but is there still any other possible way?

Can i use <style> or <img> tag to take variable url as background image?, if so how?

like image 300
ShellRox Avatar asked Dec 09 '25 05:12

ShellRox


1 Answers

It's hard to answer this question without all of the details, but the first issue that comes to mind is that you are most likely referencing your context variable "picture" incorrectly. Again, I'm not sure by your question what exactly you are doing, but perhaps this example will help:

If I have a model named "Person" and that model has 2 fields, "name" and "picture". In my views.py, if I had a function called main:

  def main(request):
      persons = Person.objects.all()
      return render(request, index.html, {"persons":persons } )

This function creates an context variables named persons that will be available in your index.html file. Obviously this is a very loose example, but serves to guide you with the basics. So in your index.html template, you would reference the picture field by doing this:

  {% for person in persons %}
      {{ person.picture }}
  {% endfor %}

Hope that helps.

like image 122
dave4jr Avatar answered Dec 10 '25 18:12

dave4jr



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!