I have model where I can upload files without problem, and a model forms which upload the file, which get the path perfectly when I call them in a html loop; but this files can't be accessed by django admin interface. In the two cases the uploaded files can by get in the defined media_root.
What am I doing wrong?
models.py
class Documentos(models.Model):
user = models.OneToOneField(User, on_delete="models_CASCADE", null=True, blank=True)
nome = models.CharField(max_length=200, default='Arquivo')
documento = models.FileField(upload_to='')
data = models.DateField(auto_now_add=True)
formatado = models.BooleanField(default=False)
class Meta:
verbose_name = 'Documento'
verbose_name_plural = 'Documentos'
def __str__(self):
return self.nome
forms.py
class DocumentosForm(forms.ModelForm):
class Meta:
model = Documentos
fields = ['user','nome','documento']
views.py
from django.shortcuts import render
from django.contrib.auth.decorators import login_required
from django.core.files.storage import FileSystemStorage
from .forms import *
from .models import *
def alfa(request):
return render(request, 'pdfupload.html')
# Create your views here.
#login_required(login_url='/register')
def upload(request):
context = {}
if request.method == 'POST':
uploaded_file = request.FILES['document']
fs = FileSystemStorage()
name = fs.save(uploaded_file.name, uploaded_file)
context['url'] = fs.url(name)
return render(request, 'pdfupload.html', context)
def documentos_lista(request):
return render(request, 'lista.html')
def upload_documento(request):
return render(request, 'documento_upload.html')
forms.html:
<form method="post" enctype="multipart/form-data">
{% csrf_token %}
<input type="file" name="document" />
<input type="submit" name="submit" value="Upload" />
</form>
I have my project/urls.py:
...
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
I am using django 2.1
Even I can't get the uploadedfiles by forms in django admin, no error message is returned.
I am very grateful for your help. Thank you, have a nice day.
Related
The form I created is not inserting the data into my database table. As far as I can tell I've done everything correctly but it still refuses to do so instead it "post" in the console and clears the form fields without creating nothing in the database. None of the data that entered is saved anywhere? Here are the files below hopeful someone can see something I'm missing.
ps. I've connected my database, ran migrations and created a superuser as well but still nothing.
models.py
from django.db import models
Media_Choices = (
("TV", "TV"),
("Radio", "Radio"),
("Youtube", "Youtube"),
("Podcast", "Podcast"),
)
class Appear(models.Model):
Show = models.CharField(max_length=100)
Media = models.CharField(max_length=30, blank=True, null=True, choices=Media_Choices)
Episode = models.IntegerField()
Date = models.DateField(max_length=100)
Time = models.TimeField(auto_now=False, auto_now_add=False)
Producer = models.CharField(max_length=100)
Producer_Email = models.EmailField(max_length=254)
def __unicode__(self):
return self.Show + ' ' + self.Producer_Email
forms.py
from django import forms
from django.core.exceptions import ValidationError
from django.forms import ModelForm
from .models import Appear
class AppsForm(ModelForm):
class Meta:
model = Appear
fields = '__all__'
def clean_Producer_Email(self):
Producer_Email = self.cleaned_data.get('Producer_Email')
if (Producer_Email == ""):
raise forms.ValidationError('field cannot be left empty')
for instance in Appear.objects.all():
if instance.Producer_Email == Producer_Email:
raise forms.ValidationError('Please fill in correct email')
return Producer_Email
views.py
from django.shortcuts import redirect, render
from django.http import HttpResponse
from .forms import AppsForm
from .models import Appear
def AppS(request):
if request == 'POST':
form = AppsForm(request.POST)
if form.is_valid():
Apps = form.save(Commit=False)
Apps.save()
else:
form = AppsForm()
return render(request, 'AppsForm.html', {'form': form})
def results(request):
return render(request, 'Results.html')
AppsForm.html
<body>
{% extends 'base.html' %}
{% block content %}
{% load crispy_forms_tags %}
<form action="" method="POST">
{% csrf_token %}
{{ form|crispy }}
<input type="submit" value="submit">
</form>
{% endblock %}
enter code here
You might be missing form errors due to which the form is not saving. Try printing if there are any form errors.
if form.is_valid():
Apps = form.save(Commit=False)
Apps.save()
else:
print(form.errors)
I am trying to make a contact form but it's html template does not see {{ form }} template. What am I doing wrong? Where is an error.
My code is attached above.
models.py
class Contact(models.Model):
listing = models.CharField(max_length=200)
listing_id = models.IntegerField()
name = models.CharField(max_length=200)
email = models.EmailField()
phone = models.CharField(max_length=100)
message = models.TextField(blank=True)
file = models.FileField(upload_to='files/%Y/%m/%d/', blank=True)
contact_date = models.DateTimeField(default=datetime.now, blank=True)
user_id = models.IntegerField(blank=True)
def __str__(self):
return self.name
def get_absolute_url(self):
return reverse('listings', kwargs={'pk': self.pk})
In views.py file
class ContactCreate(CreateView):
model = Contact
form_class = ContactForm
template_name = 'listing.html'
urls.py
from django.urls import path
from . import views
urlpatterns = [
path('listings/<int:pk>/', views.ContactCreate.as_view(), name='contact-create')
]
html
<form action="{% url 'contact-create' pk=listing.pk %}" method="post">
{{ form }}
{% csrf_token %}
<input type="submit" value="Send" class="btn btn-block btn-secondary">
</form>
forms.py
class ContactForm(forms.ModelForm):
class Meta:
model = Contact
fields = ['name','email','phone','file']
Could you help me out, please
If you provide a form_class with ContactForm, Django is expecting a form to be provided so you have two options:
Create a form.py and add the following:
from django import forms
class ContactForm(forms.Form):
name = forms.CharField()
message = forms.CharField(widget=forms.Textarea)
Don't forget to add that to your view:
from myapp.forms import ContactForm
If you want your custom form to be display you have to specify the form_class in your create view:
form_class = ContactForm
If you are using a custom template to display your form add the following to your create view:
template_name = 'listing.html' # or the path to your template
What I want to do: I want to have a login form that when details are entered they are saved on the admin side.
My problem: the forms are not showing up on my local host page. See image below:
Here is the code from the login form app:
admin.py:
from django.contrib import admin
# Register your models here.
from .models import Contact
admin.site.register(Contact)
from apps.py:
from django.apps import AppConfig
class ContactConfig(AppConfig):
name = 'contact'
from forms.py
from .models import Contact
class ContactForm(forms.ModelForm):
class Meta:
model = Contact
fields = ('username', 'password')
from models.py:
class Contact(models.Model):
username = models.CharField(max_length=100)
password = models.CharField(
max_length=100,
)
def __str__(self):
return f'{self.username} {self.password}'
from views.py:
# Create your views here.
from .forms import ContactForm
def contact(request):
template = "home2.html"
if request.method == "POST":
form = ContactForm(request.POST)
if form.is_valid():
form.save()
else:
form = ContactForm()
context = {
'form': form,
}
return render(request, template, context)
Then finally from the login page:
{% load static %}
<form method="post" class="form">
{% csrf_token %}
{{ form }}
<button type="submit" class="btn">Log In</button>
</form>
Another thing: forms are connected to the admin side but just do not appear on the login page
I looked at similar questions but they do not seem to apply. I have a very simple django form which does not show on the website, I only see the Submit button. Here are the relevant files:
models.py
from django.db import models
from django.urls import reverse
import uuid
# Create your models here.
class Job(models.Model):
id = models.UUIDField(
primary_key=True,
default=uuid.uuid4,
editable=False)
job_name = models.CharField(max_length=200)
#One to many relationship requires on_delete
email = models.EmailField()
def __str__(self):
return self.job_name
forms.py
from django import forms
class JobForm(forms.Form):
job_name = forms.CharField(max_length=200)
email = forms.EmailField()
views.py
from django.shortcuts import render
from django.views.generic import TemplateView
from .forms import JobForm
from .models import Job
class HomePageView(TemplateView):
template_name = 'index.html'
class SubmitPageView(TemplateView):
template_name = 'submit.html'
def submit_job(request):
# Retrieve post by id
if request.method == 'POST':
# Form was submitted
form = JobForm(request.POST)
if form.is_valid():
#Form fields passed validation
#If the form is valid, we retrieve the validated data accessing
#form.cleaned_data. This attribute is a dictionary of form fields and their values.
cd = form.cleaned_data
my_model = Job()
my_model.job_name = cd.get('job_name')
my_model.email = cd.get('email')
# Save the job to the database
my_model.save()
else:
form = JobForm()
return render(request, SubmitPageView(), {'form': form})
And in my template I have
<form method="POST" action=".">
<table>
{% csrf_token %}
{{ form.as_table }}
</table>
which gets rendered as:
<form method="POST" action=".">
<table>
<input type="hidden" name="csrfmiddlewaretoken" value="I7yL9XAUhEPiriKVHKtqh9UfhsLWoJrBo68uguqMecX8gmuNoJV7gykvsPc7FtQ2">
</table>
OK, I found the solution by following https://docs.djangoproject.com/en/3.0/topics/class-based-views/intro/
Basically, as I was using class-based views, the functions to get and post the form need to be subsumed into the class-based view for that page. Here is the current version
of views.py:
from django.shortcuts import render
from django.views.generic import TemplateView
from .forms import JobForm
from .models import Job
class HomePageView(TemplateView):
template_name = 'index.html'
class SubmitPageView(TemplateView):
form_class = JobForm
template_name = 'submit.html'
def get(self, request, *args, **kwargs):
form = self.form_class()
return render(request, self.template_name, {'form': form})
def post(self, request, *args, **kwargs):
form = self.form_class(request.POST)
if form.is_valid():
#Form fields passed validation
#If the form is valid, we retrieve the validated data accessing
#form.cleaned_data. This attribute is a dictionary of form fields and their values.
cd = form.cleaned_data
my_model = Job()
my_model.job_name = cd.get('job_name')
my_model.email = cd.get('email')
# Save the job to the database
my_model.save()
else:
form = JobForm()
return render(request, self.template_name, {'form': form})
Try code below:
# if a GET (or any other method) we'll create a blank form
else:
form = JobForm()
return render(request, 'submit.html', {'form': form})
<form action="/your-name/" method="post">
{% csrf_token %}
{{ form.as_table }}
<input type="submit" value="Submit">
</form>
Does it make a difference if you define the form as a modelForm and explicitly state the model and fields?
Add/modify the following to your Forms.py:
class JobForm(forms.ModelForm):
class Meta:
model = Job
fields = ('job_name', 'email')
job_name = forms....
I am new to using django. In my app, I am uploading images that is being stored to the media folder. Now, I am trying to provide the link for downloading the image which is not working. I also tried to display the image directly( using img in html) which is not working either.
My code is as follows:
urls.py
from django.conf.urls import url
from . import views
from django.conf import settings
from django.conf.urls.static import static
app_name = 'workers'
urlpatterns = [
url(r'^$', views.index, name= 'index'),
url(r'^enrollment$',views.enroll, name='enroll'),
url(r'^save_enrollment$',views.save_enrollment, name='save_enrollment'),
]
if settings.DEBUG:
urlpatterns = urlpatterns + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
forms.py
from django import forms
from django.forms import ModelForm
from .models import Worker
class Worker_enrollment(forms.ModelForm):
name = forms.CharField(max_length=250)
address = forms.CharField(max_length=500)
phone_number = forms.CharField(max_length=100)
designation = forms.CharField(max_length=1000)
docfile = forms.FileField(label='select an image to upload')
ssn = forms.CharField(max_length=200)
class Meta:
model = Worker
fields = ['name','address','phone_number','designation','docfile','ssn']
models.py:-
from django.db import models
class Worker(models.Model):
name = models.CharField(max_length=250)
address = models.CharField(max_length=500)
phone_number = models.CharField(max_length=100)
designation = models.CharField(max_length=1000)
docfile = models.ImageField(upload_to='documents/')
ssn = models.CharField(max_length=200)
def __str__(self):
return (self.name)
views.py:-
from .models import Worker
from .forms import Worker_enrollment
from django.shortcuts import render, get_object_or_404
from django.conf import settings
def index(request):
workers_info = Worker.objects.all()
context = {
'workers':workers_info
}
return render(request, 'workers/index.html', context)
def enroll(request):
form = Worker_enrollment(request.POST)
if form.is_valid():
return render(request, 'workers/enroll.html', {'form': form})
else:
form = Worker_enrollment()
return render(request, 'workers/enroll.html', {'form': form})
def save_enrollment(request):
worker_info = Worker()
if request.method == 'POST':
form = Worker_enrollment(request.POST,request.FILES)
if form.is_valid():
worker_info.name = form.cleaned_data['name']
worker_info.address = form.cleaned_data['address']
worker_info.designation = form.cleaned_data['designation']
worker_info.phone_number = form.cleaned_data['phone_no']
worker_info.ssn = form.cleaned_data['ssn']
worker_info.docfile = request.FILES['docfile']
worker_info.save()
return render(request,'workers/saves_worker.html',{'worker_info':worker_info})
else:
form = Worker_enrollment()
return render(request, 'workers/saves_worker.html', {'worker_info': worker_info})
enroll.html:-
<form action="save_enrollment" method="post" enctype="multipart/form-data">
{% csrf_token %}
{{ form.as_ul }}
<input type="submit" value="Submit" />
</form>
saves_worker.html:-
<h1>Worker has been enrolled</h1>
<br>
<h2>Name - {{worker_info.name}}</h2><br>
<h2>PhoneNo - {{worker_info.phone_number}}</h2><br>
<h2>Designtion - {{worker_info.designation}}</h2><br>
<h2>SSN - {{worker_info.ssn}}</h2>
<h2>Address - {{worker_info.address}}</h2>
<h2><a href="{{ worker_info.docfile.url }}" >worker's image</h2>
The following are specified in the settings.py file:-
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__))
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
STATIC_URL = '/static/'
STATICFILES_DIRS = (os.path.join(BASE_DIR, "static"),)
Are you sure your save_enrollment function saves the image in docfile field of the worker_info. Try using:
def save_enrollment(request):
if request.method == 'POST':
form = Worker_enrollment(request.POST,request.FILES)
if form.is_valid():
worker_info = form.save()
return render(request,'workers/saves_worker.html',{'worker_info':worker_info})
else:
form = Worker_enrollment()
return render(request, 'workers/saves_worker.html', {'worker_info': worker_info}
You dont need to define the fields again in your modelform. Also you are using FileField in the form instead of ImageField. If you want to add extra field in the form, you need to add those fields in __init__() method of form.
Try with the following:
class Worker_enrollment(forms.ModelForm):
class Meta:
model = Worker
fields = ['name','address','phone_number','designation','docfile','ssn']
Extra tip: Dont use CharField with max_length=1000. CharField should be used upto 255 characters. If you need more length use TextField instead. You also need to install Pillow library in order to make images visible.
I just solved my problem by changing the MEDIA_URL as follows:
MEDIA_URL = 'shield/media/'
The name of my project is shield.