hi please help me i have to model i want after create and save store the result save to main store
like this
store.name == mainstore.name
store.the_rest_of_quantity==mainstore.quantity
i trying to use signals but i fail
class Store(models.Model):
CHOICES = (
('NUM','number'),
('M','meter'),
)
name = models.CharField(max_length=60)
quantity = models.PositiveSmallIntegerField (validators=[MinValueValidator(0)],default=0,blank=True,null=True)
date_of_add = models.DateTimeField(auto_now_add=True)
add_new_item = models.PositiveSmallIntegerField (validators=[MinValueValidator(0)],default=0,blank=True,null=True)
date_of_remove = models.DateTimeField(auto_now =True)
remove_old_item = models.PositiveSmallIntegerField (validators=[MinValueValidator(0)],default=0,blank=True,null=True)
the_rest_of_quantity = models.PositiveSmallIntegerField (validators=[MinValueValidator(0)],default=0,blank=True,null=True)
accept_stor = models.BooleanField(default = False)
classyfiyed = models.CharField(max_length=3,choices=CHOICES,blank=True,null=True)
def __str__(self):
return 'Device Name :( {0} ) Have Quantity({1}) '.format(self.name,self.quantity)
def save(self, *args, **kwargs):
try:
totla_sum = sum([self.quantity , self.add_new_item])
self.the_rest_of_quantity = int(totla_sum - self.remove_old_item)
except Expression as identifier:
'you add remove bigger than quantity'
return super().save(*args, **kwargs)
class MainStore(models.Model):
name = models.CharField(max_length=120)
quantity = models.PositiveIntegerField (null=True,default=0)
store = models.OneToOneField(Army,on_delete=models.CASCADE,related_name='Store',null=True)
i use signals for solve it
signals.py
#receiver(post_save,sender=Store)
def create_store(sender,instance,created,**kwargs):
if created:
MainStore.objects.get_or_create(Store=instance,name=instance.name,quantity=instance.the_rest_of_quantity)
else:
obj_store = MainStore.objects.filter(Store=instance)
update_store = obj_store.update(name=instance.name,quantity=instance.the_rest_of_quantity)
return update_store
apps.py
from django.apps import AppConfig
class StoreConfig(AppConfig):
default_auto_field = 'django.db.models.BigAutoField'
name = 'Store'
def ready(self):
import Store.signals
init.py
default_app_config = "Store.apps.StoreConfig"
Related
Django is giving me this weird AttributeeError :
'Tour' object has no attribute 'check_if_requested_beds_are_avaliable'
However, I have the method check_if_requested_beds_are_avaliable() in my Tour class of my model. The other method - set_new_number_of_beds() works fine. I have never experienced this with with Django, can anybody tell me what the solution is?
This is the model :
from django.db import models
from django.urls import reverse
class Tour(models.Model):
destination = models.CharField(max_length=256)
country = models.CharField(max_length=256)
date_of_arrival = models.DateField()
total_days = models.IntegerField()
price = models.DecimalField(decimal_places=2,max_digits=6)
available_beds = models.IntegerField()
photo = models.ImageField(upload_to='photos',default='photos/def.png')
description = models.TextField(blank=True)
def set_new_number_of_beds(self,number_of_guests):
self.available_beds -= number_of_guests
return self.available_beds
def check_if_requested_beds_are_available(self,numb_of_guests):
if self.available_beds < numb_of_guests:
return False
else:
return True
def __str__(self):
return f'{self.destination} , {self.country} , {self.total_days} days for $ {self.price}'
class Client(models.Model):
name = models.CharField(max_length=256)
surname = models.CharField(max_length=256)
email = models.CharField(max_length=256)
number_of_guests =models.IntegerField()
tour = models.ForeignKey(Tour,on_delete=models.CASCADE)
total_price = models.DecimalField(decimal_places=2,max_digits=6,default=0)
def get_total_price(self):
return self.number_of_guests * self.tour.price
def get_absolute_url(self):
return reverse('tour_list')
def __str__(self):
return f'{self.name} {self.surname}, {self.tour}'
and this is the view:
from django.shortcuts import render
from aplikacija.models import Tour,Client,ContactMessage
from django.views.generic import ListView,DetailView,TemplateView,CreateView
from aplikacija.forms import ClientForm,ContactForm
def HomeView(request):
if request.method=="GET":
return render(request,'aplikacija/home.html')
else:
form= ClientForm(request.POST)
if form.is_valid():
name = form.cleaned_data['name']
surname=form.cleaned_data['surname']
email=form.cleaned_data['email']
tour_id=form.cleaned_data['tour'].pk
number_of_guests=form.cleaned_data['number_of_guests']
total_price=number_of_guests*form.cleaned_data['tour'].price
tour_name=form.cleaned_data['tour'].destination
client = Client.objects.create(name=name,surname=surname,email=email,number_of_guests=number_of_guests,tour_id=tour_id,total_price=total_price)
client.save()
tour=Tour.objects.get(destination=tour_name)
beds_available = tour.check_if_requested_beds_are_avaliable(number_of_guests)
if beds_available:
tour.set_new_number_of_beds(number_of_guests)
tour.save()
message =f'thank you {name} ! Your reservation to {tour} for {number_of_guests} guests , with a total price of {total_price} has been booked successfully.'
return render(request,'aplikacija/home.html',{'msg':message})
else:
form = ClientForm()
return render(request,'aplikacija/client_form.html',{'infoMsg':f"sorry, there are less than {number_of_guests} beds available for {tour_name}",'form':form})
def thanksView(request):
form=ContactForm(request.POST)
if form.is_valid():
sender=form.cleaned_data['sender']
title=form.cleaned_data['title']
body=form.cleaned_data['body']
message=ContactMessage.objects.create(sender=sender,title=title,body=body)
message.save()
return render(request,'aplikacija/thanks.html')
class TourListView(ListView):
model = Tour
def get_queryset(self):
return Tour.objects.all()
class TourDetailView(DetailView):
model = Tour
class CreateClientView(CreateView):
redirect_field_name = "/aplikacija/home.html"
model = Client
form_class = ClientForm
class contactView(CreateView):
redirect_field_name="/aplikacija/thanks.html"
model = ContactMessage
form_class=ContactForm
So , Its pretty clear that I have the method that gives the AttributeError. And like I said the other method in the class works fine. What am I missing?
It is due to the typo: check_if_requested_beds_are_avaliable. Can be discovered with search or by using IDE with code completion
I created a CustomUser as follows, however, I am not able to use the CustomUser functions in Views as I get the error message "get_first_name() missing 1 required positional argument: 'self'" when I call CustomUser.get_first_name().
I checked my settings.py and do import CustomUser, models as well as settings in the view file.
If you could help me here that would be awesome.
models.py
class CustomUser(AbstractBaseUser, PermissionsMixin):
email = models.EmailField(verbose_name='email', unique=True)
first_name = models.CharField(verbose_name='first_name', max_length = 15)
last_name = models.CharField(verbose_name='last_name', max_length = 15)
organization = models.CharField(verbose_name="organization", max_length = 15, choices=ORGANIZATIONS)
is_staff = models.BooleanField(default=False)
is_active = models.BooleanField(default=True) # check this for login email purposes
date_joined = models.DateTimeField(default=timezone.now)
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['first_name', 'last_name', 'organization']
objects = CustomUserManager()
def get_full_name(self):
'''
Returns the first_name plus the last_name, with a space in between.
'''
full_name = '%s %s' % (self.first_name, self.last_name)
return full_name.strip()
def get_short_name(self):
'''
Returns the short name for the user.
'''
return self.first_name
def __str__(self):
return self.email
def get_organization(self):
return self.organization
def get_first_name(self):
return self.first_name
def get_email(self):
return self.email
views.py
class Dashboard(LoginRequiredMixin, TemplateView):
template_name = "plot.html"
def get_context_data(self, **kwargs):
# Call the base implementation first to get a context
context = super(Dashboard, self).get_context_data(**kwargs)
context['plot'] = plots.plotsurvey()
return context
plots.py
def plotsurvey():
c = CustomUser()
name = c.get_first_name()
df = pd.read_csv(str(name) +'.csv') #
trace = go.Bar(
x = df['Y'],
y = df['Z'], name = 'N'
)
data = [trace]
layout = go.Layout(title="X", margin = dict(b = 150))
fig = go.Figure(data=data, layout=layout)
plot_div = plot(fig, output_type='div', include_plotlyjs=False)
#logger.info("Plotting number of points {}.".format(3))
return plot_div
You are using an instance method, as if it were a class method.
You need to change, this
def plotsurvey():
c = CustomUser()
name = CustomUser.get_first_name()
...
To this (use the instance)
def plotsurvey():
c = CustomUser()
name = c.get_first_name()
...
Note that you have another problem here. You are not actually getting any real user with c = CustomUser(). To get a user, you would need to do something like
CustomUser.objects.get(pk=user_id)
In that case, you finally get:
def plotsurvey(user_id):
c = CustomUser.objects.get(pk=user_id)
name = c.get_first_name()
...
EDIT
We can be more practical, using the view.
class Dashboard(LoginRequiredMixin, TemplateView):
template_name = "plot.html"
def get_context_data(self, **kwargs):
# Call the base implementation first to get a context
context = super(Dashboard, self).get_context_data(**kwargs)
user = self.request.user
context['plot'] = plots.plotsurvey(user.pk)
return context
You can use request object
request.user.get_first_name()
I have this models:
Class Category(models.Model):
name = models.CharField(max_length=150, unique=True)
description = models.CharField(max_length=250)
def get_absolute_url(self):
return reverse('categories_url', args=[str(self.id)])
class Company(models.Model):
name = models.CharField(max_length=150, unique=True)
country = models.CharField(max_length=50)
class Motobike(models.Model):
name = models.CharField(max_length=150)
company = models.ForeignKey('Company', on_delete=models.CASCADE)
category = models.ForeignKey('Category', on_delete=models.CASCADE)
def get_absolute_url(self):
return reverse('details_url', args=[str(self.id)])
And views:
class CategoryView(DetailView):
model = Motobike
template_name = 'bikes_site/categories_detail.html'
pk_url_kwarg = 'pk'
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
category = self.get_object()
context['motobikes'] = Motobike.objects.filter(category_id=category.pk)
return context
And test:
def test_category(setup):
client = Client()
category_id = Category.objects.get(name='Мотоциклы').id
response = client.get(f'/categories/{category_id}/')
assert response.status_code == 200
response_data = json.loads(response.content.decode('utf-8'))
assert len(response_data) == 2
assert response_data[1]['name'] == 'Ninja Turbo'
assert response_data[1]['vendor'] == 'Kawasaki'
assert response_data[1]['category'] == 'Мотоциклы'
assert response_data[1]['description'] == ''
response = client.get(f'/categories/25/')
assert response.status_code == 404
I need to present all thin in JSON, through JsonResponce, and what should almost go to the meaning of the dictonary, did i create them correctly?
You should do something like in your view:
from django.http import JsonResponse
class CategoryView(DetailView):
model = Motobike
template_name = 'bikes_site/categories_detail.html'
pk_url_kwarg = 'pk'
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
category = self.get_object()
context['motobikes'] = Motobike.objects.filter(category_id=category.pk)
return JsonResponse(context, status=200) # or wahtever status is appropriate
Note: Haven't tested it, but that's what I use with GenericAPIView
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.
I get the error "" needs to have a value for field "dataset" before this many-to-many relationship can be used." when trying to assign values to a ManyToMany field in my views. I've looked at many related questions here on SO that say I must save my Dataset object first. I think I am doing that...what is going wrong?? My database already contains four Subject items.
models.py
class Subject(TimeStampedModel):
subject_type = models.CharField(max_length=128, blank=False)
def __unicode__(self):
return self.subject_type
class Dataset(TimeStampedModel):
dataset_id = models.CharField(max_length=256)
dataset_doi = models.CharField(max_length=15)
dataset_name = models.CharField(max_length=256, blank=False)
dataset_description = models.TextField(blank=False)
lab = models.CharField(max_length=256, blank=False)
biological_sample = models.CharField(max_length=256, blank=False)
subject_type = models.ManyToManyField('Subject', related_name='datasets', blank=True)
date_collected = models.DateField(blank=True)
collection_facility = models.ManyToManyField('CollectionFacility', related_name='datasets', blank=True)
processing_notes = models.TextField(blank=True)
release_date = models.DateField()
release_asap = models.BooleanField()
pdb_code = models.CharField(max_length=256, blank=True)
publication_link = models.URLField(blank=True)
def create_name(self):
self.dataset_name = "%s %s" % (self.biological_sample, self.lab)
def save(self, *args, **kwargs):
self.dataset_id = self.id
def __unicode__(self):
return "%s : %s" % (self.dataset_name, self.dataset_id)
forms.py RegistrationForm:
class RegistrationForm(forms.Form):
subject_type = forms.ModelMultipleChoiceField(
label="Subject",
queryset = Subject.objects.all(),
widget=forms.CheckboxSelectMultiple(),
required = True,
)
views.py
def create_registration(form):
dataset = Dataset()
dataset.DOI = "preUpload"
dataset.lab = form.cleaned_data['lab']
dataset.biological_sample = form.cleaned_data['sample']
dataset.resource_type = form.cleaned_data['dataset_type']
dataset.dataset_description = form.cleaned_data['dataset_description']
dataset.date_collected = form.cleaned_data['date_collected']
dataset.release_date = form.cleaned_data['release_date']
dataset.release_asap = form.cleaned_data['release_asap']
if form.cleaned_data['pdb_code']:
dataset.pdb_code = form.cleaned_data['pdb_code']
if form.cleaned_data['publication_link']:
dataset.publication_link = form.cleaned_data['publication_link']
dataset.create_name()
dataset.save() # I don't think this save is working?
subjects = form.cleaned_data['subject_type']
dataset.subject_type = [x for x in subjects]
for facility in form.cleaned_data['facility']
dataset.collection_facility.add(facility)
dataset.save()
return dataset
def registration_submit(request):
registration_form = RegistrationForm(request.POST)
if registration_form.is_valid():
registration = create_registration(registration_form)
.......
You forgot to call the original save() in the overriden Dataset.save() method.
def save(self, *args, **kwargs):
self.dataset_id = self.id
super(Dataset, self).save(*args, **kwargs)