Set Field Equal To A Variable Django/ Python

Ray Zuchowski
Ray Zuchowski used Ask the Experts™
on
I'm trying to set one of my fields equal to a variable.

The field in my models week_of I want to equal to the variable I created . The variable in my Views.py titled weeknumber should be week_of = weeknumber is what I’m trying to accomplish.


In theory the field in week_of is suppose to extract the current week number and auto input it. So i can be doing this completely wrong, deft need guidance. Thank you all so much for the help !

views.py

def K8Points (request):
 if request.method == 'POST':
    form = K8PointsForm(request.POST)
    weekNumber = date.today().isocalendar()[1] 
    if form.is_valid():
        points = form.save()

Open in new window


models.py

class K8Points(models.Model):
    date = models.DateField(default=timezone.now) 
    teacher_class_id = models.ForeignKey(TeacherClass, on_delete = models.PROTECT, default = "")
    student_id = models.CharField(max_length=50, default = "")
    total = models.IntegerField()
    week_of = models.DateField()
    day = models.CharField(max_length= 10, choices= DAY_OF_THE_WEEK)

Open in new window

Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
NorieAnalyst Assistant

Commented:
Not sure I understand what you are trying to do, but I would have thought that if you wanted the week_of field to have a default value of date.today().isocalendar()[1] then you would use something like this in models.py

week_of = models.IntegerField(default=date.today().isocalendar()[1])

Open in new window

Ray ZuchowskiIT Director

Author

Commented:
I get an errot norie that .today is not a attribute of date . If i assign that to a variable it will work but not directly in the model.
NorieAnalyst Assistant

Commented:
What exactly is date in views.py?

Is it a another variable?
Success in ‘20 With a Profitable Pricing Strategy

Do you wonder if your IT business is truly profitable or if you should raise your prices? Learn how to calculate your overhead burden using our free interactive tool and use it to determine the right price for your IT services. Start calculating Now!

Ray ZuchowskiIT Director

Author

Commented:
Norie,

 Forget about the variable, all im trying to do is get the week_of field to auto populate the week number. That's it.
NorieAnalyst Assistant

Commented:
This is how you would get the week number for the current data, and it's pretty similar to the code you posted.
from datetime import date

weekNumber = date.today().isocalendar()[1]

Open in new window


Perhaps all you need is to add the import to models.py
Ray ZuchowskiIT Director

Author

Commented:
I tried that already and it doesnt work.
Ray ZuchowskiIT Director

Author

Commented:
The easiest solution i see is creating a variable and then setting that variable = to a field .

So for Example

name = Ray

class People(model.Models):

personname = models.charfield(max_length=20)


How do we get the person name field to equal the variable name automatically ?
NorieAnalyst Assistant

Commented:
I tried that already and it doesnt work.

What did you try and how did it not work?

Does this work?
def K8Points (request):
 if request.method == 'POST':
    form = K8PointsForm(request.POST)
    weekNumber = date.today().isocalendar()[1] 
    form['week_of'].initial = weekNumber
    if form.is_valid():
        points = form.save()

Open in new window


PS Are you sure you are using the correct data type for the week_of field?

Isn't it going to be an integer rather than a date?
Ray ZuchowskiIT Director

Author

Commented:
I set week_of field to integer, i posted the code you gave me and i get a error that form does not support item assignment.
NorieAnalyst Assistant

Commented:
Can you post the code you tried?
Ray ZuchowskiIT Director

Author

Commented:
@login_required
def K8Points (request):
   if request.method == 'POST':
      form = K8PointsForm(request.POST)
      weekNumber = date.today().isocalendar()[1] 
      setweek = form['week_of'].initial = weekNumber
      if form.is_valid():
         status = "In Session"
         points = form.save()
   else:
     form = K8PointsForm()    
     return render(request, 'points/k8points.html', {'form': form})     

Open in new window

NorieAnalyst Assistant

Commented:
What is setweek in this code?
setweek = form['week_of'].initial = weekNumber

Open in new window

