Below I describe the second week of my #100DaysOfCode challenge.
In the opening blogpost you can find out more about my Why, my goals and the rules which I set for myself.
Or find the collection of all my posts related to the #100DaysOfCode challenge.
Table of Contents
Django and MySQL: Database bugs fixed | Day 035 (2022-02-10)
- fix database warning
mysql.W002
thanks to Adam in Django Forum Thread - fix callable default issue in expirationTime property of Ad model
In my blog post of Day 33 I’ve briefly described how I encoutered several issues and gave a basic overview how I solved them.
Below I describe the solutions again in a different way.
mysql.W002
: fix database warning (1.)
- occured when calling
py manage.py migrate
- see also related hint in Django Forum
System check identified some issues:
WARNINGS:
?: (mysql.W002) MariaDB Strict Mode is not set for database connection 'default'
HINT: MariaDB's Strict Mode fixes many data integrity problems in MariaDB, such as data truncation upon insertion, by escalating warnings into errors. It is strongly recommended you activate it. See: https://docs.djangoproject.com/en/4.0/ref/databases/#mysql-sql-mode
Django: How to fix mysql.W002
?
- following the instructions in the recommended ressource in warning
- add
OPTION
dictionary inDATABASES
ofsettings.py
of Django project as follows
- add
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'codermatchingdb',
'USER': 'root',
'PASSWORD': 'secret😉',
'HOST': '127.0.0.1',
'PORT': '',
'OPTIONS': {
'init_command': "SET sql_mode='STRICT_TRANS_TABLES'",
}
}
}
- implementation of the fix above resulted in disappearance of warning
OPTIONS
: Not the ultimate solution🤔
Unfortunately the implementation of the OPTIONS
as described above, didn’t solve my problem of unapplied migrations.
Running the server using py manage.py runserver
, I still got the message:
Watching for file changes with StatReloader
Performing system checks...
System check identified no issues (0 silenced).
You have 9 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s):
codermatch.
Run 'python manage.py migrate' to apply them.
February 10, 2022 - 07:44:37
Django version 4.0.1, using settings 'codermatching.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CTRL-BREAK.
I still had 9 unapplied migrations.
And every time I made another migration (py manage.py makemigrations
) and tried to apply them (py manage.py migrate
), the unapplied migrations (when running the server) increased.
Callable Default: Fix issue in expirationTime property of Ad model (2.)
issue:
- always the same expiration date for every Ad object created in the same shell instance
class Ad(models.Model):
...
expirationTime = models.DateTimeField('expiration time (of ad)', default=timezone.now() + datetime.timedelta(days=30))
solution:
class Ad(models.Model):
...
def in30Days():
return timezone.now() + datetime.timedelta(days=30)
...
expirationTime = models.DateTimeField('expiration time (of ad)', default=in30Days)
- implement a callable default in the
DateTimeField
- checkout Adams reply in the forum thread for the explanation
didn’t fix TypeError: fromisoformat: argument must be str
But my initial error was actually TypeError: fromisoformat: argument must be str
.
With Adams hint I finally solved this TypeError
.
In the end, after lot’s of great help from Adam I’ve had a call with an acquaintance who suggested something like:
„Just delete your database and set up a new one!?🤨“
However sad this may be… I did it.
I’ve deleted my database.
I’ve set up a new one.
And I connected it to my Django project.
Voilà – everything works fine.👌
The migrations run again without interfering with the formerly defined database fields, which have been based on a previously defined model.
Instead they build up their own new database fields.
fix database bugs all day long – trivial?
As you can see and read in my respective reply in the Django forum, I’ve spent at least one complete day figuring out solutions for several follow-up database bugs (after I had already spent several days to solve the ones, which I describe above).
Today I had another call with that acquantance, where I gave thanks to him again for his suggestion.
And he actually just stressed the point:
„If something doesn’t work with your database in development, then just delete it.☝️ Don’t hold yourself back with those trivial errors!“
Datetime, timezone.now or timezone.now() – What is it now?❓
- still and always struggling with date respectively time fields, values, functions, methods…
- What’s the difference between
timezone.now
andtimezone.now()
?
- What’s the difference between
I know, I should know it by now…
And I know there are plenty of ressources regarding that topic.🤔
But I still don’t really get it.😫
Git Log: Clearing work | Day 036 (2022-02-11)
- sort, clean and clear git branches
By the way I really like that git log --oneline --all --graph
command and I use it all the day to keep track of my commits.👍
Database conflicts: delete it, make a new one | Day 037 (2022-02-12)
exclude static
directory from .gitignore
Will or Carlton from ChatDjango encouraged me to implement my suggested exclusion of static from .gitignore
.
Therefore I did it.
Thank y’all at Django Chat!🙏
delete database codermatch_db
If I create a new field in a Django model which the old database doesn’t know yet, py manage.py migrate
will raise this complaint:
django.db.utils.OperationalError: (1054, "Unknown column 'projectDescription' in 'codermatch_ad'")
When this happend first, I tried to delete all entries from the database in phpmyadmin.
But then I realized: It’s not about the entries – it’s about the fields.
If I delete all entries from the database of the respective model, I will still see the field names inside.
Therefore I delete (drop) the complete database instead.
Then I create a new one without entries and without fields to avoid migration conflicts all the time.
amend Ad model
- change project-related properties in
Ad
model and appropriate form to ad-related - change
createAdForm
to fit the new model properties - add
AdPurpose
class andmodels.IntegerField(choices=...)
, so that people can choose between different ad types (project presentation, project search, something else)
class Ad(models.Model):
...
class AdPurpose(models.IntegerChoices):
PRESENT_A_PROJECT = 1
FIND_A_PROJECT = 2
SOMETHING_ELSE = 3
...
adPurpose = models.IntegerField(choices=AdPurpose.choices, default=AdPurpose.PRESENT_A_PROJECT)
PhpMyAdmin and fix most recent classifieds | Day 038 (2022-02-14)
- refactor Ad model (move all methods up)
- add email field
creatorEmail
to Ad model and AdCreationForm - remove contactDetails from AdCreationForm
- add
BooleanField
(showEmailPublic
) to Ad model and AdCreationForm (to check whether email should be shown in public or not) - fix: Most recent classifieds don’t show the list of classifieds on the landing page anymore
How to access phpmyadmin
in browser?
- quick reminder for myself (after clearing the browser cache)
Access phpmyadmin
in the browser by typing either localhost/phpmyadmin
or 127.0.0.1/phpmyadmin
.
fix: show Most recent Classifieds again
- change reference in templating language of index.html from
projectTitle
-property to newadTitle
-property.
That way Django can find the property again, after I changed the property name in the Ad model some time ago.
old index.html (with projectTitle
):
{% if latestAdList %}
<h2>Most recent classifieds</h2>
<ul>
{% for ad in latestAdList %}
<li>
<a href="{% url 'codermatch:adDetail' adId=ad.id %}">{{ ad.projectTitle }}</a>
</li>
{% endfor %}
</ul>
{% else %}
<p>No classifieds are available...</p>
{% endif %}
amended index.html (with more generic adTitle
):
{% if latestAdList %}
<h2>Most recent classifieds</h2>
<ul>
{% for ad in latestAdList %}
<li>
<a href="{% url 'codermatch:adDetail' adId=ad.id %}">{{ ad.adTitle }}</a>
</li>
{% endfor %}
</ul>
{% else %}
<p>No classifieds are available...</p>
{% endif %}
Good practice: Note down, where to go on
After not doing it for several days, I noticed that it’s actually a really good practice for #100DaysOfCode to note down where I want to go on, when starting the next day.
That way I save some time in the morning and don’t need to bother my freshly recovered mind with desisional tasks in the morning.
TemplateView? | Day 039 (2022-02-15)
- delete superfluous parts from code (remnant from tinkering earlier)
- remove superfluous code (from earlier approaches from detail view)
- try to build my detail view using a TemplateView Base view
❓QUESTIONS
- How does
*args
and**kwargs
in Python work? - How to build a TemplateView in Django?
- How to know which view to use in Django?
- What’s a mixin (compared to a class)?
- What can they do and how do they work?
- Why do mixins not have parenthesis with arguments?
Classes don’t need arguments – reminder💡
A class could even look like this:
class Cat:
pass
But the class could even take arguments without having a parethesis itself – as long as it has an __init__
method which specifies arguments instead:
class Cat:
def __init__(self, name, age):
self.name = name
self.age = age
You could call it for example like:
cat = Cat('Kitty', 7)
print(cat.name)
print(cat.age)
Views: find the most suitable one | Day 040 (2022-02-16)
- trying to figure out which views to use and how to get an overview of their functionalities to choose wisely
- read Writing views topic guide – not much new…
- decided to switch to
DetailView
and not building everything from scratch using a generic base view (View
,TemplateView
orRedirectView
) - write hands-on summary: How to find most suitable view
What I’ve learned and accomplished this week – retrospective summary
I’ve learned and done several things this week:
- mainly database related bug fixes and how to treat database issues
- finding the most suitable view in Django😲
Thanks again to all the people who support me!💚
How to go on?
In the subsequent blogpost about the following week of my #100DaysOfCode challenge you can read how I really continued my journey.
Or find the collection of all my posts related to the #100DaysOfCode challenge.
Besides you are very welcome to follow my daily progress on Twitter.
Taking up the #100DaysOfCode challenge too?
Are you also working on the #100DaysOfCode challenge?
Are you planning to take up the challenge in the future or did you already do it in the past?
What are your personal challenges on the way?
Neueste Kommentare