Sorry if the question is really newbie, just learn programming
i put this in my models.py
from django.db import models
from . import func
class Materials(models.Model):
typeId = models.IntegerField()
typeName = models.CharField(max_length=250)
price = models.FloatField()
updated = models.DateTimeField(auto_now=True)
class Meta:
ordering = ('-typeId')
def __str__(Self):
return self.typeId
def insert_data_once():
rows = func.material_id()
for row in rows:
data = Materials(typeId = row[0], typeName = row[1], price = func.sell_min(row[0]))
data.save()
insert_data_once()
here is func.py
import requests
from xml.etree import ElementTree
import sqlite3
def material_id():
conn = sqlite3.connect('eve.db')
command = 'SELECT DISTINCT invTypeMaterials.materialTypeID, invTypes.typeName FROM invTypeMaterials ' \
'INNER JOIN invTypes ON invTypeMaterials.materialTypeID = invTypes.typeID ' \
'WHERE invTypes.Published = 1'
result = conn.execute(command)
rows = result.fetchall()
return rows
def sell_min(type_id):
URL = 'https://api.evemarketer.com/ec/marketstat?typeid=' + str(
type_id) + '®ionlimit=10000002&usesystem=30000142'
minerals_price = requests.get(URL)
root = ElementTree.fromstring(minerals_price.content)
for child in root[0][0][1].iter('min'):
sell_min = child.text
return float(sell_min)
where i should run the insert_data_once function in models.py, the fuction keep looping and cant run manage.py runserver
thank you
Related
My model:
class VisData(models.Model):
visdata_id = models.AutoField(primary_key=True,blank=True)
user_name = models.ForeignKey(Customer, null=True, on_delete=models.SET_NULL,blank=True)
title = models.CharField(max_length=200, null=True,blank=True)
buy_sell = models.CharField(max_length=1, null=True,blank=True)
date = models.DateField(auto_now_add=False,null=True,editable=True,blank=True)
hour = models.TimeField(auto_now=False, auto_now_add=False,null=True,editable=True,blank=True)
shares_number = models.DecimalField(decimal_places=0,default=0,max_digits=999,null=True,blank=True)
course = models.DecimalField(decimal_places=2,default=0,max_digits=999,null=True,blank=True)
fare = models.DecimalField(decimal_places=2,default=0,max_digits=999,null=True,blank=True)
def __str__(self):
return self.title
I want to assign:
total_value = (shares_number * (course - fare)) and just print it in terminal
My views:
def summaryPage(request):
visdata = VisData.objects.all()
#print(visdata)
context = {}
return render(request, 'smth/homepage.html', context)
I found some close answers but I couldn't understand the solution nor use them in my code.
What you probably need called aggregation:
from django.db.models import F, Sum
def summaryPage(request):
aggregated_data = VisData.objects.annotate(
intermid_result=F('course') - F('fare')
).annotate(
record_total=F('shares_number') * F('intermid_result')
).aggregate(
total=SUM('record_total')
)
result = aggregated_data['total']
print(result)
...
This query will annotate each record with the value of record_total = shares_number * (course - fare) and then calculate a sum for record_total of all records.
Also try to avoid using camelcase function names in Python. See here for details.
I am learning django and I have not been able to properly do two things within model clearance:
Within modelRetrieve the name fields that correspond to the imo number selected.
Autopopulate a date field with the current day plus 7 days.
Any ideas what I am doing wrong? Here is my code:
from django.db import models
from django.core.exceptions import ValidationError
from django.utils import timezone
from datetime import timedelta, datetime
def imo_validator(value):
if value < 0 or value > 9999999:
raise ValidationError(
'This is not a valid IMO number',
params={'value':value},
)
class ship(models.Model):
imo = models.IntegerField(unique=True,validators=[imo_validator])
name = models.CharField(max_length=20)
rpm = models.FloatField()
power = models.FloatField()
main_engine = models.IntegerField()
class Meta:
ordering = ['imo']
def __str__(self):
return "{}, (IMO:{})".format(self.name, self.imo)
class clearance(models.Model):
STATUSES = [
('PENDING','PENDING'),
('REJECTED','REJECTED'),
('APPROVED','APPROVED'),
]
PORTS = [
('PACAN','PACAN'),
('PABLB','PABLB'),
('PACCT','PACCT'),
('PAANP','PAANP'),
('PAANA','PAANA'),
]
date_of_request = models.DateField(default=timezone.now,blank=False,editable=True)
imo = models.ForeignKey(ship, on_delete=models.PROTECT)
port = models.CharField(max_length=20,null=True,choices=PORTS)
eta = models.DateField(null=False)
name = ship.name.get(imo=imo)
calculated_eta = models.DateField(datetime.today + timedelta(days=1))
aduanas = models.FileField(blank=True)
aduanas_ok = models.CharField(max_length=15,default='PENDING',choices=STATUSES,editable=False)
minsa = models.FileField(blank=True)
minsa_ok = models.CharField(max_length=15,default='PENDING',choices=STATUSES,editable=False)
def __str__(self):
return "{}, ETA:{}".format(self.imo, self.eta)
class Meta:
ordering = ['eta']
To add a default to a DateField that is 7 days in the future you need to create a function that returns the date 7 days in the future and then pass that to the "default" parameter of the field
def seven_days_from_now():
return datetime.date.today() + datetime.timedelta(days=7)
class clearance(models.Model):
...
calculated_eta = models.DateField(default=seven_days_from_now)
...
Your "name" field should be a property that returns the name of the associated "imo"
class clearance(models.Model):
...
#property
def name(self):
return self.imo.name
...
I have a permission in Django Rest Framework:
from annoying.functions import get_object_or_None
from django.utils.translation import ugettext_lazy as _
from rest_framework import permissions
from restaurants.models import Restaurant
class TableBelongsToRestaurantPermission(permissions.BasePermission):
"""
Permission to check if the table belongs to the restaurant in the request. This ensures
(together with the UserOwnsRestaurantPermission) that owner can change the QR code of a
restaurant that he doesn't own.
"""
message = TABLE_BELONGS_TO_RESTAURANT_PERMISSION_DENIED_MESSAGE
def has_object_permission(self, request, view, obj):
if not obj.table:
return True
slug = request.data.get("restaurant_slug", "")
restaurant = get_object_or_None(Restaurant, slug=slug)
if restaurant:
return restaurant.table_set.filter(id=obj.table.id).exists()
return False
And now, I wrote tests for this:
from unittest import mock
from allauth.account.models import EmailAddress
from django.contrib.auth import get_user_model
from django.test import TestCase
from addresses.models import (Address, City, Country, PostalCode, State,
StreetName)
from core.utils import QR_CODE_FUNCTIONS
from employments.models import Employment
from licenses.models import RestaurantLicense
from profiles.models import UserOwnerProfile
from qrcodeproperties.models import QRCodePropertyCheckinUser
from restaurants.models import Restaurant
from tables.models import Table
from ...models import QRCode, QRCodeFunction
from ..permissions import TableBelongsToRestaurantPermission
User = get_user_model()
USER_OWNER_EMAIL = "owner#burgergrill.de"
USER_OWNER_NAME = "Owner"
USER_PASSWORD = "test1234test"
ISO_ALPHA_2_CODE = "DE"
STATE_NAME = "NRW"
CITY_NAME = "Köln"
STREET_NAME = "Burgerstraße"
POSTAL_CODE = "32062"
STREET_NUMBER = "119"
RESTAURANT_NAME = "Burgergrill"
RESTAURANT_SLUG = "burgergrill"
TABLE_NUMBER = 1
OTHER_RESTAURANT_NAME = "Extrablatt"
OTHER_RESTAURANT_SLUG = "extrablatt"
class TableBelongsToRestaurantPermissionTestCase(TestCase):
def setUp(self):
self.permission = TableBelongsToRestaurantPermission()
owner_user = User.objects.create_user(
email=USER_OWNER_EMAIL,
name=USER_OWNER_NAME,
password=USER_PASSWORD
)
self.owner_user = owner_user
owner = UserOwnerProfile.objects.create(user=owner_user)
owner.save()
self.owner = owner
emailaddress = EmailAddress.objects.create(
user=owner_user,
email=owner_user.email,
verified=True,
primary=True
)
emailaddress.save()
self.emailaddress = emailaddress
country = Country.objects.create(
country=ISO_ALPHA_2_CODE
)
country.save()
self.country = country
state = State.objects.create(
name=STATE_NAME,
country=self.country
)
state.save()
self.state = state
city = City.objects.create(
name=CITY_NAME,
country=self.country,
state=self.state
)
city.save()
self.city = city
street_name = StreetName.objects.create(
name=STREET_NAME,
city=self.city
)
street_name.save()
self.street_name = street_name
postal_code = PostalCode.objects.create(
code=POSTAL_CODE,
city=self.city
)
postal_code.save()
self.postal_code = postal_code
address = Address.objects.create(
country=self.country,
state=self.state,
city=self.city,
postal_code=self.postal_code,
street_name=self.street_name,
street_number=STREET_NUMBER
)
address.save()
self.address = address
restaurant = Restaurant.objects.create(
name=RESTAURANT_NAME,
address=self.address
)
restaurant.save()
self.restaurant = restaurant
qr_code = QRCode.objects.create()
qr_code.save()
self.qr_code = qr_code
self.request = mock.MagicMock(
user=owner_user,
kwargs={"slug": RESTAURANT_SLUG}
)
self.view = mock.MagicMock()
def test_permissions_table_belongs_to_restaurant_denied_when_table_belongs_to_different_restaurant(self):
"""Test if a user gets permission denied if the qr code's table belongs to another restaurant."""
restaurant = Restaurant.objects.create(name=OTHER_RESTAURANT_NAME, address=self.address)
restaurant.save()
table = Table.objects.create(table_number=TABLE_NUMBER, restaurant=restaurant)
table.save()
prev_count = Table.objects.all().count()
qr_code_function = QRCodeFunction.objects.create(
qr_code=self.qr_code,
qr_code_function=QR_CODE_FUNCTIONS.checkin_user
)
qr_code_function.save()
qr_code_property = QRCodePropertyCheckinUser(
qr_code=self.qr_code,
table=table,
)
qr_code_property.save()
self.assertFalse(self.permission.has_object_permission(
request=self.request, view=self.view, obj=self.qr_code
))
def test_permissions_table_belongs_to_restaurant_granted_when_table_belongs_to_same_restaurant(self):
"""Test if a user gets permission granted if the qr code's table belongs to the same restaurant."""
table = Table.objects.create(table_number=TABLE_NUMBER, restaurant=self.restaurant)
table.save()
prev_count = Table.objects.all().count()
qr_code_function = QRCodeFunction.objects.create(
qr_code=self.qr_code,
qr_code_function=QR_CODE_FUNCTIONS.checkin_user
)
qr_code_function.save()
qr_code_property = QRCodePropertyCheckinUser(
qr_code=self.qr_code,
table=table,
)
qr_code_property.save()
self.restaurant.refresh_from_db()
print(table.restaurant == self.restaurant)
print(self.qr_code.table)
print(self.restaurant.table_set)
self.assertTrue(self.permission.has_object_permission(
request=self.request, view=self.view, obj=self.qr_code
))
def test_permissions_table_belongs_to_restaurant_granted_when_qr_code_without_table(self):
"""Test if a user gets permission granted if the qr code has no table."""
self.assertTrue(self.permission.has_object_permission(
request=self.request, view=self.view, obj=self.qr_code
))
The problem is that the second test (test_permissions_table_belongs_to_restaurant_granted_when_table_belongs_to_same_restaurant) fails. The print statements give out True, 1 Pontgrill and tables.Table.None respectively. That means that for some reason even though I did .refresh_from_db() the data for the restaurant does not update and the test fails because it Django thinks there are no relations from Table to Restaurant.
How can you refresh relations and fix the test?
I wrote a simple string generator for my order_id field.
I tested the generator script in shell, and it works perfectly.
But when I run the server, and try to create an order in django admin, the order id field remains empty when I click save.
What am I doing wrong?
from datetime import date
from django.db import models
from django.db.models.signals import pre_save
from cartapp.models import Cart
class Order(models.Model):
order_id = models.CharField(max_length=120)
cart = models.ForeignKey(Cart, on_delete=models.CASCADE)
status = models.CharField(max_length=50, default='Waiting', null=True, blank=True)
order_total = models.DecimalField(default=0.0, max_digits=10, decimal_places=1)
date_created = models.DateTimeField(auto_now_add=True)
def order_id_generator(instance):
today = date.today().strftime("%Y-%m-%d")
last_order_raw = Order.objects.latest('order_id').date_created
last_order_date = str(last_order_raw).split(' ')[0]
if today != last_order_date:
new_order_id = str(today + " 1")
else:
last_order = Order.objects.latest('order_id')
extract = last_order.order_id.split(' ')[1]
increment = int(extract) + 1
new_order_id = today + " " + str(increment)
return new_order_id
def pre_save_order_id(sender, instance, *args, **kwargs):
if not instance.order_id:
instance.order_id = order_id_generator(instance)
pre_save.connect(pre_save_order_id, sender=Order)
I noticed that you are passing instance to order_id_generator but doesn't use it there. You can avoid using signals and you can use your function as the model field default:
class Order(models.Model):
order_id = models.CharField(max_length=120, default=order_id_generator)
and you doesn't need an arg instance in your function:
def order_id_generator():
today = date.today().strftime("%Y-%m-%d")
last_order_raw = Order.objects.latest('order_id').date_created
last_order_date = str(last_order_raw).split(' ')[0]
if today != last_order_date:
new_order_id = str(today + " 1")
else:
last_order = Order.objects.latest('order_id')
extract = last_order.order_id.split(' ')[1]
increment = int(extract) + 1
new_order_id = today + " " + str(increment)
return new_order_id
I have been working on a project in which I have to point out the expenses that the workers of a company have.
For this I have created two models, workers and expenses, in which expenses has a foreign key to workers, in the field: "nomTreballador".
When I try to save it in the db I get the error: "Cannot assign "u'Joan Manel'": "despesa.nomTreballador" must be a "treballador" instance."
My models.py:
from __future__ import unicode_literals
from django.db import models
from django.core.validators import RegexValidator
KILOMETRATGE = 'KM'
DINAR = 'DIN'
AUTOPISTA = 'AP'
MANTENIMENTPC = 'PC'
GASTOS = (
(KILOMETRATGE, 'Kilometres'),
(DINAR, 'Dinar'),
(AUTOPISTA, 'Autopista peatge'),
(MANTENIMENTPC, 'Manteniment de pc')
)
NIF = 'NIF'
NIE = 'NIE'
DNI = 'DNI'
TIPUSDOC = (
(DNI, 'DNI'),
(NIF, 'NIF'),
(NIE, 'NIE')
)
class treballador(models.Model):
nom = models.CharField(max_length=150, null=False, unique=True)
cognom = models.CharField(max_length=150, null=False)
tipusDocID = models.CharField(max_length=3, choices=TIPUSDOC, null=False)
docId = models.CharField(max_length=9, null=False)
tlf_regex = RegexValidator(regex=r'^\d{9,9}$',message="Phone number must be entered in the format: '+999999999'. Up to 9 digits allowed.")
tlf = models.CharField(validators=[tlf_regex], blank=True, max_length=9) # validators should be a list
correu = models.EmailField(max_length=254)
ciutat = models.CharField(max_length=150)
dataDAlta = models.DateTimeField(auto_now_add=True)
def __unicode__(self):
return unicode(self.nom) or 'u'
class despesa(models.Model):
nomTreballador = models.ForeignKey(treballador, to_field='nom')
tipusDeGast = models.CharField(max_length=3, choices=GASTOS)
quantia = models.DecimalField(max_digits=5, decimal_places=2)
data = models.DateTimeField()
def __unicode__(self):
return unicode(self.nomTreballador) or 'u'
My forms.py:
from django import forms
from functools import partial
from .models import despesa, treballador
DateInput = partial(forms.DateInput, {'class':'datepicker'})
class desModelForm(forms.ModelForm):
data = forms.DateField(widget=DateInput(format='%d/%m/%Y'), label="Data de la despesa", input_formats=['%d/%m/%Y'])
iquery = treballador.objects.values_list('nom', flat=True).distinct()
iquery_choices = [('','None')] + [(treballador,treballador) for treballador in iquery]
nomTreballador = forms.ChoiceField(choices=iquery_choices)
class Meta:
model= despesa
fields= ["nomTreballador","tipusDeGast","quantia","data"]
def clean_despesa(self):
despeses = self.cleaned_data.get("tipusDeGast")
return despeses
def clean_date(self):
date = self.cleaned_data.get("data")
return date
def clean_quantia(self):
quantia = self.cleaned_data.get("quantia")
return quantia
def clean_nom(self):
nomTreballador = self.cleaned_data.get("nomTreballador")
return nomTreballador
My views.py:
from django.shortcuts import render
from .forms import desModelForm, treballadorForm
from .models import treballador, despesa
def home(request):
form = desModelForm(request.POST or None)
context = {
"gast_form": form
}
if form.is_valid():
desp = form.save(commit=False)
desp.save()
return render(request, "imputacioDespeses.html", context)
I've tried solutions of similar questions but I have not managed to solve it
Thank you!!
You are getting this error because you are passing a text string to be used as the nomTreballador foreign key, while you should be passing a treballador instance.
It looks like you're trying to restrict the available choices to a set of distinct trebelladors by using a forms.ChoiceField, but a better way to do this with a ModelForm is to change the queryset attribute of the nomTreballador field. You do this in the form's init method:
self.fields['nomTreballador'].queryset = treballador.objects.all().distinct()
Also you should check the clean methods you've implemented because not all of them map to an existing field.