Is it possible to add a variable to Django Model Field.choices? - django

Is it possible to add a variable to Django Model Field.choices?
I lose functionality when I have to add it statically.
IP_CHOICES = (
('192.168.1.0', '192.168.1.0'),
)
ip_address = models.IPAddressField(choices=IP_CHOICES, unique=True, blank=True)
I use a Python IP Interpreter called IPy, to calculate the correct IP block.
ip = IP(self.network + slash)
for rangeip in enumerate(ip[2:-1]):
IP_CHOICES = (
("%s" %rangeip, "%s" %rangeip)
)
Is this possible? If so, please help. Been trying to hack it for the past week and got no where. Any help is appreciated.
Please view Model Class.
#IP Block Class
class IP_block(models.Model):
network = models.IPAddressField(unique=True)
slash = models.ForeignKey(Subnet, verbose_name='CIDR')
subnet = models.CharField(max_length=64, blank=True)
gateway_ip = models.CharField(max_length=64, blank=True)
broadcast_ip = models.CharField(max_length=64, blank=True)
ip_range = models.TextField(blank=True, verbose_name='Available IP Range')
dslam = models.ManyToManyField(Dslam, verbose_name='Dslam', blank=True)
#ip block and range save function
def save(self, *args, **kwargs):
slash = unicode(self.slash)
broadcast = IP(self.network + slash).broadcast()
subnet = IP(self.network+slash).strNetmask()
self.broadcast_ip = broadcast
self.subnet = subnet
ip = IP(self.network + slash)
for gateway in ip[1]:
self.gateway_ip = gateway
#rangeip for loop
ip = IP(self.network + slash)
if self.ip_range:
print 'no override'
else:
for rangeip in ip[2:-1]:
self.ip_range += "%s\n" %rangeip
IP_CHOICE = "(%s" %rangeip + ", %s)," %rangeip
#ip_list select
ip_list = models.CharField(choices=IP_CHOICE, max_length=128, blank=True)
super(IP_block, self).save(*args, **kwargs)
class Meta:
verbose_name_plural = 'IP Blocks'
def __unicode__(self):
return self.network

You have many fairly basic errors here. For example, in your suggested syntax:
for rangeip in enumerate(whatever):
IP_CHOICES = (do_something)
It should be obvious to you that you are simply overwriting IP_CHOICES each time through the loop. At the end of the loop, it will simply have the value of the last iteration, which isn't by itself in a suitable format for choices.
You have this same pattern a number of times. Please think about what it is actually doing.
But there's an even worse error in your save function, where you have this line:
ip_list = models.CharField(choices=IP_CHOICE, max_length=128, blank=True)
I have absolutely no idea what you think that is doing. You can't define a field in the middle of a save method. You can set a field's value, but you can't suddenly define a new field (again, please think about it: how would that work with the database? And remember fields are class-level attributes: all instances of that model need to have the same field selection).
It's almost impossible to understand what you are actually trying to do. I think you are trying to provide a choice of IP addresses for one field in the model (ip_list), once the user has set the range in another field (ip_range). (It would have been useful if you'd stated that explicitly up front.)
The place to do this is in the form, not in the model. Setting choices on a model field is really just a shortcut to setting them on forms automatically created from that model, but if you need to do something dynamic you need to define the form yourself and put the logic there. I guess it would be something like this:
class IPBlockForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(IPForm, self).__init__(*args, **kwargs)
if self.instance and self.instance.ip_range:
ip_list_choices = get_ip_list_from_wherever(self.instance_ip_range)
self.fields['ip_list'] = forms.ChoiceField(choices=ip_list_choices)
class Meta:
model = IP_block
But naturally you need to fix the other logic errors in your save method, which I mention above, first.

Related

How to correctly write a condition in view Django?

The meaning of the program is to select analogues from the list and link them. I bind all values.
I think the problem is in the wrong if. How to fix it
My view:
def editpart(request, id, **kwargs):
if request.method == 'POST':
part.name = request.POST.get("name")
part.description = request.POST.get("description")
analogs = Part.objects.all()
for analog_zap in analogs:
analog = analog_zap.analog
if Part.objects.filter(analog_analog = analog):
part.analog.add(analog_zap.id)
My model:
class Part(models.Model):
name = models.CharField('Название', max_length=100)
analog = models.ManyToManyField('self', blank=True, related_name='AnalogParts')
I'm just going to assume you have gotten a part object before trying to assign the following:
part.name = request.POST.get("name")
part.description = request.POST.get("description")
Whether this was intended to update the "retrieved part object" or not, I'd recommend that you have instead two fresh variables to collect the info from the post request, then update the part object with these if any related info were found in the database.
name = request.POST.get("name")
description = request.POST.get("description")
As for the real issue here... Not sure I'm understanding your question much but I do see a problem with one of your if statements though. You have:
for analog_zap in analogs:
analog = analog_zap.analog
if Part.objects.filter(analog_analog = analog): # problem here...
part.analog.add(analog_zap.id)
As you've posted:
class Part(models.Model):
name = models.CharField('Название', max_length=100)
analog = models.ManyToManyField('self', blank=True, related_name='AnalogParts') # right here...
The Part model has a field called analog, not analog_analog: maybe you meant analog__analog. But maybe you should try checking by: if Part.objects.filter(analog__pk=analog.pk) or if Part.objects.filter(analog__in=[analog]).distinct().
Furthermore, what you might want to do is to check if something exists, so add .exists() to the end of if Part.objects.filter(analog__pk=analog.pk). Example:
if Part.objects.filter(analog__pk=analog.pk).exists():
...
Looking like:
for analog_zap in analogs:
analog = analog_zap.analog
if Part.objects.filter(analog__pk=analog.pk).exists():
part.analog.add(analog_zap.id)
# update the name and description here as well with the values retrieved from the post request
part.name = name
part.description = description
You could try that.
UPDATES
What worked in this context is:
Part.objects.filter(analog__in=[analog_zap]).distinct()

Django difficulty saving multiple model objects within save method

This is a hard question for me to describe, but I will do my best here.
I have a model that is for a calendar event:
class Event(models.Model):
account = models.ForeignKey(Account, related_name="event_account")
location = models.ForeignKey(Location, related_name="event_location")
patient = models.ManyToManyField(Patient)
datetime_start = models.DateTimeField()
datetime_end = models.DateTimeField()
last_update = models.DateTimeField(auto_now=False, auto_now_add=False, null=True, blank=True)
event_series = models.ForeignKey(EventSeries, related_name="event_series", null=True, blank=True)
is_original_event = models.BooleanField(default=True)
When this is saved I am overriding the save() method to check and see if the event_series (recurring events) is set. If it is, then I need to iteratively create another event object for each recurring date.
The following seems to work, though it may not be the best approach:
def save(self, *args, **kwargs):
if self.pk is None:
if self.event_series is not None and self.is_original_event is True :
recurrence_rules = EventSeries.objects.get(pk=self.event_series.pk)
rr_freq = DAILY
if recurrence_rules.frequency == "DAILY":
rr_freq = DAILY
elif recurrence_rules.frequency == "WEEKLY":
rr_freq = WEEKLY
elif recurrence_rules.frequency == "MONTHLY":
rr_freq = MONTHLY
elif recurrence_rules.frequency == "YEARLY":
rr_freq = YEARLY
rlist = list(rrule(rr_freq, count=recurrence_rules.recurrences, dtstart=self.datetime_start))
for revent in rlist:
evnt = Event.objects.create(account = self.account, location = self.location, datetime_start = revent, datetime_end = revent, is_original_event = False, event_series = self.event_series)
super(Event, evnt).save(*args, **kwargs)
super(Event, self).save(*args, **kwargs)
However, the real problem I am finding is that using this methodology and saving from the Admin forms, it is creating the recurring events, but if I try to get self.patient which is a M2M field, I keep getting this error:
'Event' instance needs to have a primary key value before a many-to-many relationship can be used
My main question is about this m2m error, but also if you have any feedback on the nested saving for recurring events, that would be great as well.
Thanks much!
If the code trying to access self.patient is in the save method and happens before the instance has been saved then it's clearly the expected behaviour. Remember that Model objects are just a thin (well...) wrapper over a SQL database... Also, even if you first save your new instance then try to access self.patient from the save method you'll still have an empty queryset since the m2m won't have been saved by the admin form yet.
IOW, if you have something to do that depends on m2m being set, you'll have to put it in a distinct method and ensure that method get called when appropriate
About your code snippet:
1/ the recurrence_rules = EventSeries.objects.get(pk=self.event_series.pk) is just redundant, since you alreay have the very same object under the name self.event_series
2/ there's no need to call save on the events you create with Event.objects.create - the ModelManager.create method really create an instance (that is: save it to the database).

Django query hitting the db for every iteration

I have a some model.py like so:
class Muestraonline(models.Model):
accessionnumber = models.ForeignKey(Muestra, related_name='online_accessionnumber')
muestraid = models.ForeignKey(Muestra)
taxonid = models.ForeignKey(Taxon, null=True, blank=True)
...
class Muestra(models.Model):
muestraid = models.IntegerField(primary_key=True, db_column='MuestraID') # Field name made lowercase.
latitudedecimal = models.DecimalField(decimal_places=6, null=True, max_digits=20, db_column='LatitudeDecimal', blank=True) # Field name made lowercase.
longitudedecimal = models.DecimalField(decimal_places=6, null=True, max_digits=20, db_column='LongitudeDecimal', blank=True) # Field name made lowercase.
...
And my view.py I want to get the unique specimen and find all specimens which share that taxonid. For the related specimens I just need the lat/long info:
def specimen_detail(request, accession_number=None, specimen_id=None):
specimen = Muestraonline.objects.get(accessionnumber=accession_number, muestraid=specimen_id)
related_specimens = Muestraonline.objects.filter(taxonid=specimen.taxonid).exclude(id=specimen.id)
# create array for the related specimen points
related_coords = []
# loop through results and populate array
for relative in related_specimens:
latlon = (format(relative.muestraid.latitudedecimal), format(relative.muestraid.longitudedecimal))
related_coords.append(latlon)
related_coords = simplejson.dumps(related_coords)
But when I loop through related_specimens it ends up hitting the db once for each relative. Shouldn't I be able to get the latitudedecimal and longitudedecimal values in the format I need with only one extra db query? I know I missing something very basic in my approach here, just not sure of the best way to get this done.
Any help would be much appreciated.
Just use select_related in your QuerySet:
related_specimens = Muestraonline.objects.filter(taxonid=specimen.taxonid).exclude(id=specimen.id).select_related('muestraid')
That will join your Muestraonline model to Muestra behind the scenes and each Muestraonline instance returned by the QuerySet will also contain a cached instance of Muestra.

Track the number of "page views" or "hits" of an object?

