How can I define the date format in models in django? - django

I'm defining a date variable inside my model AccessRecord using DateField attribute and I've tried every possible thing to define it. But every time a new error arises. Sometimes it says "Date is not defined" sometimes "Date should be in YYYY-MM-DD format" during migration.
Can someone give me a permanent solution for this? I'm using django 2.1.7.
I've tried default='' and default=blank and quite of few others
from django.db import models
from datetime import date
class AccessRecord(models.Model):
name = models.ForeignKey(Webpage, on_delete=models.PROTECT)
date = models.DateField(_("Date"), default=date.today)
def __str__(self):
return str(self.date)

This should be sufficent
from django.db import models
class AccessRecord(models.Model):
name = models.ForeignKey(Webpage, on_delete=models.PROTECT)
date = models.DateField(auto_now_add=True))
def __str__(self):
return str(self.date)
And for the formatting stuff use the #property mentioned in stackoverflow.com/q/20229198/4107823 as commented by PetarP

Related

New attributes are not showing up in django admin dashboard

Previously I was using my project with sqlite. Then started a new project copied the data from previous project and made some changes, and I'm using this with mysql.
This is my models.py(not full)
from django.db import models
from django.db.models import CheckConstraint, Q, F
class College(models.Model):
CITY_CHOICES=[('BAN','Bangalore')]
id=models.IntegerField(primary_key=True)
name=models.CharField(max_length=50)
city=models.CharField(choices=CITY_CHOICES,default='BAN',max_length=10)
fest_nos=models.IntegerField()
image=models.ImageField(default='default.jpg',upload_to='college_pics')
class Meta():
db_table='college'
def __str__(self):
return self.name
class Organizer(models.Model):
id=models.IntegerField(primary_key=True)
name=models.CharField(max_length=25)
phone=models.IntegerField()
def __str__(self):
return self.name
class Fest(models.Model):
FEST_CHOICES=[
('CUL','Cultural'),
('TEC','Technical'),
('COL','College'),
('SPO','Sports'),
]
id=models.IntegerField(primary_key=True)
name=models.CharField(max_length=50)
clg_id=models.ForeignKey(College,on_delete=models.CASCADE)
fest_type=models.CharField(choices=FEST_CHOICES,default='COL',max_length=10)
fest_desc=models.TextField(default='This is a fest')
#below two field are not showing up in admin page
start_date=models.DateField(auto_now_add=True)
end_date=models.DateField(auto_now_add=True)
event_nos=models.IntegerField()
org_id=models.ManyToManyField(Organizer)
image=models.ImageField(default='default.jpg',upload_to='fest_pics')
class Meta:
constraints = [
CheckConstraint(
check = Q(end_date__gte=F('start_date')),
name = 'check_start_date',
)
]
db_table='fest'
def __str__(self):
return self.name
The start_date and end_date attributes are the new ones added in this project. It was not there in the old one.
My admin.py file
from django.contrib import admin
from .models import College, Event, Fest, Organizer, Participated
admin.site.register(College)
admin.site.register(Organizer)
admin.site.register(Fest)
admin.site.register(Event)
admin.site.register(Participated)
But in my admin dashboard, while adding new fests I'm not getting the option to add start and end date.
I made migrations once again, fake migrated etc. What to do?
Is check constraint under model fest causing this problem?
They fields won't show up on Django Admin because they have auto_now_add=True so, the user shouldn't touch them.
You can make auto_now_add field display in admin by using readonly_fields in the admin class(this only show the data, you still can't edit it because it's auto_now_add)
#register with a class to use
class FestAdmin(admin.ModelAdmin):
readonly_fields = ('start_date', 'end_date')
admin.site.register(Fest, FestAdmin)

How to use work week in DateField in Django admin