Does it work without it?
 form['week_of'].initial = weekNumber

Open in new window

Ray ZuchowskiIT Director

Author

Commented:
no it doesnt work either way .
NorieAnalyst Assistant

Commented:
Can you post the rest of the code, or at least the code for K8PointsForm?
Analyst Assistant
Commented:
This seemed to work for me, it sets the default of the week_of field to be a call to the function weeknumber which returns the current ISO week number.
def weeknumber():
      return datetime.datetime.today().isocalendar()[1]

# Create your models here.
class K8Points(models.Model):
    date = models.DateField(default=timezone.now) 
    teacher_class_id = models.ForeignKey(TeacherClass, on_delete = models.PROTECT, default = "")
    student_id = models.CharField(max_length=50, default = "")
    total = models.IntegerField()
    week_of = models.IntegerField(default=weeknumber)
    day = models.CharField(max_length= 10, choices=DAY_OF_THE_WEEK, default = 1)

Open in new window

Ray ZuchowskiIT Director

Author

Commented:
AttributeError: type object 'datetime.datetime' has no attribute 'datetime'
Ray ZuchowskiIT Director

Author

Commented:
Norie,

 Here is my full models.py

from django.db import models
from django.utils import timezone
from django.forms import ModelForm
from datetime import datetime
from django.utils.translation import gettext_lazy as _
import uuid
 

# Create your models here.

DAY_OF_THE_WEEK = {
    (0, 'Monday'),
    (1, 'Tuesday'),
    (2, 'Wednesday'),
    (3, 'Thursday'),
    (4, 'Friday'),
 
    
}

class TeacherClass(models.Model):
    teacher_class_id = models.UUIDField(default=uuid.uuid4, editable=False, unique=True)
    class_name = models.CharField(max_length = 50)
    

    class Meta:
        verbose_name = "Teacher Class Room"

    def __str__(self):
        return self.class_name  



class Teachers(models.Model):
     teacher_id = models.CharField(primary_key = True , default = "", max_length = 50, unique = True)
     teacher_name = models.CharField(max_length= 50)
     grade = models.CharField(max_length = 2)
     class_name = models.ManyToManyField(TeacherClass)

     class Meta:
        verbose_name = "Teacher"

    
     def __str__(self):
        return self.teacher_name  

class Student(models.Model):
    student_id= models.CharField(primary_key = True , default = "", max_length = 50, unique = True)
    student_name = models.CharField(max_length = 50)
    student_grade = models.CharField(max_length = 2, default = "")
    counseling_goal = models.CharField(max_length = 255)
    class_name = models.ManyToManyField(TeacherClass)

 

    def __str__(self):
        return self.student_name             

class NhsPoints(models.Model):
    dayid = models.UUIDField(default=uuid.uuid4, editable=False, unique=True)
    date = models.DateField(default=timezone.now) 
    teacher_class = models.ForeignKey(TeacherClass, on_delete = models.PROTECT, default = "")
    week_of = models.IntegerField()
    day = models.CharField(max_length= 10, choices= DAY_OF_THE_WEEK)
    status = models.CharField(max_length= 10, default = "")
    
 
def weeknumber():
      return datetime.datetime.today().isocalendar()[1]

class K8Points(models.Model):
    dayid = models.UUIDField(default=uuid.uuid4, editable=False, unique=True)
    date = models.DateField(default=timezone.now) 
    teacher_class= models.ForeignKey(TeacherClass, on_delete = models.PROTECT, default = "")
    week_of = models.IntegerField(default=weeknumber)
    day = models.CharField(max_length= 10)
    status = models.CharField(max_length= 10, default = "", blank = True)

Open in new window


I even tried changing week_of to a Datetime Field and that didnt work either.
Ray ZuchowskiIT Director

Author

Commented:
I figured it out, im a moron . I had at the top of my models.py from datetime import datetime instead of import datetime. Sorry Norie.
NorieAnalyst Assistant

Commented:
Ray

So did  you set week_of to an IntegerField and use the weeknum function I suggested for the default?

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial