Django Uploading Files - python

I have a dashboard where you upload files and can see the files you uploaded. Strangely enough, when you go to upload a second file, it uploads but gives the error: IntegrityError at /dashboard/ column client_id is not unique I'm not sure why. My database is fresh and clean. What would cause this? The first file uploads and displays correctly redirecting you to the dashboard. The second file uploads, but doesn't display in the file list and displays that error. Any ideas why this is occurring or how to fix this error? I'm really stuck here so any help would save me big time.
Here is the view:
#login_required(login_url='/dashboard-login/')
def dashboard(request):
current_user = request.user
current_client = request.user.client
files = ClientUpload.objects.filter(client=current_client)
if request.method == 'POST':
form = UploadFileForm(request.POST, request.FILES)
if form.is_valid():
new_file = ClientUpload(client=current_client, file_upload = request.FILES['file_upload'])
new_file.save()
return HttpResponsePermanentRedirect('/dashboard/')
else:
form = UploadFileForm()
data = {'form': form, 'client': current_client, 'files': files}
return render_to_response('dashboard.html', data, context_instance=RequestContext(request))
The models:
#python_2_unicode_compatible
class Client(models.Model):
user = models.OneToOneField(User)
company = models.CharField(max_length=100)
def __str__(self):
return self.company
class Meta:
verbose_name_plural = _("Clients")
verbose_name = _("Client")
permissions = (
("can_upload", _("Can upload files.")),
("can_access_uploads", _("Can access upload dashboard.")),
("is_client", _("Is a client.")),
)
def generate_filename(self, filename):
name = "uploads/%s/%s" % (self.client.company, filename)
return name
#python_2_unicode_compatible
class ClientUpload(models.Model):
client = models.OneToOneField(Client)
created_at = models.DateTimeField(auto_now_add=True)
file_upload = models.FileField(upload_to=generate_filename)
def __str__(self):
return self.client.company
class Meta:
verbose_name_plural = _("Client Uploads")
verbose_name = _("Client Upload")
The form:
class UploadFileForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
self.helper = FormHelper()
self.helper.add_input(Submit(_('submit'), _('Submit')))
super(UploadFileForm, self).__init__(*args, **kwargs)
class Meta:
model = ClientUpload
fields = ('file_upload',)
And lastly, the templates:
Upload file:
{% load i18n %}
{% load crispy_forms_tags %}
{% crispy form %}
File list:
{% load i18n %}
<table class="table">
<tr>
<th>{% blocktrans %}Filename{% endblocktrans %}</th>
<th>{% blocktrans %}Size{% endblocktrans %}</th>
<th>{% blocktrans %}Upload Time{% endblocktrans %}</th>
</tr>
{% for file in files %}
{% with uploaded_file=file.file_upload %}
<tr>
<th><a href='{{ uploaded_file.url }}'>{{ uploaded_file.name }}</a></th>
<th>{{ uploaded_file.size }}</th>
<th>Uploaded At</th>
{% endwith %}
{% endfor %}
</tr>
</table>
And the one that ties them together, dashboard:
{% extends "base.html" %}
{% load i18n %}
{% block title %}Shenkan & Associates - {% trans 'Dashboard' %}{% endblock title %}
{% block css %}
{{ block.super }}
{% endblock css %}
{% block extra_css %}
{% endblock extra_css %}
{% block ie_shim %}
{{ block.super }}
{% endblock ie_shim %}
{% block header %}
{{ block.super }}
{% endblock header %}
{% block slider %}
{% endblock slider %}
{% block page_header %}{% endblock page_header %}
{% block content %}
<!--=== Content ===-->
{% trans 'Logout' %}
<div class="container content-md">
{% include "upload_file.html" %}
</div>
<div class="container content-md">
{% include "file_list.html" %}
</div>
<!--=== End Content ===-->
{% endblock content %}
{% block footer %}
{{ block.super }}
{% endblock footer %}
{% block js %}
{{ block.super }}
{% endblock js %}
{% block ie_js %}
{{ block.super }}
{% endblock ie_js %}
{% block extra_js %}
{% endblock extra_js %}
You don't need to see base.html obviously.
If someone could help me solve this mystery it would help a ton as I am having tons of problems with this and have been stuck for days.
Thanks a bunch.

I think you should use "get_or_create" in the views.
I hope this can help: get_or_create throws Integrity Error

Related

Django Please help me place a checkbox and a mail box with a send button on the html page

