Button in html that deletes an instance of a Django model - html

If I have a list of instances, and each instance has a button or checkbox.
When you press it, it calls delete() on the instance. How would you implement this in Django?

You'll need to create a function view that would query that exact instance that you want to delete. I have an example from my app that would query the selected comment on a post and deletes it when the user presses a delete button.
def delete_comment(request, comment_id):
comment = get_object_or_404(Comment, id=comment_id)
slug = slugify(comment.post.slug)
if request.user.is_staff or comment.user == request.user:
Comment.objects.get(id=comment_id).delete()
messages.success(request, "Your comment was successfully deleted.")
return HttpResponseRedirect(reverse("main.views.post", args=(slug,)))
So let me explain how does this function view work. I have a model called Comment, and that Comment model has a foriegnkey to the Post model. So each post has some comments. A user now commented on a post, and he decided to delete it. There is a delete button that redirects him to the delete_comment function view. The view tried to get the comment id, if it exists it continues, if it doesn't it returns a 404. Then it checks if the comment was made by the same user that is trying to delete it, or if the user is a staff member. Then we get the comment id, and make it the same as our function parameter comment_id so we can use that in the urls.py, as you can see we get the exact comment id and we use the delete() function to it, and that deletes the comment!
And ofcourse you'll need a url for that which would look like the following for the delete_comment view
url(r"^delete_comment/(?P<comment_id>\d+)/$", views.delete_comment, name="delete_comment"),
And here is how you write the delete button to hook it up with the view and the url
delete
As you can see the url contains where the delete function view is, and it's using the argument of the comments.id to be used in the view and the url. It's easy to implement, hope this example gave you a starting point/idea on how to start.

Related

What is the best practice to design REST URI for the following use case

A user can singup in an application
/users
GET /id get userDetails
POST saveUserDetails
A admin can create events for a user to register
/events
POST saveEvent
PUT /{event-id} for updating event
DELETE /{event-id} deleting an event
Now, the question is where would you place user to event registration uri?
will it be
/events/{event-id}/register
or
/users/{user-id}/events?event-id=xxx
and I also want to get list of the events to which the user has registered
Please help me with better API design
There's no right answers here, so I'll just throw in the hat the patterns that I would probably use:
POST /user - register a new user
GET /user/:id - Get user info
PUT /user/:id - Update user info
POST /event - create an event
PUT /event/:id - Update an event
GET /event/:id - Get event details
DELETE /event/:id - Delete event
GET /event/:id/attendees - Get list of attendees
POST /event/:id/attendees - Add user to list of attendees
GET /user/:id/event - Get list of events that user is attendee of
The main goal is to register to an event. Then you should start with /events
This is why /events/{event-id}/register looks fine to me.
There are various ways by which you can achieve this but what I see as the best practice is that you should be able to understand from the URL itself that what you're trying to achieve.
For example,
Admin wants to create an event:
POST: {basePath}/a/events or {basePath}/admin/events
a | admin: defines that this action is being performed by an Admin
events: defines that operation is being performed on events entity
Now User wants to register for the event, hence
POST: {basePath}/u/events/{eventId} or {basePath}/user/events/{eventId}
u | user: defines that this action is being performed by the User
events: defines that operation is being performed on events entity. Which can be multiple entities hence adding eventId in the path variable to define which you need to register.
now in the above example, I am assuming you can get the User details in the request
or capture it from the session but if that is not the case you want to follow then you might need to use below example (assuming path variable is the only option for you to get the User context)
POST: {basePath}/u/{Id}/events/{eventId} or {basePath}/users/{userId}/events/{eventId}
You can read more here about naming guide if you like.

How to get record's primary key value on saving in manual mode?

