I have Model:
models.py
class UserProfile(models.Model):
user = models.OneToOneField(User, related_name='userprofile')
points = models.IntegerField(default=0)
urls.py
urlpatterns = [
url(r'^$', demo),
url(r'^demo/$', demo),
]
demo.html
<form action="" method="POST">
<button type="submit">+</button>
</form>
views.py
def demo(request):
if request.method == "POST":
# I don't understand how I can get "points" from the model "UserProfile"
#to add 1 and to save in the DB
return render(request, 'app/demo.html')
I would like that after pressing on the button points of the user increased one. I really cannot figure it out.
Try something like this
def demo(request):
if request.method == "POST":
profile = UserProfile.objects.get(user=request.user)
profile.points += 1
profile.save()
return render(request, 'app/demo.html', {"user":request.user,
"profile":profile)
Related
i am new in Django. i am having issue in updating ImageField.i have following code
in models.py
class ImageModel(models.Model):
image_name = models.CharField(max_length=50)
image_color = models.CharField(max_length=50)
image_document = models.ImageField(upload_to='product/')
-This is My forms.py
class ImageForm(forms.ModelForm):
class Meta:
model = ImageModel
fields = ['image_name', 'image_color' , 'image_document']
in Html file (editproduct.html)
<form method="POST" action="/myapp/updateimage/{{ singleimagedata.id }}">
{% csrf_token %}
<input class="form-control" type="text" name="image_name" value="{{ singleimagedata.image_name}}">
<input class="form-control" type="file" name="image_document">
<button type="submit" class="btn btn-primary">UPDATE PRODUCT</button>
</form>
-myapp is my application name. {{singleimagedata}} is a Variable Containing all fetched Data
-urls.py
urlpatterns = [
path('productlist', views.productlist, name='productlist'),
path('addproduct', views.addproduct, name='addproduct'),
path('editimage/<int:id>', views.editimage, name='editimage'),
path('updateimage/<int:id>', views.updateimage, name='updateimage'),
]
and Here is My views.py
def productlist(request):
if request.method == 'GET':
imagedata = ImageModel.objects.all()
return render(request,"product/productlist.html",{'imagedata':imagedata})
def addproduct(request):
if request.method == 'POST':
form = ImageForm(request.POST, request.FILES)
if form.is_valid():
form.save()
messages.add_message(request, messages.SUCCESS, 'Image Uploaded')
return redirect('/myapp/productlist')
else:
imageform = ImageForm()
return render(request, "product/addproduct.html", {'imageform': imageform})
def editimage(request, id):
singleimagedata = ImageModel.objects.get(id=id)
return render(request, 'product/editproduct.html', {'singleimagedata': singleimagedata})
def updateimage(request, id): #this function is called when update data
data = ImageModel.objects.get(id=id)
form = ImageForm(request.POST,request.FILES,instance = data)
if form.is_valid():
form.save()
return redirect("/myapp/productlist")
else:
return render(request, 'demo/editproduct.html', {'singleimagedata': data})
My image Upload is working fine.i can not Update image while updating data.rest of the data are updated.i don't know how to update image and how to remove old image and put new image into directory.
I think you missed the enctype="multipart/form-data", try to change:
<form method="POST" action="/myapp/updateimage/{{ singleimagedata.id }}">
into;
<form method="POST" enctype="multipart/form-data" action="{% url 'updateimage' id=singleimagedata.id %}">
Don't miss also to add the image_color field to your html input.
Because, in your case the image_color field model is designed as required field.
To remove & update the old image file from directory;
import os
from django.conf import settings
# your imported module...
def updateimage(request, id): #this function is called when update data
old_image = ImageModel.objects.get(id=id)
form = ImageForm(request.POST, request.FILES, instance=old_image)
if form.is_valid():
# deleting old uploaded image.
image_path = old_image.image_document.path
if os.path.exists(image_path):
os.remove(image_path)
# the `form.save` will also update your newest image & path.
form.save()
return redirect("/myapp/productlist")
else:
context = {'singleimagedata': old_image, 'form': form}
return render(request, 'demo/editproduct.html', context)
I had a similar issue while updating the profile_pic of user. I solved this with the following code I think this might help:
Models.py
class Profile(models.Model):
# setting o2o field of user with User model
user_name = models.OneToOneField(User, on_delete=models.CASCADE, blank=True, null=True)
first_name = models.CharField(max_length=70, null=True, blank=True)
last_name = models.CharField(max_length=70, null=True, blank=True)
profile_pic = models.ImageField(upload_to="images", blank=True, null=True,)
def __str__(self):
return str(self.user_name)
forms.py
class ProfileEditForm(ModelForm):
class Meta:
model = Profile
fields = '__all__'
# excluding user_name as it is a one_to_one relationship with User model
exclude = ['user_name']
views.py
#login_required(login_url='login')
def edit_profile(request, id):
username = get_object_or_404(Profile, id=id)
extended_pro_edit_form = ProfileEditForm(instance=username)
if request.method == "POST":
extended_pro_edit_form = ProfileEditForm(request.POST, request.FILES, instance=username)
if extended_pro_edit_form.is_valid():
extended_pro_edit_form.save()
next_ = request.POST.get('next', '/')
return HttpResponseRedirect(next_)
context = {'extended_pro_edit_form': extended_pro_edit_form}
return render(request, 'edit_profile.html', context)
edit-profile.html
<form action="" method="post"
enctype="multipart/form-data">
{% csrf_token %}
{{ extended_pro_edit_form.as_p }}
{{ extended_pro_edit_form.errors }}
<!--To redirect user to prvious page after post req-->
<input type="hidden" name="next" value="{{ request.GET.next }}">
<button type="submit">UPDATE</button>
</form>
Answer from #binpy should solve your problem. In addition to your second answer, you could do:
def updateimage(request, id): #this function is called when update data
data = ImageModel.objects.get(id=id)
form = ImageForm(request.POST,request.FILES,instance = data)
if form.is_valid():
data.image_document.delete() # This will delete your old image
form.save()
return redirect("/myapp/productlist")
else:
return render(request, 'demo/editproduct.html', {'singleimagedata': data})
Check delete() method on django docs.
some times something like cached old image is not replaced in the front-end so you might just need to forces refresh by pressing CTRL + F5 or clear your browsing history.
the answer given by #binpy is a needed update so that the files are passed to the back-end.
Help me please to understand how to make the delete button, its must to delete a Cat
class Cat(models.Model):
class Meta():
db_table = "cat"
paw = models.IntegerField(default=4)
name = models.CharField(max_length=30, null=False, default='Cat')
age = models.IntegerField(default=False, null=False)
species = models.CharField(max_length=50, blank=True)
hairiness = models.IntegerField(default=False, null=False)
def __str__(self):
return self.name
This is my views.py, hope you can help. (it's need for my job interview on Monday)
from django.shortcuts import render, get_object_or_404
from .models import Cat
from .forms import CatForm
from django.shortcuts import redirect
def home(request):
template = "base.html"
queryset = Cat.objects.all()
context = {
"object_list": queryset
}
return render(request, template, context)
def new_cat(request):
if request.method == "POST":
form = CatForm(request.POST)
if form.is_valid():
cat = form.save(commit=False)
cat.save()
return redirect('/', pk=cat.pk)
else:
form = CatForm()
return render(request, 'new_cat.html', {'form': form})
def cat_edit(request, pk):
cat = get_object_or_404(Cat, pk=pk)
if request.method == "POST":
form = CatForm(request.POST, instance=cat)
if form.is_valid():
cat = form.save(commit=False)
cat.save()
return redirect('/', pk=cat.pk)
else:
form = CatForm(instance=cat)
return render(request, 'new_cat.html', {'form': form})
site is asc to addd more details, but i just don't know what else, i can add.
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.home, name='home'),
url(r'^new/$', views.new_cat, name='new_cat'),
url(r'^edit/(?P<pk>[0-9]+)/$', views.cat_edit, name='cat_edit'),
]
At first, you should create a cat_delete view, which should look something like this:
def cat_delete(request, pk):
cat = get_object_or_404(Cat, pk=pk) # Get your current cat
if request.method == 'POST': # If method is POST,
cat.delete() # delete the cat.
return redirect('/') # Finally, redirect to the homepage.
return render(request, 'template_name.html', {'cat': cat})
# If method is not POST, render the default template.
# *Note*: Replace 'template_name.html' with your corresponding template name.
Then, you should map this view in your urls.py:
from django.conf.urls import url
from . import views
app_name = 'cats'
# Note that app_name is added here!
# It is used as a namespace in order to reverse your urls better.
# See usage in template.
urlpatterns = [
# ...
url(r'^delete/(?P<pk>[0-9]+)/$', views.cat_delete, name='cat_delete')
]
In your template, you should create a form with delete button, which will simply send a POST request to the delete view:
<form action="{% url 'cats:cat_delete' cat.id %}" method="post">
{% csrf_token %}
<input type="submit" value="Delete cat">
</form>
Look closely on the form's action:
{% url 'cats:cat_delete' cat.id %}
Here I am using the app_name from urls.py that I previously added in order to resolve your urls by name, not by path. Now cats:cat_delete will evaluate to cats/delete/<pk>. And of course you pass the cat.id.
This should do the trick with deleting instance of your Cat model. Hope I helped.
I am trying to create a frontend form in my Django site that will allow users to add entries to my SQL database.
But when I use the form nothing happens in my database. What am I doing wrong?
I thought the right way would be to use the ModelForm technique.
My models looks like this:
class Actor(models.Model):
name = models.CharField(max_length=200)
wage = models.IntegerField(default=3100)
def __str__(self):
return self.name
So I wrote this in my forms.py:
from django import forms
from .models import Actor
class ActorForm(forms.ModelForm):
class Meta:
model = Actor
fields = ['name', 'wage']
form = ActorForm()
I then added this to my views.py:
def get_actor(request):
if request.method == 'POST':
form = ActorForm(request.POST)
if form.is_valid():
return HttpResponseRedirect('/scenes/thanks/')
else:
form = ActorForm()
return render(request, 'scenes/actor.html', {'form': form})
def thanks(request):
return render(request, 'scenes/thanks.html',)
And this in a template called actors.html
<form action="/scenes/actor/" method="post">
{% csrf_token %}
{{ form }}
<input type="submit" value="Submit" />
You have to call the model form's save() method after checking that it's valid:
def get_actor(request):
if request.method == 'POST':
form = ActorForm(request.POST)
if form.is_valid():
form.save()
return HttpResponseRedirect('/scenes/thanks/')
else:
form = ActorForm()
return render(request, 'scenes/actor.html', {'form': form})
I am trying to create a formset that captures a parameter from the url to prefill one of the fields. The form is displaying correctly and at the correct address, but after clicking "submit" the page redirects to "/correction/" instead of the intended /correction/A07686+dwdID19, and the form does not save. What might be the issue?
In models.py:
class correction(models.Model):
corrected_word = models.ForeignKey(item)
correction_author = models.ForeignKey(User)
correction_made = models.IntegerField(u'correction_made', choices=CORRECTION_CHOICES)
correction_word = models.CharField(u'correction_word', max_length=200, blank=True, null=True)
time = models.DateTimeField(auto_now_add=True)
approved = models.IntegerField(u'approved', choices=APPROVAL_CHOICES, blank=True, null=True)
def __unicode__(self):
return str(self.time)
In views.py:
def submit_corr(request, bdword):
if hasattr(request, 'user') and request.user.is_authenticated():
word = item.objects.filter(file_position=bdword)[0]
CorrFormSet = inlineformset_factory(item, correction, fields=['correction_made', 'correction_word','correction_author'], can_delete=False, extra=1)
form = CorrFormSet(request.POST, request.FILES, instance=word, initial=[{'correction_author': request.user,}])
if request.method == 'POST':
if form.is_valid():
for entry in form:
entry.save()
else:
form = CorrFormSet(instance=word, initial=[{'correction_author': request.user,}])
return render(request, "correctionform.html", {"form": form,"word": word})
In urls:
url(r'^correction/(?P<bdword>.*)$', 'english.views.submit_corr'),
In the template:
Submit correction</th>
Thanks in advance!
Submit correction doesn't submit a form because it's a link and when you press a link, this sends a request with a GET method to the server so never enter to if request.method == 'POST': .
Please try something like
<form action="/correction/{{word.file_position}}" method="POST">
{# your inputs fields#}
<button type="submit">Submit correction</button>
</form>
I hope to be useful. Regards
processor_for.py
from django import forms
from django.http import HttpResponseRedirect
from mezzanine.pages.page_processors import processor_for
from .models import Book
class BookForm(forms.Form):
name = forms.CharField()
email = forms.EmailField()
#processor_for(Author)
def author_form(request, page):
form = BookForm()
if request.method == "POST":
form =BookForm(request.POST)
if form.is_valid():
# Form processing goes here.
redirect = request.path + "?submitted=true"
return HttpResponseRedirect(redirect)
return {"form": form}
models.py
from django.db import models
from time import time
class Book(models.Model):
book_name= models.CharField(max_length=200, unique = True)
def __unicode__(self):
return self.book_name
views.py
def create_book (request):
if request.POST:
form = BookForm(request.POST, request.FILES)
if form.is_valid():
form.save()
return HttpResponseRedirect('/all/')
else:
form = BookForm()
args= {}
args.update(csrf(request))
args['form'] = form
return render_to_response('create_Book.html', args)
urls.py
urlpatterns += patterns('',
url(r'^/xyz/$', create_book))
create_Book.html
<form action="/xyz/" method="post" enctype="multipart/form-data">{% csrf_token %}
{{form.as_ul}}
<input type="submit" name="submit" value="create"/>
</form>
This is what i am doing but still i am unable to access form. Where i am doing wrong. will be grateful to you. Please mark that what's wrong in code?
as per you code and your explanation in question .please see your code in urls.py
urlpatterns += patterns('',
url(r'^xyz/$', create_book)) # you should write like ^xyz/$
Please follow django doc
Two Syntax Problems:
1) Always define your processor name in " " like #processor_for("Author")
2) urls for page processors like :
url("^xyz/$", "mezzanine.pages.views.page", {"slug": "Author"}, name="Author"),