One of functionality in my training project:
subscribe to the news by check-box and e-mail.
Send newsletter daily.
The user can unsubscribe from the mailing list in his profile by unchecking the checkbox.
It so happened that first I set up a daily newsletter for users who have booleanfield = true.
For it I marked the checkboxes in the admin panel. It works.
Now it is necessary to add the checkbox and the mail field to the news page.
I'm stuck on the simplest. Tired and confused.
Please help me place a checkbox and a mail box with a send button on the news page
models.py
class Profile(models.Model):
user = models.OneToOneField(settings.AUTH_USER_MODEL,
on_delete=models.CASCADE)
hr = models.BooleanField(default=False)
subscribed_for_mailings = models.BooleanField(default=False)
subscription_email = models.EmailField(default="")
def __str__(self):
return str(self.user)
Forms.py
class MailingForm(forms.ModelForm):
class Meta:
model = models.Profile
fields = ('subscription_email', 'subscribed_for_mailings', )
widgets = {
'subscription_email': forms.EmailInput(attrs={"placeholder": "Your Email..."}),
'subscribed_for_mailings': forms.CheckboxInput,
}
views.py
def all_news(request):
today = date.today()
today_news = models.TopNews.objects.filter(created__gte=today)
return render(request, "news.html",
{'today_news': today_news})
def mailing_news(request):
if request.method == 'POST':
mailing_form = forms.MailingForm(request.POST)
if mailing_form.is_valid():
mailing_form.save()
return HttpResponse('You will receive news by mail')
else:
mailing_form = forms.MailingForm()
return render(request, "news.html", {'mailing_form': mailing_form})
urls.py
...
path('news/', views.all_news, name='all_news'),
...
news.html
{% extends 'base.html' %}
{% block title %}
News
{% endblock %}
{% block body %}
<h1>Last news</h1>
{% for news in today_news%}
<h3>{{ news.title }}</h3>
Read this news
<p>
{{ news.created }}
</p>
<hr>
{% endfor %}
<h4>I want to receive news by mail</h4>
<form action="." method="post">
{{ mailing_form.as_p }}
{% csrf_token %}
<label>
<input type="submit" value="Subscribe">
</label>
</form>
{% endblock %}
The page displays a list of news and only the "send" button. There is no check-box and a field for mail
enter image description here
Finally I realized this functionality in a different way:
forms.py
class MailingForm(forms.ModelForm):
class Meta:
model = models.Profile
fields = ('subscribed_for_mailings', 'subscription_email', )
views.py
#login_required
def mailing_news(request):
if request.method == "POST":
mailing_form = forms.MailingForm(request.POST,
instance=request.user.profile,
)
if mailing_form.is_valid():
mailing_news = mailing_form.save(commit=False)
mailing_news.subscribed_for_mailings = mailing_news.subscribed_for_mailings
mailing_news.subscription_email = mailing_news.subscription_email
mailing_news.save()
return render(request, "subscribe_complete.html",
{"mailing_news": mailing_news})
else:
mailing_form = forms.MailingForm()
return render(request, 'subscribe.html', {"mailing_form": mailing_form})
news.html
{% extends 'base.html' %}
{% block title %}
News
{% endblock %}
{% block body %}
<h1>Last news</h1> {{ news.created }}
{% for news in today_news%}
<h3>{{ news.title }}</h3>
Read this news
<hr>
{% endfor %}
I want to receive news by mail
{% endblock %}
urls.py
...
path('subscribe/', views.mailing_news, name='subscribe')
...
news.html
{% extends 'base.html' %}
{% block title %}
News
{% endblock %}
{% block body %}
<h1>Last news</h1> {{ news.created }}
{% for news in today_news%}
<h3>{{ news.title }}</h3>
Read this news
<hr>
{% endfor %}
I want to receive news by mail
{% endblock %}
subscribe.html
{% extends 'base.html' %}
{% block title %}
Subscribe
{% endblock %}
{% block body %}
<form action="." method="post" enctype="multipart/form-data">
{% csrf_token %}
{{ mailing_news.as_p }}
{% if user.profile.subscribed_for_mailings is True %}
<input type="checkbox" name="subscribed_for_mailings" id="id_subscribed_for_mailings" checked="">
If you don't want to receive emails anymore, uncheck
<br>
Subscription email: <input type="email" name="subscription_email" value={{ user.profile.subscription_email }} class="vTextField" maxlength="254" id="id_subscription_email">
{% else %}
<label>
<input type="checkbox" name="subscribed_for_mailings" id="id_subscribed_for_mailings">
I want to subscribe for mailing news
</label>
<p><label>
Send news on my email:
<input type="email" name="subscription_email" class="vTextField" maxlength="254" id="id_subscription_email">
</label></p>
{% endif %}
<p><input type="submit" value="Update"></p>
</form>
{% endblock %}
subscribe_complete.html
{% extends 'base.html' %}
{% block title %}
Subscribing complete
{% endblock %}
{% block body %}
<h3>Hi {{ user.username }}</h3>
Thanks for subscribing.
You will receive daily news by email: {{ user.profile.subscription_email }}
{% endblock %}
you need to change subscribed_for_mailings in mailing news, like this
def mailing_news(request):
if request.method == 'POST':
mailing_form = forms.MailingForm(request.POST)
if mailing_form.is_valid():
profile = mailing_form.save(commit=False) ####
profile.subscribed_for_mailings = mailing_form.cleaned_data.get('subscribed_for_mailings') ####
profile.subscription_email = mailing_form.cleaned_data.get('subscription_email') ####
profile.save() #### new_line
return HttpResponse('You will receive news by mail')
else:
mailing_form = forms.MailingForm()
return render(request, "news.html", {'mailing_form': mailing_form})
you can change in cleaned_data.get('....')

self.assertContains fails; Couldn't find *word* in response

I'm having difficulty completely rendering the template of TopicsPage. It's suppose to render sub_heading.html which extends listing.html (both templates reside in the same templates folder). The test passes the self.assertTemplateUsed() assertion.
However an AssertionError is raised at the point of:
self.assertContains(response, "Looking for more?")
AssertionError: False is not true : Couldn't find 'Looking for more?' in response
How can I get the sub_heading.html content to render for the test to pass when the template is being used already? I put the implementation for GET method as pass intentionally just to show how I'm subclassing the View.
test_views.py
class TestTopicsPage__002(TestCase):
'''Verify that a topic and associated information is displayed
on the main page once the topic is created'''
#classmethod
def setUpTestData(cls):
user = User.objects.create_user("TestUser")
python_tag = Tag.objects.create(name="Python")
js_tag = Tag.objects.create(name="JavaScript")
content = {
'heading': "Test Title",
'text': "Mock text content",
'posted': datetime.datetime.now()
}
cls.topic = Topic(**content)
cls.topic.author = user
cls.topic.save()
cls.topic.tags.add(python_tag, js_tag)
def test_topics_main_page_rendered_topics(self):
response = self.client.get(
reverse("listing")
)
self.assertEqual(response.status_code, 200)
self.assertTemplateUsed(response, "topics/sub_listing.html")
self.assertContains(response, "Looking for more?")
views.py
class AbstractListingPage(TemplateView):
template_name = "topics/sub_listing.html"
extra_content = {
'query_links': ['interesting', 'hot', 'week', 'month']
}
def get_context_data(self):
context = super().get_context_data()
context['topics'] = Topic.objects.all()
context['search_form'] = SearchForm()
context['login_form'] = UserLoginForm
return context
def post(self, request):
context = self.get_context_data()
form = context['login_form'](data=request.POST)
if form.is_valid():
resolver = resolve(request.path)
login(request, form.get_user())
if resolver.namespace:
url = f"{resolver.namespace}:{resolver.url_name}"
else:
url = resolver.url_name
return HttpResponseRedirect(
reverse(url)
)
return self.render_to_response(context)
class TopicsPage(AbstractListingPage):
def get(self, request):
pass
listing.html
{% extends 'index.html' %}
{% load static %}
{% block content %}
{% if not topics %}
<h1 class="topics_placeholder">"Whoops...no topics are being talked about"</h1>
<h2>Join the community...NOW!</h2>
{% else %}
{% for topic in topics %}
<ul class="topic_stats">
<li>{{ topic.answers.count }} answers</li>
<li>{{ topic.likes }} likes</li>
<li>{{ topic.views }} views</li>
</ul>
<div class="topic_wrapper">
<h1>{{ topic }}</h1>
<ul>
{% for tag in topic.tags.all %}
<li>{{ tag }}</li>
{% endfor %}
</ul>
<p>{{ topic.posted }}</p>
<p>{{ topic.author }}</P>
</div>
{% endfor %}
{% endif %}
{% endblock content %}
{% block page_branch %}
{% endblock %}
<div class="question-header">
<button class="flex_item_btn button_widget red" type="button">
Ask Question
</button>
</div>
sub_listing.html
{% extends 'topics/listing.html' %}
{% load static %}
{% block page_branch %}
<h2>Looking for more? Browse the complete list of questions
or popular tags</h2>
{% endblock %}
The content at the bottom of listing.html is orphaned, not existing inside a block present in the parent template.
{% block page_branch %}
{% endblock %}
<div class="question-header">
<button class="flex_item_btn button_widget red" type="button">
Ask Question
</button>
</div>
Since listing.html extends index.html, it can only override blocks that exist in index.html. The above content must be put inside {% block content %} to be rendered at all. Then sub_listing.html's use of {% block page_branch %} will be rendered.