I have a model in manual save mode and a form in create mode. Once I add details and click on submit it should create the record and
alert something like 'Your request is registered with id=7' where id is the id (primary key).
Note the primary key is in auto increment and generated dynamically.
In manual save mode I am using saveChanges to save the record but seeing error:
SEVERE: Record RecordKey{key=private$2, model
key=1ymdoCYoHKEGpumlXveKKZh_57jUjd9OY|7LyXBUY46K9Jl6GRCy1DeL32kXmnGHis}
already deleted.Failed: getProperty at Object.
(UserCreationRequest:12:37) at createUCR (UserCreationRequest:11:19)
at
UserCreationRequest.Container.UserCreationRequestPanel.UserCreationRequestPanelFooter.UserCreationRequestPanelSubmitButton.onClick:1:1
(In error 12:37 points to record._key)
Code: (executed OnClick of submit button)
widget.datasource.saveChanges(function(record) {
alert('Your request is registered with id='+record._key);
}
Can someone please advise how to get the primary key on saving in manual mode?
Additional Info Reference:
The above code has worked for me in some other place for some other model. But not working for the current model, is it because the current model has a relation?
I added a new datasource in the Datasources section of the current model
and by using that its working fine. But why is not working fine with the original one?
Also FYI, this is a similar issue but it did not help as it's a different approach. I'm keen to save using the widget itself.
First, we need to understand that the create mode is not the same as the normal mode. Having that clear, we can do the following:
Assuming the datasource name is MYDATASOURCE, the form datasource should be MYDATASOURCE(create). Then, on the onClick event of the submit button widget inside the insert form, use this:
widget.datasource.createItem(function(record){
app.datasources.MYDATASOURCE.saveChanges(function(){
console.log(record._key);
});
});

"Create or update" form behavior when hitting back button

I have the following workflow on a website:
Some user John Doe declares a company through form 1
(fields: name, head office location)
After John Doe submits (HTTP POST) form 1, he is redirected (HTTP 302) to company form 2 with additional legal information about the company.
The problem is, if John Doe hits the back button of his browser during step 2, he will land on the form 1, with data filled by the browser (using values he already submitted — that's what Firefox and major browsers seem to do).
John Doe might then think he can use this form to update some information (e.g. fix a typo in the name of the company) whereas he will actually create a new company doing so, as we don't know on the server side whether he wants to declare a new company or update the one he just created.
Do you know any simple solution to handle that problem ?
Use javascript/jquery script after the page is loaded to empty all the inputs. This will prevent confusion of "updating the company".
jQuery would look something like this:
$('#elementID').val('');
You can also handle the situation by manipulating the browser history
on load of form 2, and pass the CompanyId generated on submit of form 1 using querystring. So that you can actually update the company as the user
Suppose John submits form1.html, a unique CompanyId "1001" is generated and redirected to form2.html. Now on load of form2 you can modify the browser history form1.html?companyid=1001 using
var stateObj = { foo: "bar" };
history.pushState(stateObj, "page 1", "form1.html?companyid=1001");
Now, when the user click back button and submits the form1 again. you can check for companyid in querystring and update the company.
I think it is more user-friendly when user can return back to previous form and update it (instead preventing the described behavior).
I use in most cases similar way to handle described problem:
Let's assume that user is on the page /some-page, that contains "Create new company" button.
When the user opens this page, will be executed special method createOrFindCompanyDraft() on the server-side. This method creates new company "draft" record in DB (only for the current user). For example, draft record has primary key id=473. When you execute this method again it will return the same record with the id=473 (with "draft" status). "Draft" record should't display on any other interfaces.
And "Create new company" has link /company/common/473.
When user go to /company/common/473, you display form 1, that will be filled from "draft" record. At first time user will see empty form.
Technically user will update the existing record, but you can display "Create new company" title on the page.
Then user go to form 2, for example, /company/legal-info/473, you create similar draft record for the this form (similar to step 1).
When user submit the form 2, you will remove "draft" status from the record id=473 (and any related records).
Next time when user open page /some-page, will be created new draft record for the current user.
Browser history will contain:
/some-page
/company/common/473
/company/legal-info/473
/some-page2
I like this approach, because all form only update records. You can go to previous/next form many times (for example "Back"/"Forward" browser buttons). You can close browser, and open not completed forms tomorrow. This way doesn't require any additional manipulation with the browser history.
try this
<form autocomplete="off" ...></form>
And Another
Use temporary tables or session to store the Page 1 form data. If the page 2 form is submitted use the temporary data of page 1 which is stored in database or in session.
Use a Separate key (Hidden field ) in both page 1 and page 2.
Actually I thought of a trick to obtain that "create on first post, update after" behavior (just like the user thinks it should behave).
Let's say the step 1 form is at the URL /create_company/. Then I could have that page generate a random code XXX and redirect to /create_company/?token=XXX. When I create the company I save the information that it was created through page with token XXX (for instance, I save it in user's session as we don't need to keep that information forever) and when the form is submitted, if I know that a company was already generated using this token, I know the user used the same form instance and must have used the back button since the token would be different if he explicitly asked for another company.
What do you think ? (I initially thought there should be a simpler solution, as this seems a little bit over-engineered for such a simple issue)
This is more like a UX question.
I'd think that the solution lies within the information given to the user on that form, to help them understand what they're doing.
Set a title that says 'Create a company', for example, and set your submit button as 'Create Company' will help your user with that. Use a unique id when you create the company object, and pass the id back to the same URL in order to perform an update. You should then update your title and button that tells user that they are updating instead of creating.
In that sense I'd say it's better to use a more generic URL like /company and /company?id=12345.
You could also consider using Restful API protocol to help your server identifies the CRUD operation. http://www.restapitutorial.com/lessons/httpmethods.html
Without the "routing" part of django it is hard to help. I can just answer my experience from the express.js-router functionality:
you can specify a post on /company, which is for new users.
you can specify another route for post on /company/:companyid for a changing form
and as a response from the create-post you can redirect to the different location.

Yii2 redirect to previous page

Now My application is using gridview to list all information and it's also have pagination.when the user click on pagination number and then click on edit and then save. It redirect user to view page. What I want to do it to redirect user to previous page(url with pagination number).
You could use Yii::$app->request->referrer which returns the last page the user was on.
Usage is straightforward:
return $this->redirect(Yii::$app->request->referrer);
You need also take into account that referrer can be null:
return $this->redirect(Yii::$app->request->referrer ?: Yii::$app->homeUrl);
See the docs.
Here it says that it's a good practice to check if referrer is set at the first place.
So if you use the following code you will be redirected to last page if referrer is set or to your configured homeUrl if the return URL was not set previously.
return $this->goBack((!empty(Yii::$app->request->referrer) ? Yii::$app->request->referrer : null));
goBack() details
redirect details
It is true what #Kostas says, but I think it would be better if you simply code the following, because goBack take account of a null parameter already to goBack HOME.
return $this->goBack(Yii::$app->request->referrer);
I tested it and it works fine.
If you use Html::submitButton when you are in a form and you want to be redirected to the previous page, so mostly to your module list I recommend using use yii\helpers\Url;:
return $this->redirect(Url::previous('previous') ?: ['list']);
because
return $this->redirect(Yii::$app->request->referrer);
will return you back to the form instead of a module list.

Laravel Eloquent how to limit access to logged in user only

I have a small app where users create things that are assigned to them.
There are multiple users but all the things are in the same table.
I show the things belonging to a user by retrieving all the things with that user's id but nothing would prevent a user to see another user's things by manually typing the thing's ID in the URL.
Also when a user wants to create a new thing, I have a validation rule set to unique but obviously if someone else has a thing with the same name, that's not going to work.
Is there a way in my Eloquent Model to specify that all interactions should only be allowed for things belonging to the logged in user?
This would mean that when a user tries to go to /thing/edit and that he doesn't own that thing he would get an error message.
The best way to do this would be to check that a "thing" belongs to a user in the controller for the "thing".
For example, in the controller, you could do this:
// Assumes that the controller receives $thing_id from the route.
$thing = Things::find($thing_id); // Or how ever you retrieve the requested thing.
// Assumes that you have a 'user_id' column in your "things" table.
if( $thing->user_id == Auth::user()->id ) {
//Thing belongs to the user, display thing.
} else {
// Thing does not belong to the current user, display error.
}
The same could also be accomplished using relational tables.
// Get the thing based on current user, and a thing id
// from somewhere, possibly passed through route.
// This assumes that the controller receives $thing_id from the route.
$thing = Users::find(Auth::user()->id)->things()->where('id', '=', $thing_id)->first();
if( $thing ) {
// Display Thing
} else {
// Display access denied error.
}
The 3rd Option:
// Same as the second option, but with firstOrFail().
$thing = Users::find(Auth::user()->id)->things()->where('id', '=', $thing_id)->firstOrFail();
// No if statement is needed, as the app will throw a 404 error
// (or exception if errors are on)
Correct me if I am wrong, I am still a novice with laravel myself. But I believe this is what you are looking to do. I can't help all that much more without seeing the code for your "thing", the "thing" route, or the "thing" controller or how your "thing" model is setup using eloquent (if you use eloquent).
I think the functionality you're looking for can be achieved using Authority (this package is based off of the rails CanCan gem by Ryan Bates): https://github.com/machuga/authority-l4.
First, you'll need to define your authority rules (see the examples in the docs) and then you can add filters to specific routes that have an id in them (edit, show, destroy) and inside the filter you can check your authority permissions to determine if the current user should be able to access the resource in question.