简体   繁体   中英

Saving a user specific data in django

I am currently working on my maiden django project where an authorised person can save their daily expenses. I have created the login and signup page using UserCeationForm and AuthenticationForm . My code for the same is:

  def login_view(request):
    if request.method == 'POST':
        form= AuthenticationForm(data=request.POST)
        if form.is_valid():
            user=form.get_user()
            login(request,user)
            return render (request, 'tasks_notes/index.html')
    else: 
        form= AuthenticationForm()
    return render(request, 'registeration/login.html', {'form':form}) 

  def signup_view(request):
    if request.method == 'POST':
        form= UserCreationForm(request.POST)
        if form.is_valid():
            user=form.save()
            login(request,user)
            return redirect('login')
    else: 
        form=UserCreationForm()
    return render(request, 'tasks_notes/signup.html',{'form':form})

I have created a page named index.html where I am giving input to save my daily expenses wfor the appropriate (logged in) user as:

 <form class="col s12" action='{% url "add item" %}' method='post'>
                    {% csrf_token %}
                    <div class="row">
                        <div class="container center">
                            <h3 class='center'>Your total budget is: <span style="color:green;">{{ budget }}</span> dollars</h3>
                            <h3 class='center'>You've spent a total of: <span style="color:red;">{{ expenses }}</span> dollars</h3>
                            <br>
                            <br>
                            <div class="input-field col s3">
                                <input placeholder="Expense name" name="expense_name" id='expense_name' type='text' class='validate'>
                                <label for='expense_name'>Expense name</label>
                            </div>
                            <div class="input-field col s3">
                                <input placeholder='Amount' name='cost' id='cost' type='text' class='validate'>
                                <label for='cost'>Amount</label>
                            </div>
                            <div class="input-field col s3">
                                <input placeholder='Date of Expense' name="expense_date" id="expense_date" type="text" class='datepicker'>
                                <label for="expense_date">Expense Date</label>
                            </div>
                            <button class="btn waves-effect waves-light" type="submit" name="action">Add Expense
                                <i class="material-icons right">add_circle</i>
                            </button>
                        </div>
                    </div>
                </form>

I am trying to take the inputs and put that in views.py file as:

    def additem_view(request):
    name = request.POST['expense_name']    
    expense_cost = request.POST['cost']  
    expense_date = request.POST['expense_date']
    create=BudgetInfo.objects.create(items=name,cost=expense_cost,date_added=expense_date)
    create.save()
    return HttpResponseRedirect('app')

My models.py file is:

from django.db import models
from django.contrib.auth.models import User

class BudgetInfo(models.Model):
    items= models.CharField(max_length=20)
    cost= models.FloatField(blank=False, null=True)
    date_added= models.DateField(auto_now=True)
    user= models.ForeignKey(User, on_delete= models.CASCADE)

When I am giving the input in my web page, I am getting an error like this:

Exception Type:     IntegrityError
Exception Value:    NOT NULL constraint failed: tasks_notes_budgetinfo.user_id

I have checked for budgetinfo.user_id in my dbsqlite database I found this:

CREATE TABLE IF NOT EXISTS "tasks_notes_budgetinfo" ("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "items" varchar(20) NOT NULL, "cost" real NULL, "date_added" date NOT NULL, "user_id" integer NOT NULL REFERENCES "auth_user" ("id") DEFERRABLE INITIALLY DEFERRED);

Sorry for such long explanation of my question. Can anyone tell me where am I wrong? It will be a great help. Thank you.

try this

 <form class="col s12" action='{% url "add item" %}' method='post'>
                    {% csrf_token %}
                    <input type="text" name="id" value="{{user.id}}">
                </form>

and in your views

def additem_view(request):
   name = request.POST['expense_name']    
   expense_cost = request.POST['cost']  
   expense_date = request.POST['expense_date']
   id= request.POST['id']

create=BudgetInfo.objects.create(id=id,items=name,cost=expense_cost,date_added=expense_date)
create.save()
return HttpResponseRedirect('app')

Your BudgetInfo model has a ForeignKey pointing to the your User model. When saving the BudgetInfo you never made the link to the (non-null) user.

If you want the script to refer to the "current user" (the user who actually made the request after logging in) you should simply use request.user :

BudgetInfo.objects.create(
    user=request.user,
    items=name,
    cost=expense_cost,
    date_added=expense_date,
)

If you're linking this to "some other user", you'll need to find that user first then link it the same way:

BudgetInfo.objects.create(
    user=User.objects.get(username="smassey"), # for example
    items=name,
    cost=expense_cost,
    date_added=expense_date,
)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM