django: delete pevious photo while adding a new photo - python

I am developing a user profile where users can add profile picture. Adding the picture is working fine but when I want to add a new photo, old photo doesn't go away. My django version is 3.1 and I have tried django-smartfields but still it is not working. Can anyone help?
views.py
from smartfields import fields
class Profile_Pic(models.Model):
user = models.ForeignKey(User, default='', null=False, on_delete=models.CASCADE, related_name='userPic')
profile_pic = fields.ImageField(upload_to='media', default='admin_car/static/images/img_avatar.png', blank=True)
class Meta:
db_table = 'Profile_Pic'
user_image.html
{% extends 'datas/base.html' %}
{% block content %}
{% load static %}
<h1 class="text-center" style="color: white">Add Profile Picture</h1>
<br><br>
<div class= "col-md-6.offset-md-3">
<form method="POST" enctype="multipart/form-data">
{% csrf_token %}
{% if form.errors %}
<div class="alert alert-warning alert-dismissable" role="alert">
<button class="close" data-dismiss="alert">
<small><sup>x</sup></small>
</button>
<p>Data Error, Please Check Again.....</p>
{% for field in form %}
{% if field.errors %}
{{ field.errors }}
{% endif %}
{% endfor %}
</div>
{% endif %}
{{ form.as_p }}
<input type="submit" value="Save" class="btn btn-primary">
</form>
</div>
{% endblock %}

If your image is being updated in your static/image folder but not in the browser, this is because the browsers cache your static files and they don’t change readily. But there is work around you can use ‘whitenoise’
Follow these steps.
Clear your browser cache to erase already existing cache.
pip3 install whitenoise
Then add the following to the end of your settings.py
if DEBUG:
MIDDLEWARE = [
'whitenoise.middleware.WhiteNoiseMiddleware',
] + MIDDLEWARE
INSTALLED_APPS = [
'whitenoise.runserver_nostatic',
] + INSTALLED_APPS
Then rerun your server the static files won’t be cached anymore

Related

How To Provide A Class To Fields In A Django Template?

I was working a project on mine, in which I needed to provide a class to a field in form which is a input box, but don't know how to do so.
My Template:
{% extends 'diary/base.html' %}
{% block title %}Register{% endblock title %}
{% block content %}
{% load staticfiles %}
<link rel= "stylesheet" type= "text/css" href = "{% static 'users/register.css' %}">
<div id="login-box">
<div class="left-box">
<h1>Register</h1>
<form action="{% url 'register' %}" method="post">
{% csrf_token %}
{% for non_field_error in form.non_field_errors %}
<p>{{ non_field_error }}</p>
{% endfor %}
{% for field in form %}
{{ field }}
{% for error in field.errors %}
<p>{{ error }}</p>
{% endfor %}
{% endfor %}
<input type="submit" value="SIGN UP" name="signup-button" class="signup-btn">
</form>
</div>
<div class="right-box">
</div>
</div>
{% endblock content %}
In this specific part:
{% for field in form %}
{{ field }}
{% for error in field.errors %}
I want to provide a class to {{ field }}.
I tried this:
{{ field(class="txtb") }}
This is how I use to provide a class in Flask, but in Django this didn't worked.
Any Help Would Be Appreciated!
django-widget-tweaks
I'm using django-widget-tweaks module for set HTML attribute in templates.
installation
install module using pip install django-widget-tweaks
add to INSTALLED_APPS in settings.py
INSTALLED_APPS = [
...
'widget_tweaks',
...
]
{% load widget_tweaks %} in templates file
usage
in templates code:
{% load widget_tweaks %}
...
{% for field in form %}
{% render_field field class="txtb" %}
...
in HTML, looks like this:
<input class="txtb" ... ...>
reference django-widget-tweaks github page for more information.
manually
Detailed description is in here
forms.py:
class YourForm(forms.ModelForm):
modelfield = forms.CharField(
...,
widget=forms.TextInput(
attrs={
'class': 'txtb'
}
}
)
class Meta:
model = ...
fields = ...
And I have a lot of information about django to simpleisbetterthancomplex.com
django-widget-tweaks also learned here

Django - wagtail Inline panel CSS edits