I am sure that someone has a pluggable app (or tutorial) out there that approximates this, but I have having trouble finding it: I want to be able to track the number of "views" a particular object has (just like a question here on stackoverflow has a "view count").
If the user isn't logged in, I wouldn't mind attempting to place a cookie (or log an IP) so they can't inadvertently run up the view count by refreshing the page; and if a user is logged in, only allow them one "view" across sessions/browsers/IP addresses. I don't think I need it any fancier than that.
I figure the best way to do this is with Middleware that is decoupled from the various models I want to track and using an F expression (of sorts) -- other questions on StackOverflow have alluded to this (1), (2), (3).
But I wonder if this code exists out in the wild already -- because I am not the savviest coder and I'm sure someone could do it better. Smile.
Have you seen it?
I am not sure if it's in the best taste to answer my own question but, after a bit of work, I put together an app that solves the problems in earnest: django-hitcount.
You can read about how to use it at the documentation page.
The ideas for django-hitcount came came from both of my two original answers (Teebes -and- vikingosegundo), which really got me started thinking about the whole thing.
This is my first attempt at sharing a pluggable app with the community and hope someone else finds it useful. Thanks!
You should use the django built-in session framework, it already does a lot of this for you. I implemented this in the following way with a Q&A app where I wanted to track views:
in models.py:
class QuestionView(models.Model):
question = models.ForeignKey(Question, related_name='questionviews', on_delete=models.CASCADE)
ip = models.CharField(max_length=40)
session = models.CharField(max_length=40)
created = models.DateTimeField(default=datetime.datetime.now())
in views.py:
def record_view(request, question_id):
question = get_object_or_404(Question, pk=question_id)
if not QuestionView.objects.filter(
question=question,
session=request.session.session_key):
view = QuestionView(question=question,
ip=request.META['REMOTE_ADDR'],
created=datetime.datetime.now(),
session=request.session.session_key)
view.save()
return HttpResponse(u"%s" % QuestionView.objects.filter(question=question).count())
Vikingosegundo is probably right though that using content-type is probably the more reusable solution but definitely don't reinvent the wheel in terms of tracking sessions, Django already does that!
Last thing, you should probably have the view that records the hit be either called via Ajax or a css link so that search engines don't rev up your counts.
Hope that helps!
You could create a generic Hit model
class Hit(models.Model):
date = models.DateTimeField(auto_now=True)
content_type = models.ForeignKey(ContentType)
object_id = models.PositiveIntegerField()
content_object = generic.GenericForeignKey('content_type', 'object_id')
In your view.py you write this function:
def render_to_response_hit_count(request,template_path,keys,response):
for key in keys:
for i in response[key]:
Hit(content_object=i).save()
return render_to_response(template_path, response)
and the views that you are interested in return
return render_to_response_hit_count(request, 'map/list.html',['list',],
{
'list': l,
})
This approach gives you the power, not only to count the hit, but to filter the hit-history by time, contenttype and so on...
As the hit-table might be growing fast, you should think about a deletion strategy.
I know this question is an old one and also thornomad has put an app to solve the problem and inspire me with me solution. I would like to share this solution since I didn't find much information about this topic and it may help someone else.
My approach is to make a generic model can be used with any view based on the view path (url).
models.py
class UrlHit(models.Model):
url = models.URLField()
hits = models.PositiveIntegerField(default=0)
def __str__(self):
return str(self.url)
def increase(self):
self.hits += 1
self.save()
class HitCount(models.Model):
url_hit = models.ForeignKey(UrlHit, editable=False, on_delete=models.CASCADE)
ip = models.CharField(max_length=40)
session = models.CharField(max_length=40)
date = models.DateTimeField(auto_now=True)
views.py
def get_client_ip(request):
x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
if x_forwarded_for:
ip = x_forwarded_for.split(',')[0]
else:
ip = request.META.get('REMOTE_ADDR')
return ip
def hit_count(request):
if not request.session.session_key:
request.session.save()
s_key = request.session.session_key
ip = get_client_ip(request)
url, url_created = UrlHit.objects.get_or_create(url=request.path)
if url_created:
track, created = HitCount.objects.get_or_create(url_hit=url, ip=ip, session=s_key)
if created:
url.increase()
request.session[ip] = ip
request.session[request.path] = request.path
else:
if ip and request.path not in request.session:
track, created = HitCount.objects.get_or_create(url_hit=url, ip=ip, session=s_key)
if created:
url.increase()
request.session[ip] = ip
request.session[request.path] = request.path
return url.hits
I did this by creating a model PageViews and making a column "Hits" in it. Every time when Homepage url is hit. I increment the first and only row of column Hit and render it to the template. Here how it looks.
Views.py
def Home(request):
if(PageView.objects.count()<=0):
x=PageView.objects.create()
x.save()
else:
x=PageView.objects.all()[0]
x.hits=x.hits+1
x.save()
context={'page':x.hits}
return render(request,'home.html',context=context)
Models.py
class PageView(models.Model):
hits=models.IntegerField(default=0)
I did it using cookies. Don't know if it's a good idea to do that or not. The following code looks for an already set cookie first if it exists it increases the total_view counter if it is not there the it increases both total_views and unique_views. Both total_views and unique_views are a field of a Django model.
def view(request):
...
cookie_state = request.COOKIES.get('viewed_post_%s' % post_name_slug)
response = render_to_response('community/post.html',context_instance=RequestContext(request, context_dict))
if cookie_state:
Post.objects.filter(id=post.id).update(total_views=F('total_views') + 1)
else:
Post.objects.filter(id=post.id).update(unique_views=F('unique_views') + 1)
Post.objects.filter(id=post.id).update(total_views=F('total_views') + 1)
response.set_cookie('viewed_post_%s' % post_name_slug , True, max_age=2678400)
return response

