Getting a TabError - django-apps

I am absolutely new to Django and Python and is following a tutorial someone did a few years ago to the letter. I have the following code snippet and when I save it my development Django server give me a error message:
File: "/path/to/my/file/apps.py", line 7
def ready(self):
TabError: inconsistent use of tabs and spaces in indentation
from django.apps import AppConfig
class UsersConfig(AppConfig):
name = 'users'
def ready(self):
import users.signals
When I save the file I get the error message above. I also have another file very similar to this one and that one works well. Any idea where I need to change? This code is part of code to create a profile for a user on the site when the user registers on the site.

def needs to be under name. You had added an extra space before def.
To avoid such errors in the future, use a better Text Editor or try out online auto-formatters.
Proper code-
from django.apps import AppConfig
class UsersConfig(AppConfig):
name = 'users'
def ready(self):
import users.signals

Related

How to make discord embed pages that can be browsed? (discord.py)

I am trying to make a command that can add to a database and then the info is extracted from database and sent in an embed. So, I tried to make embed pages, example if 10 entries are made in the database, it automatically creates a page 2 that can be accessed using buttons.
I tried using for loop like this:
pages = (entries // 10) + 1
for i in range(pages):
embed=discord.Embed(title=f"Page {i+1}")
db[f"pagesembed_{i+1}"]=embed
But I got a JSON decode error, so I decided to convert the embed value to string like this:
embed=str(discord.Embed(title=f"Page {i+1}"))
Then when I try to load into a message, it gives me Application Command raised an exception: AttributeError: 'str' object has no attribute 'to_dict'
I don't know what to do, I have contemplated using SQLite for storing the page embeds, maybe that should work but I need to ask if there is another way of doing it, I would really appreciate if someone would help! Thank you.
You can dump the embed class with pickle and than load it from the database
save example:
import pickle
import discord
exampleEmbedToSave = discord.Embed(title="example", description="example")
db["embed"] = pickle.dumps(exampleEmbedToSave) # the function pickle.dumps will dump the class into a string
Load example:
import pickle
import discord
loadedEmbed = pickle.loads(db["embed"]) # pickle.loads is used to load the class from the string
# >> In a command:
await channel.send(embed=loadedEmbed)

How to write batch of data to Django's sqlite db from a custom written file?

For a pet project I am working on I need to import list of people to sqlite db. I have 'Staff' model, as well as a users.csv file with list of users. Here is how I am doing it:
import csv
from staff.models import Staff
with open('users.csv') as csv_file:
csv_reader = csv.DictReader(csv_file, delimiter=',')
line_count = 0
for row in csv_reader:
firstname = row['firstname']
lastname = row['lastname']
email = row['email']
staff = Staff(firstname=firstname, lastname=lastname, email=email)
staff.save()
csv_file.close()
However, I am getting below error message:
raise ImproperlyConfigured(
django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings.
Is what I am doing correct? If yes what I am missing here?
Django needs some environment variables when it is being bootstrapped to run. DJANGO_SETTINGS_MODULE is one of these, which is then used to configure Django from the settings. Typically many developers don't even notice because if you stay in Django-land it isn't a big deal. Take a look at manage.py and you'll notice it sets it in that file.
The simplest thing is to stay in django-land and run your script in its framework. I recommend creating a management command. Perhaps a more proper way is to create a data migration and put the data in a storage place like S3 if this is something many many people need to do for local databases... but it seems like a management command is the way to go for you. Another option (and the simplest if this is really just a one-time thing) is to just run this from the django shell. I'll put that at the bottom.
It's very simple and you can drop in your code almost as you have it. Here are the docs :) https://docs.djangoproject.com/en/3.2/howto/custom-management-commands/
For you it might look something like this:
/app/management/commands/load_people.py <-- the file name here is what manage.py will use to run the command later.
from django.core.management.base import BaseCommand, CommandError
import csv
from staff.models import Staff
class Command(BaseCommand):
help = 'load people from csv'
def handle(self, *args, **options):
with open('users.csv') as csv_file:
csv_reader = csv.DictReader(csv_file, delimiter=',')
line_count = 0
for row in csv_reader:
firstname = row['firstname']
lastname = row['lastname']
email = row['email']
staff = Staff(firstname=firstname, lastname=lastname, email=email)
staff.save()
# csv_file.close() # you don't need this since you used `with`
which you would call like this:
python manage.py load_people
Finally, the simplest solution is to just run the code in the Django shell.
python manage.py shell
will open up an interactive shell with everything loaded properly. You can execute your code there and it should work.

Avoiding multiple import in Kivy when calling a function from a different file

I'm developing a small app using kivy and python3.6 (I'm still a beginner). I'm planning to separate the code in different files for clarity, however I have encountered a problem in a specific situation. I have made minimal working example to illustrate.
I have the following files:
main.py
main.kv
module.py
module.kv
Here a minimal code:
main.py:
from kivy.app import App
from kivy.uix.button import Button
from kivy.lang import Builder
import module
Builder.load_file('module.kv')
class MainApp(App):
pass
def function():
print('parent function')
if __name__ == '__main__':
MainApp().run()
main.kv:
CallFunction
module.py:
from kivy.uix.button import Button
class CallFunction(Button):
def call_function(self):
from main import function
function()
module.kv:
<CallFunction>:
id : parent_button
text: 'Call parent button'
on_press: self.call_function()
So the problem is that when I run this code, I receive a warning
The file /home/kivy/python_exp/test/module.kv is loaded multiples times, you might have unwanted behaviors.
What works:
If the function I want to call is part of the main app class, there is no problem
If the function is part of the module.py there is no problem
If the function is part of another module, there is no problem
What doesn't work
I cannot call a function which is in the main.py. If I use the import the function as the beginning of module.py, kivy has a weird behavior and call everything twice. Calling within this call_function allows to have a proper interface, but I get the warning that the file has been loaded multiple time.
There are easy workarounds, I'm well aware of that, so it's more about curiosity and understanding better how the imports in kivy works. Is there a way to make it work?
I wanted to use the main.py to initialize different things at the startup of the app. In particular I wanted to create an instance of another class (not a kivy class) in the main.py and when clicking on the button on the interface, calling a method on this instance.
Thanks :)
When you import something from another python module the python virtual machine execute this module. In the call_function you import function from the main file so everytime you press the CallFunction the module.kv is loaded.
To solve this it is recommended to include the other kv files in your main kv file.
You can also move the import statement from the method to the top of the module file.
Your kv file is loaded twice because the code is executed twice. This is due to how pythons module system works and kivy just realized that loading the kv twice is probably not what you want.
Generally python objects live in a namespace. So when a function in the module foo looks up a variable the variable is searched in the namespace of the module. That way if you define two variables foo.var and bar.var (in the modules foo and bar resp.) they don't clash and get confused for each other.
The tricky thing is that the python file you execute is special: It does not create a module namespace but the __main__ namespace. Thus if you import the file you are executing as __main__ it will create a whole new namespace with new objects and execute the module code. If you import a module that was already imported in the current session the module code is not executed again, but the namespace already created is made available. You don't even need two files for that, put the following in test.py:
print("hello!")
print(__name__)
import test
If you now execute python test.py you will see two hello! and once __main__ and once test.
You can find more information on namespaces and how variable lookups works in python in the documentation.
Also if your function actually does some work and mutates an object that lives in main.py you might want to rethink the information flow. Often it is a good idea to bind the state and functions working on them together in classes and passing the objects then where they are called i.e. to CallFunction in your example.

how to update record in between a file in python

We are trying to implement a file based student record program. We have implemented the reading and writing (Append Records) Functionalities. However now we are interested in updating a particular record via Student id. We have tried using the replace() function to replace the record but this ends up replacing all occurrences of the data in the file which makes it ambiguous.We have also tried over writing data using seek() but it does not helps much.example code is as follows.
import fileinput
import sys
for i,line in enumerate(fileinput('file_name.txt', inplace=1)):
sys.stdout.write(line.replace('old','new')
Any help shall be great.
Assume your input file is
1:Naveen Kumar:Chennai
2:Joseph Nirmal:Bangalore
and you want to change the name of student id 2 to Joseph Nirmal Kumar, then the following code should do
import fileinput
import sys
# change name for student 2
for line in fileinput.input('records.txt', inplace=1):
id,name,location = line.split(':')
if id == '2':
sys.stdout.write('{}:{}:{}'.format(id,'Joseph Nirmal Kumar',location))
else:
sys.stdout.write(line)
then the file will become
1:Naveen Kumar:Chennai
2:Joseph Nirmal Kumar:Bangalore
Hope that helps. I would recommend to try other data persistence options available in python

Adjusting python auto-complete behavior

I have been using Aptana with pydev and IDLE to learn python2.7. And it has done a fair job of helping me to learn, except for when I came across this microblog tutorial. In it there is a line from flask.ext.sqlalchemy import SQLAlchemy which leads to a db = SQLAlchemy( line, in Aptana there is no help, no doc string, no examples of what could go in there. Even worse, all of this:
class User(db.Model):
id = db.Column(db.Integer, primary_key = True)
nickname = db.Column(db.String(64), index = True, unique = True)
email = db.Column(db.String(120), index = True, unique = True)
role = db.Column(db.SmallInteger, default = ROLE_USER)
Is in red, no idea how to pull it apart to learn its syntax. However, when I do:
from flask.ext.sqlalchemy import SQLAlchemy
from flask import Flask
app = Flask(__name__)
db = SQLAlchemy(app)
class User(db.Model):
id = db.Column(db.Integer,primary_key = True)
In IDLE, I am getting auto-completion, doc strings, I can see what else can go in there, I can learn.
I thought the answer would exist with a new IDE like environment, I got it in my head that VIM might be helpful. I am on windows, so GIT, MinGW, TortoiseHG, _vimrc, vimfiles, {autoload,bundle}, pathogen.vim, jedi-vim, building vim from source (for some reason the ones I kept finding didn't have python enabled) were not easy task, considering first time exposure and all at once. So I have a vim that can edit python code, and from flask.ext.sqlalchemy import SQLAlchemy in vim has the same result as in Aptana, no help.
Can someone explain to me why IDLE is able to help but Aptana/Pydev and Vim cannot? Can someone show me how they can help?
This is what is in flask.ext.__init__().py
# -*- coding: utf-8 -*-
"""
flask.ext
~~~~~~~~~
Redirect imports for extensions. This module basically makes it possible
for us to transition from flaskext.foo to flask_foo without having to
force all extensions to upgrade at the same time.
When a user does ``from flask.ext.foo import bar`` it will attempt to
import ``from flask_foo import bar`` first and when that fails it will
try to import ``from flaskext.foo import bar``.
We're switching from namespace packages because it was just too painful for
everybody involved.
:copyright: (c) 2011 by Armin Ronacher.
:license: BSD, see LICENSE for more details.
"""
def setup():
from ..exthook import ExtensionImporter
importer = ExtensionImporter(['flask_%s', 'flaskext.%s'], __name__)
importer.install()
setup()
del setup
So in my case from flask.ext.sqlalchemy import SQLAlchemy translates to "look in site-packages for the flask_sqlalchemy.py and in that file find SQLAlchemy" which is, in this case, a big class. How can I make Aptana and vim see this, like IDLE does?
This link solved it, but I used C:\Python27\Lib;C:\Python27\DLLs;C:\Python27\Lib;C:\Python27\Lib\site-packages as my Variable value and I deleted and restored my interpreter in pydev, seems to have worked.

Resources