django user profile upload image - django

this is my model
my user model
this is my modelform
i imported the user model
the view
and the template
i dont know what am doing wrong am new to django

You just need to fix the view and the template here:
In view:
#login_required
def profile(request):
form = UpdateProfile()
return render(request, 'explore/profile.html', {"form":form})
In template:
<form method="post" enctype="multipart/form-data">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Upload</button>
</form>
Please check here for more details.

Related

django form populate multiple identical field form in one submit

I don't want to use django form class as they will not give me much flexibility.
I have a form where will random number field in easy request. i am trying to populate the multiple value of forms that appears.
this is my models.py
class Profile(models.Model):
name = models.CharField(max_length=100)
photo = models.FileField()
and this my form.html
<form method="POST" action="{% url 'form' %}">
{% csrf_token %}
{% for i in range %}
<input type="text" id="name" name="name"><br>
<input type="file" id="photo" name="photo"><br><br>
{% endfor %}
<input type="submit" value="Submit">
</form>
You may notice I am rendering field with for loop.
that is means, there will be as much field as possible can be appear based on user request.
So I want to populate these models.
my view looks like
def form_view(request):
if request.method == 'POST':
# Need to puplate the form
return render(request, 'form.html', {'range': range(40)})
Can anyone please help me how can i achieve this? i am just struggling to achieve this.
you can use modelformset_factory for this. this way,
in your views.py
from .models import Profile
from django.forms import modelformset_factory
def form_view(request):
form_range = 40 # set the range here
ProfileFormSet = modelformset_factory(Profile, fields=("name", "photo"), extra=form_range, max_num=form_range)
formset = ProfileFormSet(request.POST or None)
if request.method == "POST":
if formset.is_valid():
formset.save()
return render(request, "form.html", {"profile_formset": formset})
and in your form html
<form method="POST" action="{% url 'form' %}">
{% csrf_token %}
{{ profile_formset.as_p }}
<input type="submit" value="Submit">
</form>

Custom Form Field Render using UpdateView not Saving Data

