How to Save Currently Logged in User to Model in Django - django-users

I am trying to get the currently logged in User and save it to a model. I am getting the following error
"Cannot assign "<SimpleLazyObject: <User: rsomani005>>": "process_master.user" must be a "User" instance"
I am using Django's built in user model.
My model looks like this -
class User(auth.models.User,auth.models.PermissionsMixin):
def __str__(self):
return "#{}".format(self.username)
class plan_master(models.Model):
plan_name = models.CharField(max_length=256)
plan_description = models.CharField(max_length=256)
plan_price = models.FloatField()
plan_active_status = models.BooleanField(default=True)
plan_credits = models.IntegerField(default=0)
registration_type_name = models.CharField(max_length=50)
My view file looks like this -
class FileFieldView(LoginRequiredMixin,FormView):
form_class = FileFieldForm
template_name = 'merge_ops/merge_ops.html'
success_url = reverse_lazy('merge_ops:file_setup')
def post(self, request, *args, **kwargs):
form_class = self.get_form_class()
form = self.get_form(form_class)
files = request.FILES.getlist('file_field')
if form.is_valid():
for f in files:
fs = FileSystemStorage()
fs.save(f.name,f)
obj = process_master()
user = request.user
obj.user = user
obj.process_date = datetime.now()
obj.number_of_workbooks = len(files)
obj.save()
return self.form_valid(form)
else:
return self.form_invalid(form)

An easy way to get the logged user in one of your views is:
user = request.user
but that is usually when the user model that you have created is something like that in the model.py:
from django.contrib.auth.models import AbstractUser
from django.db import models
class User(AbstractUser):
pass
I would suggest using this one to register users because it is automatic and complete.
and from there use the object for what you need. You can pass it on as a context or
source model objects from it.

Related

I am trying to bind my FormView to show the Form in djangocms but i am not able to

I am trying to bind my FormView to show the Form in djangocms but I am not able to,
my model is:
class ContactFormView(FormView, CMSPlugin):
template = '/ContactForm/ContactForm.html'
form_class = contact_form
success_url = reverse_lazy('success-page')
def post(self, request, **kwargs):
assert request.is_ajax()
request_data = json.loads(request.body)
form = self.form_class(data=request_data[self.form_class.scope_prefix])
if form.is_valid():
return JsonResponse({'success_url': force_text(self.success_url)})
else:
response_data = {form.form_name: form.errors}
return JsonResponse(response_data, status=422)
cms_plugins.py:
class ContactFormPlugin(CMSPluginBase):
model = ContactForm.ContactFormView
render_template = '/ContactForm/ContactForm.html'
name = 'Contact Form'
allow_children = False
plugin_pool.register_plugin(ContactFormPlugin)
Looking at what you've got there, I'm not sure you've given your plugin a proper model but a view!? And the form class isn't a form class, form_class = contact_form but what is contact_form? You need it to be the class of your form e.g.
class ContactForm(forms.Form):
name = forms.CharField(label='Your name', max_length=100)
email = forms.EmailField(label='Your email', max_length=100)
class ContactFormView(FormView):
template = '/ContactForm/ContactForm.html'
form_class = ContactForm
success_url = reverse_lazy('success-page')
And if you've got a form you want your plugin to render, you need to tell it what to do...
from cms.models.pluginmodel import CMSPlugin
class ContactFormPlugin(CMSPluginBase):
model = CMSPlugin
render_template = '/ContactForm/ContactForm.html'
name = 'Contact Form'
allow_children = False
def render(self, context, instance, placeholder):
context = super(ContactFormPlugin, self).render(context, instance, placeholder)
context['form'] = ContactForm()
return context
However you're working with a CMS plugin, so you don't define a View at all for a plugin. I think you could make this do what you're trying to do but the view doesn't want to inherit CMSPlugin because you just want a view to receive data from the plugin.
If you need to define views then you're building an app which in CMS requires an Apphook, not a plugin. (Technically you could post to a URL without an Apphook, but depends how much CMS integration you want)
There is a great example that starts with a plugin posting to a view then progresses into the app integration which is possible here; http://docs.django-cms.org/en/latest/introduction/plugins.html

Plone: Add additional registration fields to users (members)

