I'm using Flask-peewee, looking for a way to give permission to admins, I'd like to make a multi tenancy admin dashboard.
I have made for displaying deals:
class DealsAdmin(ModelAdmin):
columns = ('deal_name', 'deal_desc', 'created_on')
exclude = ('created_on','merchand_id')
def get_query(self):
loggedin_username=auth.get_logged_in_user()
merchant=Merchant.select().where(Merchant.id == loggedin_username).get()
return self.model.select().where(self.model.merchand_id == loggedin_username)
So now I'd like to keep the loggedinuserid for Merchant id when they want to edit forms.
*Edit on image text: Merchant_id must be the auth.loggedinid as default
Remove the field from being displayed in the form, then hook into on_model_change:
class MyDealModelView(ModelView):
form_excluded_columns = ('merchant_id',)
def on_model_change(form, model, is_created):
model.merchant_id = login.current_user.merchant_id;
http://flask-admin.readthedocs.org/en/latest/api/mod_model/#flask.ext.admin.model.BaseModelView.on_model_change
Related
I have a Model which consists of almost 500+ fields. I want to take data through the front-end Form. But the issue is I can’t display all the 500 fields.
what I want is I will add the fields which I need. like on day-1 I will add 3 fields. food = 230 , petrol = 500, rent = 700. on the second day, fields may vary. I can add 20 fields on the second day. on the third day data may be of different fields. like petrol = 200, cement= 5000 , steel = 100 etc etc and so on!
Simple Solution is: I displayed all fields in HTML and submitted it to view and received in View function through Post Request! and then save() . But i want it to be dynamic!
if request.method == 'POST':
print("this is post")
# print()
food_expense=request.POST['food']
petrol_expense=request.POST['petrol']
easyload_expense=request.POST['easyload']
labour_expense = request.POST['labour']
equipments_expense = request.POST['equipments']
rent_expense = request.POST['rent']
cement_expense = request.POST['cement']
steel_expense = request.POST['steel']
other1_expense = request.POST['other1']
other2_expense = request.POST['other2']
other3_expense = request.POST['other3']
..... .... fields upto 500+
# expense_paidby = request.POST['paid_by']
expense_paidby_id = request.POST['paid_by']
paidby= PaidBy.objects.get(id=expense_paidby_id)
# expense_paidby = PaidBy.objects.get(name__icontains = request.POST['paid_by'])
projectname_id= request.POST['pname']
project_in_which_expenses_made=ProjectName.objects.get(id=projectname_id)
# project_in_which_expenses_made = request.POST['project_name']
date = request.POST['date']
# total = food_expense+petrol_expense+easyload_expense+labour_expense+equipments_expense+rent_expense
# print(petrol_expense, projectname_id , project_in_which_expenses_made)
inst= ProjectExpenses(food=food_expense,petrol=petrol_expense,easyload=easyload_expense ,labour=labour_expense ,
equipments=equipments_expense ,rent=rent_expense,cement=cement_expense,steel=steel_expense,
other1=other1_expense, other2=other2_expense, other3=other3_expense, date_of_expense=date, PaidByName=paidby,
expenses_in_project = project_in_which_expenses_made)
#in query i will have 500 fields.
inst.save()
what I want is how I can create dynamic input fields with name attributes as I have in the database.
how should I create these fields dynamically in the front end and then how I will handle it in view function instead of writing all 500+ fields through “value = request. post[“500+ fields line by line”]” means how I can handle it dynamically only those fields which come to view function. and then save it to DB.
data will only insert in selected fields all remaining will be zero by default.
I will appreciate forum Help.
I am not sure if I understood your question right. Perhaps a more minimal working example would clarify.
But, have you tried using model forms, such as CreateView?
You can dynamically create input forms and handling based on your model definition by adding a CreateView to your urlpatterns.
from django.views.generic.edit import CreateView
from .models import ProjectExpenses
urlpatterns += [path("new-project-expense", CreateView.as_view(model=ProjectExpenses, fields="__all__"))]
You can configure the "fields" argument to be a selection of your 500 model fields.
So within Zendesk I created these custom fields as follows:
and now I am trying to create a user with all these fields filled with preset values. But when I try to create users, like follows:
for row in df.iloc[1:11].fillna(0).iterrows():
user = User(name = row[1].first_name,
email = row[1].email,
lifetime_value = row[1].purchased_total_value,
first_order = row[1].first_purchased,
last_order = row[1].last_purchased,
products_ordered = row[1].purchased_product_count,
total_orders = row[1].purchased_unique_orders,
total_returns = row[1].total_returns,
products_returned = row[1].products_returned,
pro_account = pd.notna(row[1].proaccount_deal),
verified=True)
created_user = zenpy_client.users.create(user)
All users are created however only with email and name fields filled up and all the custom fields which I created are empty. Zenpy's User() function is not very informative in this regard however it accepts **kwargs** and as per json representations in documentation, it should work in theory. Any workaround or my mistakes in this regard?
Have you tried using user_fields?
for row in df.iloc[1:11].fillna(0).iterrows():
uf = {"lifetime_value" : row[1].purchased_total_value,
"first_order" : row[1].first_purchased,
"last_order" : row[1].last_purchased,
"products_ordered" : row[1].purchased_product_count,
"total_orders" : row[1].purchased_unique_orders,
"total_returns" : row[1].total_returns,
"products_returned" : row[1].products_returned,
"pro_account" : pd.notna(row[1].proaccount_deal),
"verified":True}
user = User(name = row[1].first_name, email = row[1].email, user_fields=uf)
created_user = zenpy_client.users.create(user)
This should work, but if it doesn't you could try creating the user first and then querying for them, and then seeing all of your custom fields in user.user_field.
Doing so would allow you to see all the available custom user fields you can enter in. From there you can update the object and zenpy_client.users.update(user) it into the system.
I am currently trying to change the name of the "Delete Selected" admin action. I have already effectively override the default (so I can store some data before completely deleting it), but now I want to change the option from the vague "Deleted selected" to something more specific like "Deleted all selected registrations." Or, at least, for it to say, "Deleted selected registrations" like it did before I overwrote the function.
I have so far tried this:
delete_selected.short_description = 'Delete all selected registrations'
But the option is still "Deleted selected." Is there a way to fix this?
Here's my code:
def delete_selected(modeladmin, request, queryset):
"""
This overrides the defult deleted_selected because we want to gather the data from the registration and create a
DeletedRegistration object before we delete it.
"""
for registration in queryset:
reg = registration.get_registrant()
if registration.payment_delegation:
delegate_name = registration.payment_delegation.name
delegate_email = registration.payment_delegation.email
else:
delegate_name = None
delegate_email = None
registration_to_delete = DeletedRegistration.objects.create(
registrant_name = reg.full_name(),
registrant_email = reg.email,
registrant_phone_num = reg.phone,
delegate_name = delegate_name,
delegate_email = delegate_email,
# Filtering out people (with True) who couldn't participate in events because we are only interested in the people
# we had to reserve space and prepare materials for.
num_of_participants = registration.get_num_party_members(True),
special_event = registration.sibs_event,
)
registration.delete()
delete_selected.short_description = 'Delete all selected registrations'
edit: just tried delete_selected.list_display that didn't work either
You can't have it in the function, so I just had to tab it back one space and it worked.
example:
def delete_selected(modeladmin, request, queryset)
code
delete_selected.short_description = "preferred name"
thanks.
Is there a way to automatically set field values for models in Django when defining the model?
I need t define some values of fields automatically in my model using function.
my function get input image path calculate and I need that calculation results to define my database fields in Django.
first to I want is something like this :
my view :
def myview(request):
uploadimages = UploadImagesForm(request.POST or None, request.FILES or None)
if uploadimages.is_valid():
# Get the images that have been browsed
if request.FILES.get('multipleimages', None) is not None:
images = request.FILES.getlist('multipleimages')
for image in images:
MyModel.objects.create(field1=request.user,field2=image)
that doesn't work because to work my function need first to upload image in server to get the path to work.
any idea how to define my model automate using my function ?
update
instance = MyModel.objects.create(user=request.user, upload=image)
instance.field1 = name
instance.field2 = myvalue
instance.field3 = myvalue2
instance.field4 = myvalue3
instance.field5 = myvalue4
instance.save()
error in this code is the my function cant understand the image path to create the calculation to set the values in fields.
if I use this :
MyModel.objects.create(user=request.user, upload=image)
instance = MyModel.objects.create(user=request.user, upload=image)
instance.field1 = name
instance.field2 = myvalue
instance.field3 = myvalue2
instance.field4 = myvalue3
instance.field5 = myvalue4
instance.save()
that work but create me duplicates in database .
You can try:
instance = MyModel.objects.create(field1=request.user, field2=image)
instance.field3 = myfunc(image)
instance.field4 = myfunc(image)
instance.save()
In my website, I have a model Experiment that contains many Activities. I have a view where people can add or remove Activities from an Experiment.
I show a table with Activities that are a part of this Experiment, and a table of Activities not a part of this Experiment. Users can check which Activities they want to add or remove and use a submit button under the table.
However, when I update the list of choices on one form, the list of choices on the other form reflects this. Am I doing something wrong?
For both adding and removing the Activities to/from the Experiment, I use the same form.
class MultiCheckboxField(SelectMultipleField):
widget = ListWidget(prefix_label=False)
option_widget = CheckboxInput()
class ActivityListForm(Form):
activities = MultiCheckboxField(validators=[DataRequired()], choices=[])
submit = SubmitField("Submit")
def populate_activities(self, activities_set):
activities_mapping = {}
for activity in activities_set:
activities_mapping[str(activity.id)] = activity
choice_tuple = (str(activity.id), activity.question)
self.activities.choices.append(choice_tuple)
return activities_mapping
Here is my view:
def settings_experiment(exp_id):
experiment = Experiment.query.get(exp_id)
remove_activities_form = ActivityListForm(prefix="remove")
add_activities_form = ActivityListForm(prefix="add")
remove_activities_mapping = remove_activities_form.populate_activities(
experiment.activities)
add_activities_mapping = add_activities_form.populate_activities(
Activity.query.\
filter(not_(Activity.experiments.any(id=experiment.id))).all())
return render_template("experiments/settings_experiment.html",
experiment=experiment,
update_experiment_form=update_experiment_form,
remove_activities_form=remove_activities_form,
add_activities_form=add_activities_form,
add_activities_mapping=add_activities_mapping,
remove_activities_mapping=remove_activities_mapping)
Although remove_activities_form and add_activities_form have their options set separately to different lists, they both end up containing a union of their two option lists, which messes up my template rendering. Is there a way to keep them separate or am I screwed?
https://github.com/wtforms/wtforms/issues/284
Solution in the above discussion.