I am trying to use custom HTML to render form field elements. However, now the data is not saving. The data is saving if I use the default form.as_p method.
Related template:
<!--DOES NOT SAVE DATA-->
<form action="" method="post" enctype="multipart/form-data">
{% csrf_token %}
{{ form.description }}
<input type="submit" value="Update"/>
</form>
<!--SAVES DATA-->
<form action="" method="post" enctype="multipart/form-data">
{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Update"/>
</form>
Related UpdateView:
class ProfileEditView(UserPassesTestMixin, UpdateView):
model = Profile
form_class = ProfileCreateForm
template_name = 'update_profile_backup.html'
def get_success_url(self):
return reverse('profile', kwargs={'pk': self.object.pk})
def test_func(self):
obj = self.get_object()
print(obj.user == self.request.user)
return obj.user == self.request.user
Related ModelForm:
class ProfileCreateForm(forms.ModelForm):
class Meta:
model = Profile
fields = 'platform', 'content_niche', 'youtube_channel_id', 'description','profile_img', 'v_id_0', 'v_id_0_title', 'v_id_0_desc', \
'v_id_1', 'v_id_1_title', 'v_id_1_desc', 'v_id_2', 'v_id_2_title', 'v_id_2_desc'
Is it because the custom render method is not validating the form data? If so, how would I do that with an updateview?

linking updateview form with template form in django

I want to have CreateView and UpdateView form on the same page but update form is displayed only when edit button is pressed which is also on the same page
but the problem is when edit button is pressed it is redirected to update view(ie same page) if the URL of updateView is linked to the button and if I don't link the updateView to the button then the form is not auto-filed to be update. what is its solution?
class stock_add_view(CreateView):
model = part_stock
fields = ['part_id','entry_date','supplier','amount','remaining']
success_url = reverse_lazy('parts:part_list')
class stock_update_view(UpdateView):
model = part_stock
fields = ['part_id','entry_date','supplier','amount','remaining']
success_url = reverse_lazy('parts:part_list')
template_name = 'part_detail.html'
URL pattern
url(r'^add_stock$',views.stock_add_view.as_view(),name='stock_add_view'),
url(r'^update_stock/(?P<pk>\d+)/$',views.stock_update_view.as_view(),name='stock_update_view'),
Template: part_detail.html
<script type="text/javascript">
$(function () {
$('.edit_btn').on('click',pop_up);
function pop_up() {
alert("hi")
$('#update_form').show();
}
})
</script>
<div>//add form
<form method="post" action="{% url 'parts:stock_add_view'%}">
{% csrf_token %}
{{ form.as_p }}
<input type="submit">
</form>
</div>
<div style="display: none;" id="update_form">//update form
<form method="post" action="{% url 'parts:stock_update_view' stock.id%}">
{% csrf_token %}
{{ form.as_p }}
<input type="submit">
</form>
</div>
//edit button
<button type="button" class="edit_btn" data-id="{{ stock.id }}">Edit</button>
Since you're using the same fields for both forms, instead of two Class based Views , just use one that extends a FormView and use the update_or_create method
class stock_add_view(FormView):
model = part_stock
template_name = 'part_detail.html'
success_url = reverse_lazy('parts:part_list')
def form_valid(self, form):
part_stock.objects.update_or_create(
'part_id': form.cleaned_data["part_id"]
defaults={
'entry_date': form.cleaned_data["entry_date"],
'supplier': form.cleaned_data["supplier"],
'amount': form.cleaned_data['amount'],
'remaining':form.cleaned_data['remainig'],
}
)
return render(self.request, self.template_name, {'form': form})
This means that django will look for an object with id=part_id,if it exists, it will be updated else it will be created, with data in the default's dict

Django - How do form template tags work?

This is a simple question, but I can't find the answer. The django docs show the following example for calling a form in template just using {{ form }}:
<form action="/your-name/" method="post">
{% csrf_token %}
{{ form }}
<input type="submit" value="Submit" />
</form>
This doesn't fully explain how the {{ form }} tag in the template works if I'm not missing something.
I have my some snippets of my code here which show the problem I'm having with my form tag which currently returns blank:
forms.py
class addtaskForm(forms.ModelForm):
task_name = forms.CharField(label='task_name')
priority = forms.ChoiceField(choices=PRIORITY_CHOICES)
views.py
def add_task(request):
if request.method == "POST":
return HttpResponse("works!")
urls.py
url(r'^add_task/$', 'todo.views.add_task', name='add_task')
tasks.html
<form id="add_task" action="/add_task/" method="post">
{% csrf_token %}
{{ add_task_form }}
<input type="submit" value="submit">
</form>
The {{add_task_form}} is just a guess.
{{ form }} is not a template tag, it is a context variable. By default Form instances are rendered using the Form.as_table() method. So you have to pass such variable to the template in the render() call:
from django.shortcuts import render
def add_task(request):
if request.method == "POST":
form = addtaskForm(request.POST)
if form.is_valid():
# do something useful and redirect
else:
form = addtaskForm()
return render(request, 'tasks.html', {'add_task_form': form})
I suggest you to carefully read the full explanation of the forms in the Working with forms chapter of the django documentation.

How to generate a form in Django like in the admin?

I'm using the app geoposition and when I enter in the admin I can see a form like this one:
http://i.imgur.com/kb3Fqm3.png
This is the repo of the app that I'm using: https://github.com/philippbosch/django-geoposition
When I create the form it appears empty in the browser, this my code:
views.py
from geoposition.forms import GeopositionField
def add_route(request):
form = GeopositionField()
args = {}
args = dict(form=form)
return render_to_response("gestion/add_route.html", args)
add_route.html
<form method="POST" action="">{% csrf_token %}
{{ form.media }}
{{ form.as_p }}
</form>
How I can solve it?
views.py
from django import forms
from geoposition.forms import GeopositionField
from django.shortcuts import render_to_response
class TestForm(forms.Form):
geo_position_field = GeopositionField()
def add_route(request):
form = TestForm(request.POST)
return render_to_response("gestion/add_route.html", {'form': form})
add_route.html:
<form method="POST" action="">
{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Submit">
</form>
also you can use this document to know more about django forms basics.