python - How to open a form in editable mode -
models.py
class userprofile(models.model): user = models.onetoonefield(user) phone_daytime = models.charfield(max_length=50, null=true, blank=true) class user(models.model): first_name = models.charfield(max_length=30) last_name = models.charfield(max_length=30) email = models.charfield(max_length=75) password = models.charfield(max_length=75)
views.py
def profile(request): """""" registerform = userregisterform(request.post) createprofileform = usercreateprofileform(request.post) if registerform.is_valid() , createprofileform.is_valid(): result = registerform.save(commit=false) result.set_password(request.post['password']) result.save() member.user_id = user.id member.member_id = result.id member.save() member_profile = userprofile.objects.get(user=result.id) createprofileform = usercreateprofileform(request.post, instance=member_profile) createprofileform.save() return render(request,'profile.html',{'createprofileform':createprofileform,'registerform':registerform})
view save data database.
template
<tr> <td>first name:</td><td>{{registerform.first_name}}</td> </tr> <tr> <td>last name:</td><td>{{registerform.last_name}}</td> </tr> <tr> <td>daytime phone:</td><td>{{createprofile.phone_daytime}} </td> </tr> <tr> <td>email:</td><td>{{registerform.email}} </td> </tr> <tr> <td>password</td><td>{{registerform.password}} </td> </tr>
the saved name , email id displayed in template this,
<td> <input type="submit" name="delete" value="{{list.0.id}}" class="delete_reporter" /></span> <a href="{{list.0.id}}">{{list.0.first_name|title}} {{list.0.last_name}}</a></td> <td> {{list.0.email}} {{list.1.phone_daytime}} {{list.1.phone_mobile}}</td>
in template,if click <a href="{{list.0.id}}">{{list.0.first_name|title}} {{list.0.last_name}}</a>
form should open in editable mode,so if want make changes can change , save again.how in django.i passing id in <a>
tag.
if understand correct want have kind of data, can edited , saved. can achive of forms. here's example:
define form:
class basicform(forms.form): name = forms.charfield() age = forms.integerfield()
then, in views define logic , provide initial data form:
def update_view(request): initial_data = {'name': 'john', 'age': 25} form = basicform(initial_data) if request.method == 'post': form = basicform(request.post) if form.is_valid(): # passed data, example update existing model. pass return render(request, 'template.html', {'form': form})
if want update models in database can provide initial data this:
from django.forms.models import model_to_dict model = model.objects.get(name='john') initial_data = model_to_dict(model, exclude=['field_name']) form = basicform(initial_data) if request.method == 'post': form = basicform(request.post) if form.is_valid(): # update "john" model model.name = form.cleaned_data['name'] model.age = form.cleaned_data['age'] model.save()
Comments
Post a Comment