I have two additional fields for my group objects (like described here).
Now I need (other) additional fields for my member objects as well (short strings). I have created them in portal_memberdata/manage_propertiesForm, but I still can't select them for registration form usage (##member-registration).
I need the two new fields for registration, at least one of them mandatory. How can I achieve this? Thank you!
Update:
I found plone.app.users.userdataschema and added my fields to the interface IUserDataSchema; furthermore, I monkeypatched plone.app.users.browser.personalpreferences.UserDataPanelAdapter. There still seems to be missing something (no change visible in ##member-registration).
My customization code looks like this:
from plone.app.users.userdataschema import IUserDataSchema
from zope import schema
from Products.CMFPlone import PloneMessageFactory as _
IUserDataSchema.custom1 = schema.ASCIILine(
title=_(u'label_custom1',
default=u'Custom1 member id'),
description=_(u'help_custom1_creation',
default=u'Custom1 membership is required; '
u'please enter your member id'),
required=True)
from plone.app.users.browser.personalpreferences import UserDataPanelAdapter
def set_custom1(self, value):
if value is None:
value = ''
return self.context.setMemberProperties({'custom1': value})
def get_custom1(self):
return self._getProperty('custom1')
UserDataPanelAdapter.custom1 = property(get_custom1, set_custom1)
It didn't work when I used the monkeypatched original interface class;
but it does work to monkeypatch the UserDataSchemaProvider to return a subclass:
from plone.app.users.userdataschema import IUserDataSchema
from plone.app.users.userdataschema import UserDataSchemaProvider
from zope import schema
from Products.CMFPlone import PloneMessageFactory as _
class IUserDataSchemaExtended(IUserDataSchema):
"""
Extends the userdata schema
by a mandatory field
"""
customField1 = schema.ASCIILine(
title=_(u'label_customField1',
default=u'CustomField1 member id'),
description=_(u'help_customField1_creation',
default=u'CustomField1 membership is required; '
u'please enter your member id'),
required=True)
def getExtendedSchema(self):
return IUserDataSchemaExtended
UserDataSchemaProvider.getSchema = getExtendedSchema
from plone.app.users.browser.personalpreferences import UserDataPanelAdapter
def set_customField1(self, value):
if value is None:
value = ''
return self.context.setMemberProperties({'customField1': value})
def get_customField1(self):
return self._getProperty('customField1')
UserDataPanelAdapter.customField1 = property(get_customField1, set_customField1)
Remarks:
It might be better to simply use customField1 for the translatable title instead of label_customField as the name the field is used when the registration page is quickedited
with Plone 5, it apparently is possible to configure additional userdata fields via XML

getting webapp2 session id

How to get a session id in webapp2?
It doesn't seem to be documented anywhere and it wasn't trivial to me.
I have found some solution, which I present in the answer to this question, but maybe somebody will find simpler or better one.
Anyway I think that this can be useful to somebody
My solution looks like this:
import webapp2
from webapp2_extras import sessions
class Test(webapp2.RequestHandler):
def get(self):
session_store = sessions.get_store(request=self.request)
cookie_name = session_store.config['cookie_name']
session_id = self.request.cookies[cookie_name]
self.response.out.write('<html><body>')
self.response.out.write('Session id: %s' % session_id)
self.response.out.write("</body></html>")
In your example, you can't get the session id, until you refresh the page. You should make an authenticate page to create the session. Also you should define a base handler that extends the dispatch() method to start the session store and save all sessions at the end of a request. Read the documentation See an example:
class Main(main.BaseHandler):
def get(self):
if not self.session.get('user'):
self.redirect("/authenticate",abort=True)
session = self.request.cookies("session")
#more stuff........
class Authenticate(main.BaseHandler):
def get(self):
if self.session.get('user'):
self.redirect("/")
else:
self.render("authenticate.htm")
def post(self):
if self.session.get('user'):
self.redirect("/",abort=True)
post_param = {"username":self.request.get("username"),
"password":self.request.get("password")}
if not post_param["password"] or not post_param["username"]:
redirect("/authenticate")
mySql = dbLib.MySqlLib()
try:
mySql.query("SELECT password FROM users where username=%s", post_param["username"],))
dbPassword = mySql.dbCur.fetchone()[0]
except dbLib.ProgrmmgError as error:
self.render("authenticate.htm",username = post_param["username"],
errorMessage = "Password and/or Username\
else: invalid")
if bcrypt.hashpw(post_param["password"],dbPassword) == dbPassword:
self.session['user'] = "root"
self.redirect("/")
else:
self.render("authenticate.htm",username = post_param["username"],
errorMessage = "Password and/or Username\
mySql.close()
app = main.webapp2.WSGIApplication([('/', Main),
("/authenticate",Authenticate),
(".*",main.Error_404)],
debug=True)

Table creation fails with SqlAlchemy and Pylons

I just upgraded to Pylons 1.0 and SqlAlchemy 0.6.5. What was a simple process of creating the DB schema no longer works.
I have a simple model:
Base = declarative_base()
class User(Base):
__tablename__ = 'user'
id = Column(Integer, primary_key=True)
user_name = Column(String)
def __init__(self, userName):
self.userName = userName
def __repr__(self):
return "<User('%s')>" % (self.userName)
When I run
paster setup-app development.ini
the database file is created (sqlite3), but not the table, and no errors are returned.
Logging shows that the following lines in websetup.py do execute:
log.info("Creating schema...")
Base.metadata.create_all(bind = Session.bind, checkfirst = True)
log.info("Database successfully set up.")
What am I missing?
Edit: Further digging shows that the Base.metadata.tables dictionary is empty. So, why isn't the model reflected in the metadata?
Ok, I found the issue.
In model.meta.py, Base = declarative_base() was already performed. When I also added that statement to the model.__init__.py, it evidently creates a new instance without the metadata, so there were no tables to create.
I'm not clear on exactly why/how this works, so if anyone (Mike Bayer?) has details, I would love to know.

relating models to one another using generic views

I'm new to Django and programming in general. I'm trying to make a simple site that allows players of a sport sign up for leagues that have been created by the admin. In my models.py, I created two models:
from django.db import models
from django.forms import ModelForm
class League(models.Model):
league_name = models.CharField(max_length=100)
pub_date = models.DateTimeField('date published')
class Info(models.Model):
league = models.ManyToManyField(League)
name = models.CharField(max_length=50)
phone = models.IntegerField()
email = models.EmailField()
def __unicode__(self):
return self.info
class InfoForm (ModelForm):
class Meta:
model = Info
exclude = ('league')
From what I've read, I can probably use the Create/Update/Delete generic views to display a form for the user to sign up for the league. So with my app, I want the user to come to a simple homepage that lists the leagues, be able to click on the league and enter their info to sign up. Here's what my urlconf looks like:
from django.conf.urls.defaults import *
from mysite.player_info.models import League, Info, InfoForm
info_dict = {
'queryset': League.objects.all(),
}
InfoForm = {'form_class' : InfoForm}
urlpatterns = patterns('',
(r'^$', 'django.views.generic.list_detail.object_list', info_dict),
(r'^(?P<object_id>\d+)/$', 'django.views.generic.list_detail.object_detail', info_dict),
url(r'^(?P<object_id>\d+)/results/$', 'django.views.generic.list_detail.object_detail', dict(info_dict, template_name='player_info/results.html'), 'league_results'),
(r'^(?P<object_id>\d+)/info/create/$', 'django.views.generic.create_update.create_object', InfoForm),
)
Here's my problem: When I click on a league to sign up for on the homepage with my current setup, I get this error: TypeError at /league/1/info/create.... create_object() got an unexpected keyword argument 'object_id'. What am I doing wrong?
The issue isn't with your models, but rather with the function your "create" URL calls -- the line that calls django.views.generic.create_update.create_object() in urls.py. create_object() doesn't take an object_id argument, but you specified one in your url (r'^(?P<object_id>\d+)/info/create/$'). This makes sense -- you're creating an object, so you don't know its ID yet. create_object() only takes a form_class or model argument, as noted in the docs.
I'm guessing you're trying to create an Info object that is attached to a League object, and in that URL, <object_id> is the ID number of the League object; in which case, you shouldn't name that ID number, and instead should just use r"^\d+/info/create/$" as the URL. I'm not sure how you'll grab the league ID number using Django's create_object() function, though. You might have to write your own view handler. You may be able to use a custom ModelForm and pass it in with the form_class parameter, but I'm not sure.

Resources