Django : form is not saved into my database -
altough form send offer correctly displayed , have no error when submitting offers, not saved in database. know checking admin site, no objects saved. on other hand, have written code registration , users saved in database.
i suspect foreignkey relation between 2 models culprit.
models.py
from django.db import models class user(models.model): username = models.charfield(max_length=30, unique=true, blank=false) password1 = models.charfield(max_length=40, blank=false) password2 = models.charfield(max_length=40, blank=false) mail = models.emailfield(unique=true, blank=false) birthday = models.datefield(blank=false) date = models.datetimefield(auto_now_add=true, auto_now=false, verbose_name="date d'inscription") def __str__(self): return self.username class offer(models.model): publisher = models.foreignkey(user) content = models.textfield() date = models.datetimefield(auto_now_add=true, auto_now=false, verbose_name="date de parution") def __str__(self): return self.publisher.username
forms.py
from django import forms django.contrib import admin django.contrib.auth.hashers import make_password, check_password django.utils.translation import ugettext_lazy _ myuser.models import user, offer class usercreationform(forms.modelform): class meta: model = user widgets = { 'password1' : forms.passwordinput(), 'password2' : forms.passwordinput(), } fields = ("username", "password1", "password2", "mail") def clean_password2(self): # check 2 password entries match password1 = self.cleaned_data.get("password1") password2 = self.cleaned_data.get("password2") if password1 , password2 , password1 != password2: raise forms.validationerror("les mots de passes ne correspondent pas") return password2 def save(self, commit=true): # save provided password in hashed format user = super(usercreationform, self).save(commit=false) user.password1 = make_password(self.cleaned_data["password1"]) user.password2 = make_password(self.cleaned_data["password2"]) if commit: user.save() return user class loginform(forms.form): username = forms.charfield(label="nom d'utilisateur") password = forms.charfield(label="mot de passe", widget = forms.passwordinput) def clean(self): cleaned_data = super(loginform, self).clean() username = cleaned_data.get('username') password = cleaned_data.get('password') user = user.objects.get(username=username) if check_password(password, user.password1): return cleaned_data else: raise forms.validationerror("le nom d'utilisateur et le mot de passe ne correspondent pas") class sendofferform(forms.modelform): class meta: model = offer fields = ('content',)
views.py
from django.shortcuts import render django.http import httpresponseredirect, httpresponse django.core.exceptions import objectdoesnotexist myuser.models import user, offer myuser.forms import usercreationform, loginform, sendofferform def get_logged_user_from_request(request): if 'logged_user_id' in request.session: logged_user_id = request.session['logged_user_id'] return user.objects.get(id=logged_user_id) else: return none def register(request): registered = false if request.method == 'post': user_form = usercreationform(data=request.post) if user_form.is_valid(): user = user_form.save() registered = true else: print(user_form.errors) else: user_form = usercreationform() return render(request, 'myuser/create_account.html', {'user_form': user_form, 'registered': registered} ) def login(request): if request.method=='post': form = loginform(request.post) try: if form.is_valid(): user = user.objects.get(username=request.post.get('username')) logged_user = user.objects.get(username=request.post.get('username')) request.session['logged_user_id'] = logged_user.id return httpresponseredirect('/') else: error = "le nom d'utilisateur et le mot de passe ne correspondent pas" return httpresponse("invalid login details supplied.") except user.doesnotexist: return httpresponse("invalid login details supplied.") else: form = loginform return render(request, 'myuser/mylogin.html', locals()) def send_offer(request): sent = false logged_user = get_logged_user_from_request(request) if logged_user: if request.method == 'post': try: offerform = sendofferform(request.post, instance=logged_user) if offerform.is_valid(): sent = true offerform.save() else: print(offerform.errors) except: return httpresponse("drapeau except") else: offerform = sendofferform(instance=logged_user) else: return httpresponse("vous n'ĂȘtes pas connectĂ©") return render(request, 'myuser/send_offer.html', locals())
urls.py
from django.conf.urls import patterns, url, include django.views.generic import templateview urlpatterns = patterns('myuser.views', url(r'^inscription/$', 'register', name='create_account'), url(r'^connexion/$', 'login', name='login'), url(r'^envoyer_une_offre$', 'send_offer', name='send_offer'), )
send_offer.html
{% extends "base.html" %} {% block content %} <h1> offer </h1> {% if not sent %} <p> write offer <p/> <form action="{% url "send_offer" %}" method='post' class='sendofferform'> {{ form.errors }} {{ form.non_field_errors }} {% csrf_token %} {{ offerform.as_p }} <input type="submit" value="submit" /> </form> {% else %} offer published <a href="/poster_une_offre">publish offer?</a><br /> <a href="/">get homepage</a><br /> {% endif %} {% endblock %}
admin.py
from django.contrib import admin myuser.models import user, offer#, message class useradmin(admin.modeladmin): list_display = ('id', 'username', 'status', 'college', 'apercu_description') list_filter = ('id', 'username', 'birthday') date_hierarchy = 'date' ordering = ('date', ) search_fields = ('username', 'description') def apercu_description(self, user): text = user.description[0:40] if len(user.description) > 40: return '%s' % text else: return text class offeradmin(admin.modeladmin): list_display = ('id', 'publisher', 'apercu_offre') list_filter = ('id', ) date_hierarchy = 'date' ordering = ('date', ) search_fields = ('publisher',) def apercu_offre(self, offer): text = offer.content[0:40] if len(offer.content) > 40: return '%s' % text else: return text admin.site.register(user, useradmin) admin.site.register(offer, offeradmin)
all of other function works (register , login) , register() function correctly saves user send_offer() function, similar register function doesn't work , after searching on internet hours, still have no idea why offers not saved.
but when try add offer in admin site, seems work.
besides, tried save offer in python manage.py shell :
>>> offer.publisher = "a" >>> offer.content = "lalalala" >>> offer.save() traceback (most recent call last): file "/usr/local/lib/python3.4/dist-packages/django/core/management/commands/shell.py", line 69, in handle self.run_shell(shell=options['interface']) file "/usr/local/lib/python3.4/dist-packages/django/core/management/commands/shell.py", line 61, in run_shell raise importerror importerror during handling of above exception, exception occurred: traceback (most recent call last): file "/usr/lib/python3.4/code.py", line 90, in runcode exec(code, self.locals) file "<console>", line 1, in <module> typeerror: save() missing 1 required positional argument: 'self'
edit : solution add these lines :
if offerform.is_valid(): sent = true offer = offerform.save(commit=false) offer.publisher = user.objects.get(id=logged_user.id) offer.save()
please, note logged_user function, described in view.py.
on modelform if don't pass object when instantiated create new object in database of specified type. in case on sendofferform have specified offer. if pass existing object has specified type in case offer.
it looks trying automatically fill publisher field logged in user. in order need manually set publisher field instance of user.
if intend form create new offer in database this
offerform = sendofferform(request.post)
if trying update current offer need pass instance object form
offerform = sendofferform(request.post, instance=someoffer)
to manually add user field call save on form commit=false return offer object without saving db. @ point have chance customize data in object , save.
offer = offerform.save(commit=false) offer.publisher = request.user.id offer.save()
all of explained in more detail in django documentation modelform documentation
Comments
Post a Comment