I have trouble with edit data in django project.
Everything is almost ok :) , but if I'm trying edit data my form get all data from database exept date field.
I found solution as below and I see datapicker on my edit form but I have to fill in data to this field.
Every data in edit form are filled in exept this one.
Datapicker for adding records works good. I'm using the same form to add and edit.
My forms.py is listed below:
from django import forms
from .models import Expens, Category
class DateInput(forms.DateInput):
input_type = 'date'
class ExpensForm(forms.ModelForm):
class Meta:
model = Expens
fields = ('name', 'date', 'category', 'value', 'add_description', 'scan')
labels = {
'name': 'Nam:',
'date': 'Date:',
'category': 'Category:',
'value': 'Value:',
'add_description': 'Descripion:',
'scan': 'Scan:',
}
widgets ={
'name': forms.TextInput(attrs={'class': 'form-control'}),
'date': DateInput(attrs={'class': 'form-control'}),
'category': forms.Select(attrs={'class': 'form-control'}),
'value': forms.NumberInput(attrs={'class': 'form-control'}),
'add_description': forms.TextInput(attrs={'class': 'form-control'}),
'scan':(),
}
My html template to this forms is listed below:
{% extends 'expenses/index.html' %}
{% block tytul %} DATABASE FORMS {% endblock %}
{% load bootstrap5 %}
{{ form.media }}
{% block strona %}
{% if new %}
<h5>Add record</h5>
{% else %}
<h5>Edit record</h5>
{% endif %}
<div class="mb-3">
<form method="post" enctype="multipart/form-data">
{% csrf_token %}
{% bootstrap_form form %}
<div class="col-lg-12" style="text-align:center">
{% if new %}
<button type="submit" class="btn btn-success btn-sm">ADD</button>
{% else %}
<button type="submit" class="btn btn-success btn-sm">EDIT</button>
{% endif %}
</div>
</form>
</div>
<div class="col-lg-12" style="text-align:center">
<br>
<br>
Back
</div>
{% endblock %}
My models.py listing is:
from django.db import models
# Create your models here.
class Category(models.Model):
name = models.CharField(max_length=60, blank=False, unique=True)
add_description = models.TextField(default="")
def __str__(self):
return self.name
class Expens(models.Model):
name = models.CharField(max_length=120, blank=False, null=False)
date = models.DateField(null=True, blank= True)
category= models.ForeignKey(Category, blank=False, null=True, on_delete=models.SET_NULL)
value = models.DecimalField(max_digits=10, decimal_places=2, null = False, blank=False)
add_description = models.TextField(default="", null=True, blank=True)
scan = models.ImageField(upload_to ="scans", null = True, blank = True)
def __str__(self):
return self.expens_with_data()
def expens_with_data(self):
return "{} ({})".format(self.category, self.date)
What is wrong with my form ? :)
Related
Coding some kind of blog with django, and I can't make homepage to contain images of the articles... It just doesn't upload a image...
my Views.py :
class AddPostView(CreateView):
model = Post
form_class = PostForm
template_name = 'add_post.html'
my Models.py:
class Post(models.Model):
title = models.CharField(max_length=255)
title_tag = models.CharField(max_length=255, default="YNTN")
#author = models.ForeignKey(User, on_delete=models.CASCADE)
body = RichTextField(blank=True, null=True)
image = models.ImageField(upload_to="profile_pics", blank=True, null=True)
#body = models.TextField()
post_date = models.DateField(auto_now_add=True)
likes = models.ManyToManyField(User, related_name="blog_posts")
def total_likes(self):
return self.likes.count()
def __str__(self):
return (self.title + " | " + str(self.author))
def get_absolute_url(self):
return reverse("home")
My Forms.py:
class PostForm(forms.ModelForm):
class Meta:
model = Post
fields = ('title', 'title_tag', 'body', 'image')
widgets = {
'title': forms.TextInput(attrs={'class':'form-control', 'placeholder':'Title of the Blog'}),
'title_tag': forms.TextInput(attrs={'class':'form-control', 'placeholder':'Copy the title with no space and a hyphen in between'}),
'body': forms.Textarea(attrs={'class':'form-control', 'placeholder':'Content of the Blog'}),
}
and my add_post.html :
{% extends 'base.html' %}
{% block title %}Make an article{% endblock %}
{% block content %}
{% if user.is_authenticated %}
<h1>Make an article</h1>
<div class="form-group">
<form method="POST">
<br/>
{% csrf_token %}
{{ form.media }}
{{ form.as_p }}
<button class="btn btn-dark">POST</button>
</div>
{% else %}
<h1>You are not allowed to post! You need to Log in or Register</h1>
{% endif %}
{% endblock %}
I tried on many ways but never worked..
You are missing enctype="multipart/form-data" (as mentioned in the documentation) in the form tag inside the html template. Update the html file like this:
<form method="POST" enctype="multipart/form-data">
<br/>
{% csrf_token %}
{{ form.as_p }}
<button type="submit" class="btn btn-dark">POST</button>
</form>
I am having some trouble getting a file to post via a form using generic class-based view CreateView. Below is what i have so far. I am not quite sure how to handle the file and if request.FILES is getting the file being posted or if there is something else i need to be doing to capture the file information in the form. I have tried following the docs, however no luck in getting something working. File uploads as a blank field.
views.py
# Create
class FileUploadCreateView(BSModalCreateView):
template_name = 'fileupload/create-file.html'
form_class = FileUploadModelForm
success_message = 'Success: File was uploaded.'
success_url = reverse_lazy('files_list')
# Add required field my_user prior to posting form
def form_valid(self, form):
form = FileUploadModelForm(self.request.POST, self.request.FILES)
self.object = form.save(commit=False)
self.object.my_user = self.request.user
self.object.file_status = 'ready'
return super().form_valid(form)
forms.py
class FileUploadModelForm(BSModalModelForm):
class Meta:
model = FileUpload
fields = ['file_name', 'file_description', 'file_date_from', 'file_date_to','file_upload']
widgets = {
'file_name': forms.TextInput(attrs={'class':'form-control mb-3', 'id':'ruleset_name'}),
'file_description': forms.Textarea(attrs={'rows':5}),
'file_date_from': DatePickerInput(
options={
"format": "MM/DD/YYYY",
"showClose": True,
"showClear": True,
"showTodayButton": True,
}
),
'file_date_to': DatePickerInput(
options={
"format": "MM/DD/YYYY",
"showClose": True,
"showClear": True,
"showTodayButton": True,
}
),
'file_upload': forms.FileInput(attrs={'class':'form-control-file mb-3', 'id':'file_upload', 'type':'file', }),
}
html
{% load widget_tweaks %}
<form method="post" action="" enctype="multipart/form-data">
{% csrf_token %}
<div class="modal-header">
<h5 class="modal-title" style="color:#7a7a7a;">
<i class="fas fa-plus-square fa-med pr-2 align-middle"></i>
<span class="align-middle">ADD File</span>
</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<div class="{% if form.non_field_errors %}invalid{% endif %} mb-2">
{% for error in form.non_field_errors %}
{{ error }}
{% endfor %}
</div>
{% for field in form %}
<div class="form-group">
<label for="{{ field.id_for_label }}" style="font-size: small; color:#7a7a7a;">{{ field.label }}</label>
{% render_field field class="form-control" %}
<div class="{% if field.errors %} invalid{% endif %}">
{% for error in field.errors %}
<p class="help-block">{{ error }}</p>
{% endfor %}
</div>
</div>
{% endfor %}
</div>
<div class="modal-footer">
<button type="button" class="btn btn-outline-secondary" data-dismiss="modal">Cancel</button>
<button type="button" class="submit-btn btn btn-primary pr-4 pl-4">Save</button>
</div>
</form>
model.py
class FileUpload(models.Model):
"""
Class for the creation of file uploads
"""
id = models.AutoField(primary_key=True)
my_user = models.ForeignKey('users.MyUser', on_delete=models.CASCADE, related_name='file_uploads', default=None)
file_name = models.CharField(max_length=255, blank=False, default=None, verbose_name='File Name')
file_description = models.CharField(max_length=255, blank=False, default=None, verbose_name='File Description')
file_date_from = models.DateField(default=None, null=True, blank=False, verbose_name='File Date From')
file_date_to = models.DateField(default=None, null=True, blank=False, verbose_name='File Date To')
STATUS_CHOICES = (
('ready','Ready'),
('processed', 'Processed'),
('archived','Archived'),
)
file_status = models.CharField(max_length=9, choices=STATUS_CHOICES, default=None, blank=False, verbose_name='File Status')
file_create_date = models.DateTimeField(verbose_name='File Create Date', auto_now_add=True)
file_upload = models.FileField(upload_to='uploads/%Y/%m/%d/', default=None, verbose_name='File Upload', blank=True)
class Meta:
ordering = ['-file_create_date']
constraints = [
models.UniqueConstraint(fields=['my_user','file_name'], name='Unique MyUser File')
]
def __str__(self):
return self.file_name
Pretty sure you forgot to add the enctype="multipart/form-data" data attribute to the form tag in your template.
To be sure, you would have to provide us with the Model, the Form and the template code.
after working on the view for some time, I was able to get the file to post via the following, using cleaned_data.
# Add required fields prior to posting form
def form_valid(self, form):
self.instance = form.save(commit=False)
self.instance.my_user = self.request.user
self.instance.file_status = 'ready'
self.instance.file_upload = form.cleaned_data['file_upload']
return super().form_valid(form)
I am really lost and trying to solve this issue for hours. I am working on this social media for photographers, where they can comment each other's photos. I set up forms for comments, but I am getting AttributeError :
'Post' object has no attribute 'get_content_type'
This is my Views.py - photo_detail, where is the error :
def photo_detail(request, id):
instance = get_object_or_404(Post, id=id)
comments = Socialmedia.objects.filter_by_instance(instance)
initial_data = {
"content_type": instance.get_content_type,
"object_id": instance.id
}
socialmedia_form = SocialmediaForm(
request.POST or None, initial=initial_data)
if socialmedia_form.is_valid():
print(socialmedia_form.cleaned_data)
context = {
"title": instance.title,
"photo": instance.photo,
"instance": instance,
"comments": comments,
"socialmedia_form": socialmedia_form,
}
return render(request, "photo_detail.html", context)
When I comment out line "content_type": instance.get_content_type,, the error disaapers, but after writing comment its saying field is required and not posting anything , so it doesnt load the data from comment.
And here is my models.py :
from django.db import models
from django.urls import reverse
from django.contrib.auth.models import User
from socialmedia.models import Socialmedia, SocialmediaManager
from django.contrib.contenttypes.models import ContentType
def upload_location(instance, filename):
return '%s/%s' % (instance.id, filename)
class Post(models.Model):
# category = models.ForeignKey(Type, blank=True, null=True, on_delete=models.CASCADE)
user = models.ForeignKey(User, on_delete=models.CASCADE, default=1)
title = models.CharField(max_length=200)
updated = models.DateTimeField(auto_now=True, auto_now_add=False)
time = models.DateTimeField(auto_now=False, auto_now_add=True)
photo = models.ImageField(upload_to=upload_location,
null=True, blank=True,
height_field="height_field",
width_field="width_field")
height_field = models.IntegerField(default=0)
width_field = models.IntegerField(default=0)
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse("photo_detail", kwargs={"id": self.id})
#property
def get_content_type(self):
instance = self
content_type = ContentType.objects.get_for_model(instance.__class__)
return content_type
And the last page photo_detail.html, where I am trying to implement it.
{% extends "base.html" %}
{% block content%}
<div class="col-sm-8 col-sm-offset-6">
{% if instance.photo %}
<img src="{{ instance.photo.url }}" class="img-responsive"/>
{% endif %}
<h1>{{ title }} </h1>
<p>Author: {{ instance.user}}</p>
<p><div class="fb-like" data-href="https://developers.facebook.com/docs/plugins/" data-width="" data-layout="button" data-action="like" data-size="small" data-share="true"></div></p>
<br>
<p>Updated : {{ instance.updated }}<br/></p>
<p> Created :{{ instance.time }}<br/></p>
<div>
{{instance.comments.all}}
<p class="lead">Comments</p>
<form method="POST" action="."> {% csrf_token %}
{{ socialmedia_form}}
<input type="submit" value="Post" class="btn btn-default">
</form>
{% for comment in comments %}
<div class="">
{{ comment.content }}
{{comment.user}} {{comment.time | timesince }} ago
</div>
{% endfor %}
</div>
</div>
{% endblock %}
I made a project with net-ninja on youtube now I am adding "uploading media" feature in my own project but it is not working although every thing is set just tell me where i m going wrong.
My form is keep asking me to upload image file even though i had already done, every time i send a post request it renders the page again with no value in image field. what is wrong here, why it is not taking image input?Don't comment set the required to false that is not the solution i don't know why some people said this to others on stackoverflow when they asked the same question as me.
My model class looks like this
class Products(models.Model):
name = models.CharField(max_length=500, unique=True, )
price = models.IntegerField()
stock = models.IntegerField()
date_added = models.DateTimeField(verbose_name="date added", auto_now_add=True, )
thumb = models.ImageField(default='default.png', blank=True)
profile = models.ForeignKey(Profile, on_delete=models.CASCADE, default=None,)
def __str__(self):
return self.name
class Meta():
verbose_name_plural = "Products"
My form looks like this
class AddProduct(forms.ModelForm):
name = forms.CharField(widget=forms.TextInput(attrs={'placeholder':'Product Name', 'required':'True', 'class': 'form-control'}))
price = forms.IntegerField(widget=forms.NumberInput(attrs={'placeholder':'Set Price', 'required':'True', 'class': 'form-control'}))
stock = forms.IntegerField(widget=forms.NumberInput(attrs={'placeholder':'Number of items', 'required':'True', 'class': 'form-control'}))
thumb = forms.ImageField(required=False, widget=forms.ClearableFileInput(attrs={'placeholder':'Upload Picture', 'enctype' : 'multipart/form-data'}))
class Meta():
model = Products
fields = ('name', 'price', 'stock','thumb', )
HTML looks like this
<form class="row contact_form" action="/shop/add_products" method="post">
{% csrf_token %}
{% for field in form %}
<div class="col-md-12 form-group p_star">
{{ field }}
{{ field.errors }}
</div>
{% endfor %}
<!-- {% for field in form %}
{% for error in field.errors %}
<div class="col-md-12 form-group p_star">
{{ error }}
</div>
{% endfor %}
{% endfor %} -->
{% if form.non_field_errors %}
<div class="col-md-12 form-group p_star">
{{ form.non_field_errors }}
</div>
{% endif %}
<div class="col-md-12 form-group">
<button type="submit" value="submit" class="btn_3">
Add Product
</button>
</div>
</form>
My views file looks like this
#login_required(login_url='/shop/login')
def shop_add_products(request):
if request.method == 'POST':
form = AddProduct(request.POST, request.FILES)
if form.is_valid():
instance = form.save(commit=False)
instance.profile = request.user
instance.save()
return redirect("/shop/products")
else:
form = AddProduct()
return render(request, "pillow_site_html/add_product.html", { 'form':form })
Oh sorry i didn't understood the question here, you are getting that because in fact you are not sending the picture inside your form as you have to add this to your form so it can accept files handling
<form class="row contact_form" action="/shop/add_products" method="post" enctype="multipart/form-data">
I have a form field that I want to have as a calendar widget that defaults to the current date. I had it so it was showing the date in d/m/y format but when I'd submit it would say Enter a valid date
forms.py
class CreateBlogPostForm(forms.ModelForm):
published = forms.DateField()
class Meta:
model = BlogPost
fields = ('title', 'published','featured_image', 'post',)
widgets = {
'title': forms.TextInput(attrs={'class': 'blog-title-field', 'placeholder': 'Title'}),
'published': forms.DateInput(format=('%d-%m-%Y'), attrs={"type": 'date'}),
'post': forms.TextInput(attrs={'class': 'blog-post-field', 'placeholder': 'Write something..'}),
}
models.py
class BlogPost(models.Model):
title = models.CharField(max_length=100)
published = models.DateField()
featured_image = models.ImageField(upload_to='blog/%Y/%m/%d')
post = models.TextField()
slug = AutoSlugField(null=True, default=None,
unique=True, populate_from='title')
class Meta:
verbose_name_plural = "Blog"
def __str__(self):
return self.title
create-blog.html
{% extends 'base.html' %}
{% block content %}
<div class="container text-center">
<form enctype="multipart/form-data" method="POST">
{% csrf_token %}
{{form.title}}
{{form.post}}
{{form.featured_image}}
{{form.published}}
{{form.errors}}
<button type="submit" class="btn btn-primary"><i class="fa fa-plus" aria-hidden="true"></i> Submit</button>
</form>
</div>
{% endblock content %}
If you see carefully, your DateInput format is as format=('%d-%m-%Y') while your question states that your format for date is in d/m/y. Try with the hyphen instead of the slash, or vice versa and you should be fine.