I'm just learning Python and Django.
What I want to do is something like this
csvobject = CSVViewer(file)
rows = csvobject.get_row_count()
This is what I have so far. Remember this is all new to me so I'm looking for a an explanation. Thanks.
class CSVViewer:
def __init__(self, file=None):
self.file = file
def read_file(self):
data = []
file_read = csv.reader(self.file)
for row in file_read:
data.append(row)
return data
def get_row_count(self):
return len(read_file(self))
I am having problems with read_file(self)
Well, first of all, It seems you're missing import csv in order to csv.reader(self.file) works in the def read_line(self) method.
Second, you must call the instance method read_file like this self.read_file() in the get_row_count method. This should work:
import csv
class CSVViewer:
def __init__(self, file=None):
self.file = file
def read_file(self):
data = []
file_read = csv.reader([self.file])
for row in file_read:
data.append(row)
return data
def get_row_count(self):
return len(self.read_file())
Related
I need to pass an integer variable to the class in forms.py
form.py
class GeeksForm(forms.Form):
def __init__(self, *args,number, **kwargs):
super().__init__(*args, **kwargs)
filename = "downloaded{}.csv".format(number)
data = open(filename, encoding = "utf8")
csv_data = csv.reader(data)
data_lines = list(csv_data)
property_dic = {}
...created dictionary...
key1 = forms.ChoiceField(choices = property_dic[list1[i]] )
so as per comment below, am throwing away key1 after init ends not actually creating a field.
so how to fix this?
how to construct the form field above init . looked documentation. couldnt understand.
and override it. with dictionary data
You override the constructor and process the number. I would however advice to use a named parameter, because a Django form already has some positional parameters, making it quite "ambiguous":
class GeeksForm(forms.Form):
def __init__(self, *args, number, **kwargs):
super().__init__(*args, **kwargs)
# do something with number
# …
then you construct the form with:
def name_view(request, num1):
form = forms.GeeksForm(request.POST, number=num1)
I am importing a file with django import-export and I want to take the values of each row.
For example:
import_resource = ImportResource()
dataset = Dataset()
imported_data = dataset.load(import_file.read().decode('utf-8'))
result = import_resource.import_data(dataset, dry_run=True)
I iterate through the rows of the Result with result.rows and each row seems to have a raw_values property but it returns empty.
Try with the code below.
class OtherResource(resources.ModelResource):
"""
My code
"""
def before_import_row(self, row, **kwargs):
row['created_by'] = kwargs.get('user')
row['modified_by'] = kwargs.get('user')
class MyClassAdmin(ImportMixin, admin.ModelAdmin):
resource_class = OtherResource
def import_data(self, dataset, dry_run=False, raise_errors=False, use_transactions=None, collect_failed_rows=False, **kwargs):
"""
Getting the user's request to pass it to the import
"""
result = OtherResource.import_data(dataset, dry_run=False, raise_errors=False, use_transactions=None, user=self.request.user)
return result
You have to remember there are a lot of actions such as: before_import_row, after_import_row among others.
I'm looking for a simple tutorial explaining how to write items to Rethinkdb from scrapy. The equivalent can be found for MongoDB here.
Here is a translation of "Write items to MongoDB" line for line with RethinkDB.
A couple notes:
I'm not sure where crawler.settings are set.
The scrapy docs say process_item's second param item can be an
object or dict, so the .insert(dict(item)) cast/conversion is probably necessary.
import rethinkdb as r
class RethinkDBPipeline(object):
table_name = 'scrapy_items'
def __init__(self, rethinkdb_uri, rethinkdb_port, rethinkdb_db):
self.rethinkdb_uri = rethinkdb_uri
self.rethinkdb_port = rethinkdb_port
self.rethinkdb_db = rethinkdb_db
#classmethod
def from_crawler(cls, crawler):
return cls(
rethinkdb_uri=crawler.settings.get('RETHINKDB_URI'),
rethinkdb_db=crawler.settings.get('RETHINKDB_DATABASE', 'items')
)
def open_spider(self, spider):
self.conn = r.connect(
host = self.rethinkdb_uri,
port = self.rethinkdb_port,
db = self.rethinkdb_db)
def close_spider(self, spider):
self.conn.close()
def process_item(self, item, spider):
r.table(self.table_name).insert(dict(item)).run(self.conn)
return item
Let's assume I have the following table class:
class TestTable(tables.Table):
id = tables.Column()
description = tables.Column()
def render_description(self, value):
return mark_safe('''<a href=%s>%s</a>''' % (???, value))
Is it possible to access the value of the column "id" in the render method, so that I can build up a link which leads to the id but shows the text which depends on the 'description'-field?
Thanks in advance!
From a quick glance at the docs for render_FOO it looks like you can just do:
class TestTable(tables.Table):
id = tables.Column()
description = tables.Column()
def render_description(self, value, record):
return mark_safe('''<a href=%s>%s</a>''' % (record.id, value)
Not sure of the exact shape of a row record, so it might be record['id'], the link to the docs should help with exploration...
#Darb Thank you, that option works perfectly. However I was wondering if there is any way to do this using accesors instead of hacking a text column to output html...
In my case I use
# tables.py
from django.core.urlresolvers import reverse
from django.utils.safestring import mark_safe
#...
class FieldTable(tables.Table):
allows__count = tables.LinkColumn(viewname=None, attrs={'td': {'class': 'leftA'}},
verbose_name='No. of Allowed values')
def __init__(self, *args, **kwargs):
super(FieldTable, self).__init__(*args, **kwargs)
def render_allows__count(self, value, record):
if value!=0:
a = reverse(viewname='dict:field_detail',
kwargs=
{'field_slug': record.slug,
'extract_slug': record.extract.slug,
'system_slug': record.extract.system.slug})
return mark_safe('<a href={}>{}</a>'.format(a, value))
However I would like to replace the mark_safe, for something that calls the accessor of allows__count and returns the reverse hyperlink and the value...
Anyway works for know
I use a snippet in http://www.djangosnippets.org/snippets/1034/ for my Model inheritance. It works fine at the first. However, after I delete some elements in database, the code works wrong.
As I debug, I found that the problem is reside in the method: as_leaf_class.
In the following code:
if (model == Meal):
return self
return model.objects.get(id=self.id)
the last line will raise exception when the element is deleted.
Anyone could give a solution for this?
Model inheritance with content type and inheritance-aware manager
from django.db import models
from django.contrib.contenttypes.models import ContentType
from django.db.models.query import QuerySet
class SubclassingQuerySet(QuerySet):
def __getitem__(self, k):
result = super(SubclassingQuerySet, self).__getitem__(k)
if isinstance(result, models.Model) :
return result.as_leaf_class()
else :
return result
def __iter__(self):
for item in super(SubclassingQuerySet, self).__iter__():
yield item.as_leaf_class()
class MealManager(models.Manager):
def get_query_set(self):
return SubclassingQuerySet(self.model)
class Meal (models.Model) :
name = models.TextField(max_length=100)
content_type = models.ForeignKey(ContentType,editable=False,null=True)
objects = MealManager()
def save(self, *args, **kwargs):
if(not self.content_type):
self.content_type = ContentType.objects.get_for_model(self.__class__)
super(Meal, self).save(*args, **kwargs)
def as_leaf_class(self):
content_type = self.content_type
model = content_type.model_class()
if (model == Meal):
return self
return model.objects.get(id=self.id)
class Salad (Meal) :
too_leafy = models.BooleanField(default=False)
objects = MealManager()
I don't know if that snippet is still relevant now that you can use abstract base classes.
This lets you declare a model that is not a db table but that other models can inherit from.
First answer: Why are you trying to call as_leaf_class on a deleted object? If it hurts when you do that, don't do it.
The second answer is that you could wrap the failing line with try...except Meal.DoesNotExist, and return None or self or something.