I am using wagtail on django and creating a page where I will create questions and allow students to answer it by typing in the input box. I am using inline field where the wagtail gives me the option to choose various input option like(singleline, multiline, radio button etc). For my questions, I am choosing a singleline option. The problem I am facing is with the text box, the text box is too small, is there a way to increase the size(width) of the text box.
model.py
class QuestionPage(AbstractForm):
intro = RichTextField(blank=True)
thank_you_text = RichTextField(blank=True)
points_for_this_activity = models.IntegerField(blank=True, default=0)
content_panels = AbstractEmailForm.content_panels + [
FieldPanel('intro', classname="full"),
InlinePanel('form_fields', label="Create your question"),
FieldPanel('points_for_this_activity', classname="title"),
FieldPanel('thank_you_text', classname="full"),
]
question.html
<div class ="container">
<h1>{{ page.title }}</h1>
{% if user.is_authenticated and user.is_active or request.is_preview %}
{% if form %}
<div>{{ page.intro|richtext }}</div>
<form action="{% pageurl page %}" method="POST">
{% csrf_token %}
{{ form.as_p }}
<input class="btn-md btn-primary" type="submit">
</form>
{% else %}
<div>You have already answered this. Go to the next question.</div>
{% endif %}
{% else %}
<div>To fill in the form, you should log in.</div>
{% endif %}
{% endblock %}
</div>

i have deployed Django project in Heroku.where users can upload images shows up for some hours after some hours images gets dont showup in screen

