I am trying to save the image without using Django forms in the media folder. The image should save in the media\seller_profile folder and its path has to be entered in a database like seller_profile\abc.png but somehow I am getting only abc.png missing seller_profile.
Models.py
class SellerProfile(models.Model):
email = models.EmailField(max_length=255, unique=True)
first_name = models.CharField(max_length=255, default=None, null=True)
seller_profile_picture = models.ImageField(upload_to='seller_profile', default="seller_profile/empty_profile.png")
def __str__(self):
return self.email
Views.py
def profile(request):
if request.method == "POST":
profile_data = SellerProfile.objects.filter(email = str(request.user)).update(
first_name = request.POST.get("First name"),
seller_profile_picture = request.FILES["seller profile picture"],
)
print("object File --->", request.FILES["seller profile picture"])
return redirect("/seller/profile")
else:
user_data = SellerProfile.objects.filter(email=str(request.user))
if len(user_data) == 0:
SellerProfile.objects.create(email = str(request.user))
data_entered = {"First name": "Value not Provided"}
else:
data_entered = dict()
data_entered["First name"] = user_data[0].first_name
return render(request, "seller/profile.html", {"data_entered":data_entered})
seller/profile.html
{% extends 'general/layout.html'%}
{% block body %}
<div class="container">
<div class="jumbotron">
<form method="post" enctype=multipart/form-data>
{% csrf_token %}
{% for attribute, placeholder in data_entered.items %}
<div class="form-group">
<dt><label for="{{attribute}}">{{attribute}}</label>
<dd><input class="form-control" id="{{attribute}}" name="{{attribute}}"
type="text" placeholder="{{placeholder}}" required>
</dd>
</div>
{% endfor %}
<dt><label for="seller profile picture">Profile Picture</label>
<dd><input class="form-control" id="seller profile picture" name="seller profile picture"
type="file" required>
</dd>
</dt>
<div class="form-group text-center">
<p>
<input class="btn btn-primary " type="submit" value="Update">
</p>
</div>
</form>
</div>
</div>
{% endblock%}
Updating Models.py by referring link. According to this solution update do not call save.
def profile(request):
if request.method == "POST":
print("get ", SellerProfile.objects.get(email = str(request.user)))
print("type get ", type(SellerProfile.objects.get(email = str(request.user))))
profile_data = SellerProfile.objects.get(email = str(request.user))
profile_data.email = str(request.user),
profile_data.first_name = request.POST.get(seller_char_attribute[0]),
profile_data.seller_profile_picture = request.FILES["seller profile picture"],
profile_data.save()
but this gives me error as follow
Virtialenv\lib\site-packages\django\db\models\fields\files.py",line 286, in pre_save
if file and not file._committed:
AttributeError: 'tuple' object has no attribute '_committed'
You've left trailing commas at the end of some of the lines where you're assigning values to the profile_data object. Those commas mean that tuples will be assigned rather than the values you intend:
profile_data.email = str(request.user),
profile_data.first_name = request.POST.get(seller_char_attribute[0]),
profile_data.seller_profile_picture = request.FILES["seller profile picture"],
Removing the trailing commas from the above lines should resolve.
In your profile function def profile(request):
where you are dealing with image
profile_data.seller_profile_picture = request.FILES["seller profile picture"],
Instead of this you have to use request.FILES.get()
An instead of passing the image name in list type ["seller profile picture"]you have to give only image name
So at last your line will look like this
profile_data.seller_profile_picture = request.FILES.get("seller profile picture")
Related
i am still learning django. trying to create a comment form in my blogdetail view.. i am following a tutorial from youtube..
https://www.youtube.com/watch?v=An4hW4TjKhE&t=40s
this tutorial has form which takes users from django users .. but in my form i want user to enter his name ,email and content..
following this tutorial i made form model but i have no idea how to get data from my own html form by this..
i have reached to a stage where in admin i can add comments and display them in my html file but now i am getting an error..
name 'post' is not defined
my files are..
forms.py
from django import forms
from.models import Comment
class CommentForm(forms.ModelForm):
class Meta:
model = Comment
fields = ('content', 'email', 'name' ,)
models.py
class BlogPost(models.Model):
title = models.CharField(max_length=500)
writer = models.CharField(max_length=150,default='my dept')
category =models.CharField(max_length=150)
image = models.ImageField(upload_to='images')
post = models.TextField(max_length=2000)
Date = models.DateField( default=datetime.date.today)
def __str__(self):
return self.title
class Comment(models.Model):
post = models.ForeignKey(BlogPost , on_delete=models.CASCADE)
name = models.CharField (max_length = 150)
email = models.CharField (max_length = 150)
content = models.TextField ()
def __str__(self):
return self.email
views.py
def detailview(request, id=None):
blg = get_object_or_404(BlogPost, id=id)
comments = Comment.objects.filter( post=blg).order_by('-id')
if request.method == 'POST':
comment_form = CommentForm(request.POST or None )
if comment_form.is_valid():
content = request.POST.get('content')
Comment.objects.create(post= post , content=content)
comment_form.save()
else:
comment_form = CommentForm()
context = {'blg': blg,
'comments': comments,
'comment_form' : comment_form,
}
return render(request, 'blog/blogdetail.html', context)
blogdetail.html
<div id="respond" class="clearfix">
<div class="title-box">
<h3>Leave a <strong>Comment</strong></h3>
</div><!-- end title-box -->
<div class="row">
<!-- start Comment Form -->
<form class="clearfix" action="#" method="post" id="commentform">
{% csrf_token %}
<p class="comment-notes"><span id="email-notes">Your email address will not be published.</span> Required fields are marked <span class="required">*</span></p>
<div class="form-group">
<div class="col-sm-12">
<label>Comment<span class="required">*</span></label>
<textarea name="comment" cols="58" rows="7" tabindex="4" class="form-control" required >{{comment.content}}</textarea>
</div>
</div><!-- end form-group -->
<div class="form-group">
<div class="col-sm-6">
<label>Name<span class="required">*</span></label>
<input name="author" id="author" value="" size="22" tabindex="1" class="form-control" type="text" required >{{comment.name}}</div>
<div class="col-sm-6">
<label>Email<span class="required">*</span></label>
<input name="email" id="email" value="" size="22" tabindex="2" class="form-control" type="text" required >{{comment.email}}</div>
</div><!-- end form-group -->
<div class="form-group">
<div class="col-sm-12">
<button name="submit" type="submit" id="submit-button" tabindex="5" value="Submit" class="btn btn-shutter-out-horizontal btn-lg">Submit Comment</button>
</div>
</div><!-- end form-group -->
</form>
<!-- end Comment Form -->
</div>
</div><!-- #respond end -->
it actually looks like this
[![comment form][1]][1]
i want to post name email and comment from front end .. wasted almost 2 days without no success.. please help..
[1]: https://i.stack.imgur.com/HjDZ6.png
since you are passing the data manually from html rewrite this function
if comment_form.is_valid():
content = request.POST.get('content', '')
email = request.POST.get('email', '')
name = request.POST.get('author', '')
comment =Comment.objects.create(post= blg, email=email, name=name, content=content)
return redirect('posts-detail', pk=comment.id )<this can be how you like it>
what you are missing is getting the missing fields in html they are taken from name attribute in the input
if comment_form.is_valid():
content = request.POST.get('content')
Comment.objects.create(post= blg , content=content) # YOU HAVE ADDED post= post even post variable you are not define
comment_form.save()
I am having an issue that i have been trying to solve for a few days and feel like I have hit a roadblock and can't find the answers I need. What I am trying to do is:
Upload a csv file (this file basically contains details about stock trades) which will be saved in a table and stored in media directory, the content is then parsed and passed to a dictionary (this step is working) -- the contents of this file will be used to update various tables in my database later.
As I loop through the key, value pairs in the dictionary check to see if certain values exist in various models which are used as foreign keys (this part also works) -- So for example, if a trade is tagged with Fund X and fund X doesn't exist in my Fund table, it will take me to a form to fill in all the required fields to create fund X in my database
If a value is missing I want to be sent to a form that will then allow me to create this value in the database so that I can populate the required fields (this part is partially working, I can get to the form for missing data but I am unable to save the inputs of that form to the data base)
I have a utils.py file that will be containing all of my classes or helper functions to accomplish this.
if i print out fund_form.errors in from my views.py file i get the following:
<ul class="errorlist"><li>fund_code<ul class="errorlist"><li>This field is required.</li></ul></li><li>fund_name<ul class="errorlist"><li>This field is required.</li></ul></li></ul>
Please let me know if you need any other information I have been struggling with this for a few days.
models.py
class Funds(models.Model):
fund_code = models.CharField(max_length=10, primary_key=True)
fund_name = models.CharField(max_length=100, unique=True)
def __str__(self):
return self.fund_code + ' - ' + self.fund_name
class Trades(models.Model):
trade_date = models.DateField(default=timezone.now)
trade_file = models.FileField(upload_to='trades/')
user = models.ForeignKey(User, on_delete=models.PROTECT)
views.py
VALID_FILE_TYPES = ['csv']
def upload_trades(request):
if not request.user.is_authenticated:
return render(request, 'position_mgmt/login.html')
else:
form = UploadFileForm(request.POST or None, request.FILES or None)
if form.is_valid():
trades = form.save(commit=False)
trades.user = request.user
trades.trade_date = request.POST['trade_date']
trades.trade_file = request.FILES['trade_file']
file_type = trades.trade_file.url.split('.')[-1]
file_type = file_type.lower()
if file_type not in VALID_FILE_TYPES:
context = {
'trades': trades,
'form': form,
'error_message': 'File type must be .csv',
}
return render(request, 'position_mgmt/upload_trades.html', context)
trades.save()
trade_upload = ProcessUpload(trades.trade_file.name)
parsed_trades = trade_upload.parse_trades()
database_check = trade_upload.check_database(parsed_trades, request)
if database_check['fund_code']:
fund_form = CreateFundForm(request.POST or None)
database_check['form'] = fund_form
if request.method == 'POST':
if fund_form.is_valid():
fund = fund_form.save(commit=False)
fund.user = request.user
fund.fund_code = request.POST['fund_code']
fund.fund_name = request.POST['fund_name']
fund.save()
return render(request, 'position_mgmt/upload_trades.html', {'trades': trades})
return render(request, 'position_mgmt/positions_form.html', database_check)
return render(request, 'position_mgmt/trade_files.html', {'trades': trades})
context = {'form': form}
return render(request, 'position_mgmt/upload_trades.html', context)
forms.py
class UploadFileForm(forms.ModelForm):
class Meta:
model = Trades
fields = ['trade_date', 'trade_file']
class CreateFundForm(forms.ModelForm):
class Meta:
model = Funds
fields = ['fund_code', 'fund_name']
utils.py
class ProcessUpload:
"""
A class to upload and process trade files
Attributes
----------
name: str
name of the file that will be processed
Methods
-------
parse_trades()
imports csv file from the MEDIA_ROOT and returns a list of dictionaries of format:
[{:,:}, {:,:}......]
check_database()
...
"""
def __init__(self, name):
"""
:param name:
name of the csv file
"""
self.name = name
def parse_trades(self):
file_path = os.path.join(settings.MEDIA_ROOT, self.name)
with open(file_path) as f:
trade_file = csv.DictReader(f, restkey='tags')
return list(trade_file)
def check_database(self, trade_dict, request):
for each_trade in trade_dict:
for _key in each_trade:
if _key == 'fund_code':
if not Funds.objects.filter(fund_code=each_trade[_key]).exists():
return {'fund_code': each_trade[_key],
'error_message': 'fund {0} does not exist'.format(each_trade[_key])}
return None
upload_trades.html
{% extends 'position_mgmt/base2.html' %}
{% block title %}Upload{% endblock %}
{% block body %}
<body>
{% block sub_body %}
{% endblock %}
<br>
<div class="container-fluid">
<div class="row">
<div class="col-sm-12 col-md-7">
<div class="panel panel-default">
<div class="panel-body">
<h3>Upload Trades</h3>
{% if error_message %}
<p><strong>{{ error_message }}</strong></p>
{% endif %}
<form class="form-horizontal" role="form" action="" method="post" enctype="multipart/form-data">
{% csrf_token %}
{% include 'position_mgmt/form-template.html' %}
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button type="submit" class="btn btn-success">Submit</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
</body>
{% endblock %}
form-template.html
{% for field in form %}
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<span class="text-danger small">{{ field.errors }}</span>
</div>
<label class="control-label col-sm-4">{{ field.label_tag }}</label>
<div class="col-sm-8">{{ field }}</div>
</div>
{% endfor %}
I'm trying to edit the form via my edit button.
When i click update button in my form I'm getting the following error:
FieldError at /studentapp/editrow/72/
Cannot resolve keyword 'rowid' into field Choices are: address, course, id, name, pub_date, roll
My traceback shows the error originating in this line
item = get_object_or_404(Studentapp, rowid=id) this line.
My models.py looks like this:
class Studentapp(models.Model):
name = models.CharField(max_length=100)
roll = models.IntegerField()
course = models.CharField(max_length=100)
address = models.CharField(max_length=100)
pub_date = models.DateTimeField('date published', auto_now=True)
def __str__(self):
return '%s %s %s %s' % (self.name, self.roll, self.course, self.address)
def published_recently(self):
return self.pub_date >= timezone.now() - datetime.timedelta(days=1)
EDIT
My view:
def editrow(request, id):
item = get_object_or_404(Studentapp, id=id)
if request.method=="POST":
form = EntryForm(request.POST, instance=item)
if form.is_valid():
post=form.save(commit=False)
post.save()
return HttpResponseRedirect(reverse('studentapp:index'), id)
else:
form=EntryForm(instance=item)
return render(request, 'index.html',{'form':form})
else:
form=EntryForm(instance=item)
return render(request, 'index.html',{'form':form})
My urls.py
url(r'^editrow/(?P<rowid>[0-9]+)/$', views.editrow, name='editrow'),
Form that i'm using to update the entry:
{% load staticfiles %}
<form action="{% url 'studentapp:editrow' student_detail.id %}" id="editform" method="POST">
{% csrf_token%}
<div class = "form-group">
<label for = "your_name">
Your name:
</label>
<input class = "form-control" id="new_name" type = "text" name="name" value="{{ student_detail.name }}" placeholder="Enter your name">
</div>
<div class="form-group">
<label for = "course_name">
Course:
</label>
<input id="new_course" class = 'form-control' type = "text" name="course" value="{{ student_detail.course }}" placeholder="Enter your course">
</div>
<div class = "form-group">
<label for = "rollno">
Roll No.:
</label>
<input id="new_rollno" type = "text" class = 'form-control' name="roll" value="{{ student_detail.roll }}" placeholder="Enter your roll number">
</div>
<div class = "form-group">
<label for ="addr">
Address:
</label>
<input id="new_address" type = "text" name="address" class = 'form-control' value="{{ student_detail.address }}" placeholder="Enter your address"/>
</div>
<input type = "submit" value="Update" id="update" class = "btn btn-success" style="font-size:18px;" />
</form>
This line is not right, your model does not have the field rowid
item = get_object_or_404(Studentapp, rowid=id) this line. # WRONG
item = get_object_or_404(Studentapp, id=id) this line. # OK
and your urls should be
url(r'^editrow/(?P<id>[0-9]+)/$', views.editrow, name='editrow'),
# url(r'^editrow/(?P<rowid>[0-9]+)/$', views.editrow, name='editrow'), # WRONG
I want to set a Boolean field is_rep in a retest model to true when the retest form is submitted.
Now it is just get added up in a retest model.
Because I want to trigger other events when the request is submitted.
My code
models.py
class Retest(models.Model):
semester = models.ForeignKey(Semester)
dept = models.ForeignKey(Departement)
batch = models.ForeignKey(Batch)
date = models.DateField(default=0)
subject = models.ForeignKey(Subject)
name = models.CharField(max_length=50)
admnno = models.CharField(max_length=50)
reason = models.CharField(max_length=50)
proof = models.CharField(max_length=200)
is_hod = models.BooleanField(default=False)
is_principal = models.BooleanField(default=False)
notify = models.BooleanField(default=False)
is_sure = models.BooleanField(default=False)
is_rep = models.BooleanField(default=False)
def get_absolute_url(self):
return reverse( 'retest:retestform')
def __str__(self):
return self.name
urls.py
url(r'^retest/retestform/$',login_required(views.RetestCreate.as_view()), name='retestform')
views.py
class RetestCreate(CreateView):
model = Retest
fields = ['semester', 'dept', 'batch', 'date', 'subject', 'name', 'admnno', 'reason', 'proof', 'is_sure']
template
<form class="form_horizontal" action="" method="post" enctype="multipart/form-data" >
{% csrf_token %}
{% include 'retest/form-template.html' %}
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button type="submit" class="btn btn-success">Submit</button>
</div>
</div>
</form>
If you want to set the boolean field to true, when the form is submitted, you just have to handle it in the view.
Submit the form and before saving it into the database just set the is_rep = true.
is_rep is a field which is in the model, but not used in the form.
So, if you want to change that then you have to manually write a view for it. Try to use base view instead of generic views to understand the workflow of the views and forms.
I'd recommend using something like this:
class RetestView(View):
def get(self, request, *args, **kwargs):
..............
return render(request, self.template, {"some_context"}
def post(self, request, *args, **kwargs):
form_data = your_form(request.POST)
if form_data.is_valid():
new_object = form_data.save(commit=False)
new_object.is_rep = True
new_object.save()
return render(request, self.template, {"some...context"})
Hope you got what you were looking for..!
form_template
{% for field in form %}
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<span class="text-danger small">{{ field.errors }} </span>
</div>
<label class="control-label col-sm-2">{{ field.label_tag }} </label>
<div class ="col-sm-12">
<div class="form-control">
{{ field }}</div></div>
</div>
{% endfor %}
I have a template form and trying to save some data. Upon clicking on the submit button the page just refreshes and nothing gets saved to the database. I don't get any errors on anything.
template
<form action="" method="post" id="salesform">
{% csrf_token %}
<input type="name" class="form-control" id="name" placeholder="Name">
<input type="clinic" class="form-control" id="clinic_name" placeholder="Clinic">
<input type="phone" class="form-control" id="phone" placeholder="Phone">
<input type="email" class="form-control" id="email" placeholder="Email">
<button id="sub" type="submit" class="btn btn-default">Submit</button>
</form>
forms.py
class LeadForm(forms.ModelForm):
name = forms.CharField(max_length=250, required= True,widget=forms.TextInput())
clinic_name = forms.CharField(max_length=250, required= True,widget=forms.TextInput())
phone = forms.CharField(max_length=8, required= True,widget=forms.TextInput(attrs={'type':'number'}))
email = forms.CharField(max_length=250, required= False, widget=forms.TextInput())
class Meta:
model = Lead
fields = ("clinic_name","phone")
views.py
def add_doc_info(request):
d = getVariables(request,dictionary={'page_name': "Doctors",
'meta_desc' : "Sign up "})
if request.method == "POST":
SalesForm = LeadForm(request.POST)
if SalesForm.is_valid():
name = SalesForm.cleaned_data['name']
clinic_name = SalesForm.cleaned_data['clinic_name']
phone = SalesForm.cleaned_data['phone']
email = SalesForm.cleaned_data['email']
#Saving to database
lead = Lead(name=name, clinic_name=clinic_name, phone=phone, email=email)
lead.save()
else:
SalesForm = LeadForm()
return render(request, 'm1/add_doc_info.html', d, context_instance=RequestContext(request))
models.py
class Lead(models.Model):
name = models.CharField(max_length=1300)
clinic_name = models.CharField(max_length=1300)
phone = models.IntegerField()
email = models.EmailField(blank = True)
submitted_on = models.DateField(auto_now_add=True)
def __unicode__(self):
return u"%s %s" % (self.clinic_name, self.phone)
Almost certainly the form is not valid, but you're not using it in your template so there is no way for it to display errors, or redisplay itself with partially-filled fields.
The Django documentation is fairly explicit on this, so I don't know why you have done something different. Pass the form into your context:
d['form'] = SalesForm
return render(request, 'm1/add_doc_info.html', d)
and use it in the template:
{{ form.errors }}
<form action="" method="post" id="salesform">
{% csrf_token %}
{{ form.name }}
{{ form.clinic_name }}
{{ form.phone }}
{{ form.email }}
<button id="sub" type="submit" class="btn btn-default">Submit</button>
</form>
(Note also you've unnecessarily defined all the fields explicitly in the form, but also stated you are only using two of them in the meta class; also your is_valid block is mostly unnecessary as you can just call form.save() directly. Again, all this is shown fully in the documentation.)