In my model, I say:
class Foo(models.Model):
start = models.DateField(help_text='Start Date')
In the django admin, when adding a new Foo object, I see a text field with a calendar attached allowing me to select the date. I want to customize this a little bit so that I can either select the date from the calendar or enter something like WW12'22 in the textfield and during Save, this gets converted into a DateField. I am not sure how to do implement this in the django admin. Any ideas would be helpful.
I try something like this, but I get an invalid date when I enter '05 22' (i.e, WW05'22).
class FooForm(forms.ModelForm):
start_date = forms.DateField(widget=forms.DateInput(format='%W %y'), localize=True)
You could create your own DateField subclass and when the provided value isn't parsed as a date you implement your own parsing.
Since you need to provide the day of the week to use week number when parsing, replace the "WW" part of your input with 1 and parse this as the day of the week (1 is Monday)
admin.py
import re
import datetime
from django.contrib import admin
from django import forms
from .models import Foo
from django.contrib.admin.widgets import AdminDateWidget
class MyDateField(forms.DateField):
def to_python(self, value):
try:
return super().to_python(value)
except forms.ValidationError:
if re.match(r'WW\d+\'\d+', value):
return datetime.datetime.strptime(value.replace('WW', '1-'), '%w-%W\'%y')
raise
class FooForm(forms.ModelForm):
start_date = MyDateField(widget = AdminDateWidget)
class Meta:
model = Foo
fields = '__all__'
class FooAdmin(admin.ModelAdmin):
form = FooForm
admin.site.register(Foo, FooAdmin)

How to bypass WSGI error in django filter

from django.db import models
from django.contrib.auth.models import User
class Transfer(models.Model):
id = models.AutoField(primary_key=True)
amount = models.DecimalField(max_digits=10, decimal_places=2)
name=models.CharField(max_length=55)
timestamp = models.DateTimeField(auto_now_add=True, auto_now=False)
Is it possible to make a request like this without WSGI error?
result = Transfer.objects.filter(name=request.name)
filter()
filter(**kwargs)
Returns a new QuerySet containing objects that match the given lookup parameters.
The lookup parameters (**kwargs) should be in the format described in Field lookups below.
Where charfield == String object, so try to str(request.name)

First parameter to ForeignKey must be either a model, a model n ame, or the string 'self'

Hey I am using the First Parameter as a model but still it keeps on giving the error:
First parameter to ForeignKey must be either a model, a model n
ame, or the string 'self'
for my code.
It works totally well if I use 'self' as first parameter for foreign key. but thats not what I want. Also i am unable even to makemigrations after the following code.
models.py
from django.db import models
import datetime
from django.utils import timezone
class commentt(models.Manager):
comment_id=models.IntegerField(primary_key=True)
name=models.CharField(max_length=100, default="No Comment Added")
comment_created=models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.name
# Create your models here.
class task_check_manager(models.Manager):
def create_task(self, title,c1,c2,c3,list,score_occurence,score_occurence_csm,To):
Task_check = self.create(title=title,c1=c1,c2=c2,c3=c3,list=list,score_occurence=score_occurence,score_occurence_csm=score_occurence_csm,To=To)
# do something with the book
return Task_check
class task_check(models.Model):
LIST = (
('DAILY', 'DAILY'),
('WEEKLY','WEEKLY'),
('FORTNIGHT','FORTNIGHT'),
('MONTHLY','MONTHLY')
)
STATUS=(
('YES','YES'),
('NO','NO'),
('NEUTRAL','NEUTRAL')
)
title=models.CharField(max_length=50)
c1=models.CharField(max_length=20,default='C1')
c2=models.CharField(max_length=20,default='C2')
c3=models.CharField(max_length=20,default='C3')
From=models.DateTimeField(default=timezone.now())
To=models.DateTimeField(default=timezone.now())
#created_task=models.DateTimeField(auto_now_add=True)
status=models.CharField(max_length=15,default="NEUTRAL",choices=STATUS)
list=models.CharField(max_length=15, default='DAILY',choices=LIST )
score_occurence_csm=models.IntegerField(default=0)
score_occurence=models.IntegerField(default=0)
comments=models.ForeignKey(commentt, on_delete=models.SET_NULL, null=True)
vendor=models.TextField(max_length=200,default="NONE", editable=False)
objects = task_check_manager()
def __str__(self):
return self.title
You Commentt model is indeed not a model, it is a manager. You should make it a subclass of Model:
class Commentt(models.Model): # <- Model, not Manager
comment_id = models.IntegerField(primary_key=True)
name = models.CharField(max_length=100, default="No Comment Added")
comment_created = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.name
Note: According to the PEP-8 Style Guide, the classes should be written in PerlCase, and the fields in snake_case.
I know this is not a solution to your problem but I was shown the same error for missing the (models.Manager) on a model class. I am sharing this because it might help someone else.

Django date query from newest to oldest

I am building my first Django program from scratch and am running into troubles trying to print out items to the screen from newest to oldest.
My model has an auto date time field populated in the DB as so:
Model
from django.db import models
from django.contrib.auth.models import User
from django.conf import settings
from django.utils import timezone
class TaskItem(models.Model):
taskn = models.CharField(max_length = 400)
usern = models.ForeignKey(User)
#Created field will add a time-stamp to sort the tasks from recently added to oldest
created_date = models.DateTimeField('date created', default=timezone.now)
def __str__(self):
return self.taskn
What is the line of code that would be abel to sort or print this information in order from newest creation to oldest?
Want to implement it into this call:
taskitems2 = request.user.taskitem_set.all().latest()[:3]
ordered_tasks = TaskItem.objects.order_by('-created_date')
The order_by() method is used to order a queryset. It takes one argument, the attribute by which the queryset will be ordered. Prefixing this key with a - sorts in reverse order.
By the way you also have Django's created_at field at your disposal:
ordered_tasks = TaskItem.objects.order_by('-created_at')
You can set your ordering in model Meta class. This will be the default ordering for the object,for use when obtaining lists of objects.
class TestModel(models.Model):
...
created_at = models.DateField()
....
class Meta:
ordering = ['-created_at']
Or you can apply ordering to specific queryset.
TestModel.objects.order_by('-created_at')