i have deployed my project in Heroku.what happens is i have form where users can upload files(images) which is reflected back to pages after being uploaded problem is those uploaded images shows on page for some hours and then images gets dont showup in screen after some hours. but again wen some users fill up the form a upload the images ,it shows up in the screen but rest of the previously uploaded images dont show up .in this newly uploaded image also disappears after some hour . also every time i do git push heruko masters those images disappears.
you can visit the site(http://productpanditapp.herokuapp.com/)
settings.py
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.0/howto/static-files/
STATICFILES_DIRS = [
os.path.join(BASE_DIR,'producthunt/static/')
]
STATIC_ROOT = os.path.join(BASE_DIR,'static')
STATIC_URL = '/static/'
MEDIA_ROOT = os.path.join(BASE_DIR,'media')
MEDIA_URL = '/media/'
models.py
from django.db import models
from django.contrib.auth.models import User
class Product(models.Model):
title = models.CharField(max_length=255)
pub_date = models.DateTimeField()
body = models.TextField()
image = models.ImageField(upload_to='images/')
icon = models.ImageField(upload_to='images/')
url = models.TextField()
votes_total = models.IntegerField(default=1)
hunter = models.ForeignKey(User,on_delete=models.CASCADE)
def __str__(self):
return self.title
def summary(self):
return self.body[:100]
def short_pub_date(self):
return self.pub_date.strftime('%b %e %Y')
views.py
def home(request):
products = Product.objects.all().order_by("-pub_date")
query = request.GET.get("q")
if query:
products= products.filter(Q(title__icontains=query)|
Q(body__icontains=query)|
Q(hunter__username__icontains=query)).distinct()
paginator = Paginator(products, 5) # Show 25 contacts per page
page = request.GET.get('page')
list = paginator.get_page(page)
return render(request,'products/home.html',{'product':list})
home.html
{% extends 'base.html' %}
{% block content %}
{% if messages %}
<br>
<div class="container">
{% for message in messages %}
<p{% if message.tags %} class="alert alert-danger"{% endif %}>{{ message }}</p>
{% endfor %}
{% endif %}
</div>
<br>
<div class="container">
<form class="form-inline" method="GET" action="">
{% csrf_token %}
<input class="form-control mr-sm-2" type="text" placeholder="Search Product" name='q' value="{{request.GET.q}}">
<button class="btn btn-outline-primary" type="submit">Search</button>
</form>
<br>
</div>
{% for pro in product %}
<div class="container pt-2">
<div class="jumbotron p-1">
<div class="row pt-2">
<div class="col-2" onclick="window.location='{% url 'detail' pro.id %}';" style="cursor:pointer;">
<img src="{{ pro.icon.url }}" height=100 width=100 class="rounded float-left"/> #images dont show up after some hours from file is upload time
</div>
<div class="col-4" onclick="window.location='{% url 'detail' pro.id %}';" style="cursor:pointer;">
<h1>{{ pro.title }}</h1>
<p>{{ pro.summary }}</p>
</div>
<div class="col-4" onclick="window.location='{% url 'detail' pro.id %}';" style="cursor:pointer;">
<p><strong>Published on :</strong> {{pro.pub_date}}</p>
<p><strong>Hunter :</strong> {{pro.hunter}}</p>
</div>
<div class="col-2">
<button class="btn btn-success btn-block"><span class="oi oi-thumb-up"></span></span> Upvote {{pro.votes_total}}</button>
</div>
</div>
<form id="vote{{pro.id}}" action="{% url 'upvote' pro.id %}" method="POST">
{% csrf_token %}
<input type="hidden">
</form>
</div>
</div>
{% endfor %}
<div class="pagination">
<span class="step-links">
{% if product.has_previous %}
« first
previous
{% endif %}
<span class="current">
Page {{ product.number }} of {{ product.paginator.num_pages }}.
</span>
{% if product.has_next %}
next
last »
{% endif %}
</span>
</div>
{% endblock %}
any help will be greatly appreciated !
Thanks in advance.!
pictures of the pages where i m facing a problem,please click the link!
forms where images are uploaded
main pages where images gets disappeared after some hours of being uploaded

Django user selects multiple images from gallery and saves it as strings in database backend

Im trying to create a form where the user selects from a gallery of images and it saves it to the database. The code below currently renders some radio buttons in the html output. Is there anyway I can change these to images i have saved in a static directory so the user can click on images instead? Would be great if I could change what it saves in the database to what I needed instead of image urls as well. Theres lots of documentation on uploading images but not much I could find on selecting images. Im using django 1.9.7 and python 3.5
models.py
client_choices = (('client1', 'Client 1'),
('client2', 'Client 2'),
('client3', 'Client 3'),
('client4', 'Client 4'),
('client5', 'Client 5'))
class ClientSelect(models.Model):
client = MultiSelectField(choices=client_choices)
forms.py
from app.models import ClientSelect
class ClientSelectForm(forms.ModelForm):
class Meta:
model = ClientSelect
fields = '__all__'
views.py
class FormWizard(SessionWizardView):
template_name = "app/clientchoices.html"
#define what the wizard does when its finished collecting information
def done(self, form_list, **kwargs):
form_data = process_form_data(form_list)
return render_to_response('app/about.html', {'form_data': form_data})
urls.py
url(r'^clientchoices$', FormWizard.as_view([ClientSelectForm]) , name='clientchoices'),
clientchoices.html
{% load staticfiles %}
{% block content %}
<section class="content">
<div class="container">
<div class="fit-form-wrapper">
<h2>Client Choices</h2>
<p>Step {{ wizard.steps.step1 }} of {{ wizard.steps.count }}</p>
{% for field in form %}
{{field.error}}
{% endfor %}
<form action="{% url 'clientchoices' %}" method="post">{% csrf_token %}
<table>
{{ wizard.management_form }}
{% if wizard.form.forms %}
{{ wizard.form.management_form }}
{% for form in wizard.form.forms %}
{{ form }}
{% endfor %}
{% else %}
{{ wizard.form }}
{% endif %}
</table>
{% if wizard.steps.prev %}
<button class="btn btn-brand" name="wizard_goto_step" type="submit" value="{{ wizard.steps.first }}">"First Step"</button>
<button class="btn btn-brand" name="wizard_goto_step" type="submit" value="{{ wizard.steps.prev }}">"Previous Step"</button>
{% endif %}
<input class="btn btn-brand" type="submit" value="Submit" />
</form>
</div>
</div>
</section>
{% endblock %}
Any help is appreciated thank you

django_markdown doesn't work on my template

I'm using the module django markdown and it doesn't work on my template, but it does on django admin
My Django version is 1.8.5 and I'm using the latest version of django markdown
I followed the steps showed in the repository's README https://github.com/klen/django_markdown
setup ( add django_markdown in settings and url are both ok )
in model.py ( migrate is ok )
from django_markdown.models import MarkdownField
class MyModel(models.Model):
description = MarkdownField()
python manage.py collectstatic is ok
forms.py
class BidForm(BaseBidForm, forms.ModelForm):
class Meta:
model = Bid
fields = ('name', 'description')
description = forms.CharField(widget=MarkdownWidget())
admin.py
#admin.register(models.Bid)
class BidAdmin(admin.ModelAdmin):
formfield_overrides = {MarkdownField: {'widget': AdminMarkdownWidget}}
template .html
{% load django_markdown %}
{% for field in form %}
{% if field.html_name == 'description' %}
<div class="col-md-7">
<div class="form-group">
<label for="{{ form.description.html_name }}">{% trans "Descripción" %} <span class="red">*</span> <small class="required">(obligatorio)</small></label><br>
<textarea id="new" class="form-control {{ field.errors|yesno:'error,' }}" rows="3"
name='{{ form.description.html_name }}'
placeholder="{% trans "ejemplos" %}"
value="{% if form.description.value %}{{ form.description.value }}{% endif %}"></textarea>
{% markdown_editor "#new" %}
{% markdown_media %}
</div>
</div>
{% endif %}
{% endfor %}

Categories

Resources