django - create user from request - django

I need some help with django request
I want to add a custom form proccessing to add a user (or any other model instance)
I don't want to create it like this
tagName = request.POST["tagname"]
new_tag = Tag()
new_tag.name = tagName
new_tag.save()
because I would need to rewrite this code everythime something changes in the model
Is there any way how can I create a model instance from the request?
What is the way django-admin do this?
Thank you so much

Use ModelForms

Related

Fetch external data and populate form in django admin

In short:
I would like to fill in some form fields in django admin, before I click the save button, based on the input in another field.
The longer version:
I have 2 models, SteamGame and GameInfo which has a ForeignKey to SteamGame. The SteamGame table gets filled once a day with all the games listed on Steam, by fetching and parsing http://api.steampowered.com/ISteamApps/GetAppList/v0002/, the GameInfo table gets filled manually using the admin site. When adding to GameInfo I select the game from SteamGame. Some of the fields are for info I add myself, some of the fields I want to be populated after selecting the game and fetching https://store.steampowered.com/api/appdetails?appids=GAMEID&l=en for that information.
Are there some magic Django functions I can use to accomplish this? Or any other suggestions on how to do this?
Thanks!
you can pass a javascript file and using query you can make a ajax call and append the values to the form using jquery .
class HistoryConfigurationAdmin(admin.ModelAdmin):
class Media:
js = ("customjs/yourjsfile.js",)
and create a yourjsfile.js in static folder of you project.note for using jquery in django admin instead of using $(document).ready we use "jq" instead of "$" symbol
You can use javascript to achieve that.
On your admin model, add this to call for a custom javascript:
class MyAdmin(admin.ModelAdmin):
class Media:
js = ('/static/js/myMagicJavascriptThatDoesAllThisStuff.js',
)
The JS will allow the user to see what will be saved BEFORE saving it.
If you want to pull the information after the save, you should override the admin save function

Django - force pk_url_kwarg to query other model instances

Consider the following code:
views.py
class BHA_UpdateView(UpdateView):
model = BHA_overall
pk_url_kwarg = 'pk_alt'
form_class = BHA_overall_Form
To my understanding, pk_url_kwarg = 'pk_alt' will query and return instances of model = BHA_overall.
Is there any way that I can force pk_url_kwarg to query
& return other model instances defined in models.py (like model = other_model), while having my get_object() method to return objects in model = BHA_overall? What CBV should I use (I think UpdateView is not a good choice in this case)?
++ I'm trying to make a page that allows users to manage information about the product they use. So, ultimately I will implement forms, and the user input needs to be saved in DB
++ I need pk_url_kwarg = 'pk_alt' to query other models and generate url. But I still need get_object() method to return objects in model = BHA_overall to generate form fields on the user side.
From my understanding you need a django form generated from BHA_overall, but the data should be saved to AnotherModel right?
I will propose 2 solutions to this problem, Choose what best fits you.
Multiple views:
Have multiple views for the task, What I mean is create a view which creates the form for the frontend using BHA_overall, you can create both Create and Update view this way and update view's initial could be overwritten so form will have expected value when editing. And now post the data to another view which handles the post data. This view can have your AnotherModel doing its thing.
Using Django Form:
If you dont like having multiple views, You can keep things simple by creating a form yourself. Create a DjangoForm with the same fields you want to show to the user and use it in to create your own views, Now you wont need BHA_overall and use your AnotherModel to save datal.

Django update single field in model entry with request

I try to update a model entry with a POST request.
<QueryDict: {u'is_locked': [u'False']}>
I tried with a model form :
modelEntry = model.get(pk=pk)
modelForm (request.POST, initial= modelEntry)
if modelForm.is_valid():
modelForm.save()
This was not valid (csrf_exempt)..
And also tried without modelform, directly into the model :
model.objects.filter(pk=pk).update(**request.POST)
Nothing happen ..
Ideally I search a solution with modelform (to check and clean my datas before saving).
There is a proper way for this ?
Cheers
You should pass instance, instead of initial to your model form so that it knows which object to update.
modelForm (request.POST, instance = modelEntry)
if modelForm.is_valid():
modelForm.save()

Creating manytomany objects on a fresh django db object

I am using Django-rest-framework and am trying to add tags to my models.
Every thing is ready on the database-side, but how do I do it on the django-rest side?
Simplified, my model looks like:
name = models.CharField()
tags = models.ManyToManyField(Tags)
I am presenting the tags as a comma-list in django-rest to make it easy for people using the API to add and change tags. However, how can I add tags to a object that doesn’t exists yet?
Using django-rest restore_object in my serializer, I am able to create the list of manytomany objects, but how do I add them to django-rest attrs so it will add them to my object?
In short, how can I add a list of items to .tags in django-rest restore_object function?
Or is this impossible and I need to do the tags handeling -after- the object is created and therefor hide the "tags" field when creating the object in django-rest and display it at the detailed serializer page instead?
I'm not sure if this is the best method, but this seems to work with overriding the save_object method in the serializer.
def save_object(self, obj, **kwargs):
super(MySerializer, self).save_object(obj, **kwargs)
tags = self.init_data.get('tags', None)
if tags:
obj.tags.clear()
tags = tags.split(',')
for t in tags:
tag_obj, created = Tag.objects.get_or_create(name=t, owner=self.context['request'].user)
obj.tags.add(tag_obj)
Is it a bad idea to grab this data from init_data? Seems a little dirty...

Implement auto_current_user_add when using Django's User table

I have an AppEngine app that I'm migrating to run in Django, using app-engine-patch to get all the goodness of Django - particularly the Admin interface.
One of my models looks like (partially) this:
class Request(db.Model):
requestor = db.UserProperty(auto_current_user_add=True)
When I display a form based on this model I don't display the requestor field, and so when I call the Model's put() method the entity I'm saving doesn't have the requestor property set. This triggers the auto_current_user_add magic, and the user who created the request is automatically added.
Under Django, I'm using the provided Users table. I want this to display as a list of the users of my app, so the model becomes:
from ragendja.auth.google_models import User
class Request(db.Model):
requestor = db.ReferenceProperty(User)
However, this breaks the auto_current_user_add magic in the admin interface - if the user of the admin interface doesn't enter a value for the requestor property, Django sets the property to None, when I'd really like for the Request to have their username inserted automatically.
How can I restore the magic?
My solutions relies on three things:
First: it's possible to override the model's put() method.
Second: users.get_current_user() still provides the correct user, and
Third: ragendja.auth.google_models.User.get_djangouser_for_user() takes a google.appengine.api.users.user object and returns the corresponding Django User object - creating it first if it didn't already exist.
Putting this all together, I have:
class Request(db.Model):
requestor = db.ReferenceProperty(User)
def put(self):
if not self.requestor:
self.requestor = User.get_djangouser_for_user(users.get_current_user())
super(Request, self).put()
This works nicely with the admin interface: the admin can assign any existing user (or use the supplied + sign to create a new user) - if they leave it blank, they'll be assigned as the requestor.
Later when I add a view for users to manage their own requests, this value will be on the 'excluded' list, and the same method will add in their username every time they create a new request.
I'm not sure if this is an optimal solution though; I'm new to Django, so maybe there's a better way to achieve this.