Sorting products after dateinterval and weight

What I want is to be able to get this weeks/this months/this years etc. hotest products. So I have a model named ProductStatistics that will log each hit and each purchase on a day-to-day basis. This is the models I have got to work with:
class Product(models.Model):
name = models.CharField(_("Name"), max_length=200)
slug = models.SlugField()
description = models.TextField(_("Description"))
picture = models.ImageField(upload_to=product_upload_path, blank=True)
category = models.ForeignKey(ProductCategory)
prices = models.ManyToManyField(Store, through='Pricing')
objects = ProductManager()
class Meta:
ordering = ('name', )
def __unicode__(self):
return self.name
class ProductStatistic(models.Model):
# There is only 1 `date` each day. `date` is
# set by datetime.today().date()
date = models.DateTimeField(default=datetime.now)
hits = models.PositiveIntegerField(default=0)
purchases = models.PositiveIntegerField(default=0)
product = models.ForeignKey(Product)
class Meta:
ordering = ('product', 'date', 'purchases', 'hits', )
def __unicode__(self):
return u'%s: %s - %s hits, %s purchases' % (self.product.name, str(self.date).split(' ')[0], self.hits, self.purchases)
How would you go about sorting the Products after say (hits+(purchases*2)) the latest week?
This structure isn't set in stone either, so if you would structure the models in any other way, please tell!
first idea:
in the view you could query for today's ProductStatistic, than loop over the the queryset and add a variable ranking to every object and add that object to a list. Then just sort after ranking and pass the list to ur template.
second idea:
create a filed ranking (hidden for admin) and write the solution of ur formula each time the object is saved to the database by using a pre_save-signal. Now you can do ProductStatistic.objects.filter(date=today()).order_by('ranking')
Both ideas have pros&cons, but I like second idea more
edit as response to the comment
Use Idea 2
Write a view, where you filter like this: ProductStatistic.objects.filter(product= aProductObject, date__gte=startdate, date__lte=enddate)
loop over the queryset and do somthing like aProductObject.ranking+= qs_obj.ranking
pass a sorted list of the queryset to the template
Basically a combination of both ideas
edit to your own answer
Your solution isn't far away from what I suggested — but in sql-space.
But another solution:
Make a Hit-Model:
class Hit(models.Model):
date = models.DateTimeFiles(auto_now=True)
product = models.ForeignKey(Product)
purchased= models.BooleanField(default=False)
session = models.CharField(max_length=40)
in your view for displaying a product you check, if there is a Hit-object with the session, and object. if not, you save it
Hit(product=product,
date=datetime.datetime.now(),
session=request.session.session_key).save()
in your purchase view you get the Hit-object and set purchased=True
Now in your templates/DB-Tools you can do real statistics.
Of course it can generate a lot of DB-Objects over the time, so you should think about a good deletion-strategy (like sum the data after 3 month into another model MonthlyHitArchive)
If you think, that displaying this statistics would generate to much DB-Traffic, you should consider using some caching.
I solved this the way I didn't want to solve it. I added week_rank, month_rank and overall_rank to Product and then I just added the following to my ProductStatistic model.
def calculate_rank(self, days_ago=7, overall=False):
if overall:
return self._default_manager.all().extra(
select = {'rank': 'SUM(hits + (clicks * 2))'}
).values()[0]['rank']
else:
return self._default_manager.filter(
date__gte = datetime.today()-timedelta(days_ago),
date__lte = datetime.today()
).extra(
select = {'rank': 'SUM(hits + (clicks * 2))'}
).values()[0]['rank']
def save(self, *args, **kwargs):
super(ProductStatistic, self).save(*args, **kwargs)
t = Product.objects.get(pk=self.product.id)
t.week_rank = self.calculate_rank()
t.month_rank = self.calculate_rank(30)
t.overall_rank = self.calculate_rank(overall=True)
t.save()
I'll leave it unsolved if there is a better solution.