The 'Thumbnail' attribute has no file associated with it. Django {% if %} {% else%} {% endif %}

The 'Thumbnail' attribute has no file associated with it.
I have tried Django {% if %} {% else %} {% endif %} in my HTML list and it works on the page, but when I do the same for a detailview HTML it doesn't work and returns "The 'Thumbnail' attribute has no file associated with it."
** Models.py **
class Article(models.Model):
Title = models.CharField(max_length=150)
Thumbnail = models.ImageField(blank=True, null=True)
Author = models.ForeignKey(Author, on_delete=models.CASCADE)
Content = QuillField()
Date = models.DateField(auto_now_add=True)
slug = AutoSlugField(populate_from='Title')
** Views.py**
class ArticlesDetailView(DetailView):
model = Article
template_name = 'articles_app/articles_detail.html'
def get_context_data(self, **kwargs):
latest = Article.objects.order_by('-id')[0:3]
context = super().get_context_data(**kwargs)
context['latest'] = latest
return context
** HTML - List (articles_list.html) ** It works perfectly fine here!!!
<img src=" {% if articles.Thumbnail %}
{{ articles.Thumbnail.url }}
{% else %}
{% static 'img/add-ons/article_thumbnail_default.jpg' %}
{% endif %} " alt="..." class="card-img-top">
** HTML - Detail (articles_detail.html) ** It doesn't work here.
{% for obj in latest %}
<img src="{% if obj.Thumbnail %}
{{ obj.Thumbnail.url }}
{% else %}
{% static 'img/add-ons/article_thumbnail_default.jpg' %}
{% endif %} " alt="..." class="card-img-top">
{% endfor %}
What am I doing wrong? Please help!
try object.Thumbnail instead of obj.Thumbnail, I think that will solve your problem.

Django extends not working

I have a problem with execute html view. I have base.html which do not showing the child views from another files. Can anybody help me what I doing wrong? Here are my files:
models.py
from django.db import models
from django.utils import timezone
class Kategorie(models.Model):
glowna = models.CharField(max_length=150, verbose_name='Kategoria')
class Meta:
verbose_name='Kategoria'
verbose_name_plural='Kategorie'
def __str__(self):
return self.glowna
class Witryna(models.Model):
nazwa = models.CharField(default="", max_length=150, verbose_name = 'Nazwa strony')
adres_www = models.CharField(max_length=70, verbose_name='Adres www')
slug = models.SlugField(max_length=250, verbose_name='Przyjazny adres url')
email = models.CharField(max_length=100, verbose_name='Adres e-mail')
text = models.TextField(max_length=3000, verbose_name='Opis strony')
kategoria = models.ForeignKey(Kategorie, verbose_name='Kategoria')
data_publikacji = models.DateTimeField(blank=True, null=True, verbose_name='Data publikacji')
class Meta:
verbose_name='Strona www'
verbose_name_plural = 'Strony www'
def publikacja(self):
self.data_publikacji=timezone.now()
self.save()
def __str__(self):
return self.nazwa
urls.py
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^strony$', views.widok_strony, name='widok_strony'),
url(r'^$', views.widok_kategorii, name='widok_kategorii'),
]
views.py
from django.shortcuts import render
from .models import Witryna, Kategorie
from django.utils import timezone
#from django.db.models import Count
def widok_strony(request):
firmy = Witryna.objects.filter(data_publikacji__lte=timezone.now()).order_by('data_publikacji')
return render(request, 'firmy/widok_strony.html', {'firmy': firmy})
def widok_kategorii(request):
kategorie = Kategorie.objects.all()
wpisy_kat = Kategorie.objects.count()
return render(request, 'firmy/widok_kategorii.html', {'kategorie': kategorie, 'wpisy_kat': wpisy_kat})
widok_kategorii.html
{% extends 'firmy/base.html' %}
{% block kategorie %}
{% for kategoria in kategorie %}
<table>
<tr>
<th>
{{ kategoria.glowna|linebreaksbr }} ({{ wpisy_kat }})
</th>
</tr>
</table>
{% endfor %}
{% endblock kategorie%}
widok_strony.html
{% extends 'firmy/base.html' %}
{% block firmy %}
{% for firma in firmy %}
<div>
<img src="http://free.pagepeeker.com/v2/thumbs.php?size=s&url={{ firma.adres_www }}"/>
{{ firma.nazwa }}<p>
</div>
{% endfor %}
{% endblock %}
base.html
{% include 'firmy/header.html' %}
<html>
<body>
<h4>Ostatnio dodane</h4>
{% block firmy %}
{% endblock %}
<h4>Kategorie</h4>
{% block kategorie %}
{% endblock %}
</body>
{% include 'firmy/footer.html' %}
</html>
When I try to run localhost:8000 the base.html showing me only the view from widok_kategorii.html file.Of course when I change the url to localhost:8000/strony that page is loading perfectly. But I want to have this two html files on the one page base.html
Have you tried renaming your blocks so that they do not overlap with the names of arguments you are passing through view.py.
I would try the following:
widok_kategorii.html
{% extends 'firmy/base.html' %}
{% block content_kat %}
{% for kategoria in kategorie %}
<table>
<tr>
<th>
{{ kategoria.glowna|linebreaksbr }} ({{ wpisy_kat }})
</th>
</tr>
</table>
{% endfor %}
{% endblock %}
widok_strony.html
{% extends 'firmy/base.html' %}
{% block content_firm %}
{% for firma in firmy %}
<div>
<img src="http://free.pagepeeker.com/v2/thumbs.php?size=s&url={{ firma.adres_www }}"/>
{{ firma.nazwa }}<p>
</div>
{% endfor %}
{% endblock %}
base.html
{% include 'firmy/header.html' %}
<html>
<body>
<h4>Ostatnio dodane</h4>
{% block content_firm %}
{% endblock %}
<h4>Kategorie</h4>
{% block content_kat %}
{% endblock %}
</body>
{% include 'firmy/footer.html' %}
</html>
Realize that you will not get both content on the same page at one instance. If you would like to have both content on the same page then you need to combine the views and htmls.
I would do the following:
views.py
def widok_strony_kategorii(request):
firmy = Witryna.objects.filter(data_publikacji__lte=timezone.now()).order_by('data_publikacji')
kategorie = Kategorie.objects.all()
wpisy_kat = Kategorie.objects.count()
return render(request, 'firmy/widok_strony_kategorii.html', {'firmy': firmy,'kategorie': kategorie, 'wpisy_kat': wpisy_kat})
firmy/widok_strony_kategorii.html
{% extends 'firmy/base.html' %}
{% block content_kat %}
{% for kategoria in kategorie %}
<table>
<tr>
<th>
{{ kategoria.glowna|linebreaksbr }} ({{ wpisy_kat }})
</th>
</tr>
</table>
{% endfor %}
{% endblock %}
{% extends 'firmy/base.html' %}
{% block content_firm %}
{% for firma in firmy %}
<div>
<img src="http://free.pagepeeker.com/v2/thumbs.php?size=s&url={{ firma.adres_www }}"/>
{{ firma.nazwa }}<p>
</div>
{% endfor %}
{% endblock %}
firmy/base.html
<<Same as the edited one above>>

Something like publish notes in a webpage

I'm building a site where I publish a notice and it appear in one webpage but my code dosen't return the objects. I post my code then:
Models:
from django.db import models
class Contenidos(models.Model):
title = models.CharField(max_length = 255)
content = models.TextField()
created = models.DateTimeField(auto_now_add=True)
published = models.BooleanField(default=True)
class Meta:
ordering = ['-created']
def __unicode__(self):
return u'%s' % self.title
Views:
from django.shortcuts import render
from granada.models import Contenidos
def contenidos(request):
contenido_list = Contenidos.objects.all()
return render(request, 'contenidos.html', {'contenido_list' : contenido_list})
contenidos.html
{% extends 'base.html' %}
{% block title %} Contenidos {% endblock %}
{% block content %}
<h2> contenidos </h2>
{% for contenido in contenido_list %}
<h3>
{{ contenido_list.title }}
</h3>
<p>{{ contenido_list.content }}</p>
{% endfor %}
{% endblock %}
You're accessing the wrong object in your loop, contenidos instead of contenido.
{% extends 'base.html' %}
{% block title %} Contenidos {% endblock %}
{% block content %}
<h2> contenidos </h2>
{% for contenido in contenidos %}
<h3>
{{ contenido.title }} {# was contenidos.title #}
</h3>
<p>{{ contenido.content }}</p>
{% endfor %}
{% endblock %}

Categories