Django UpdateView not populating form - python

I've been stuck on this problem for hours, looking through Django documentation and adjusting my code hasn't helped.
I have manually coded a HTML form (for styling reasons). Everything works fine until I try to edit an object via this form.
I'm using a standard UpdateView with no additions but for some reason the form is not populating the data in the object.
class RPLogbookEditEntry(LoginRequiredMixin, UpdateView):
login_url = 'ihq-login'
template_name = 'internethq/ihq-rplogbookform.html'
model = RPLogbookEntry
fields = ['entry_date', 'rpa_code', 'rpa_icao_code','rpa_registration', 'user_role', 'crew', 'crew_role', 'launch_location', 'recovery_location',
'remarks', 'vlos', 'evlos1', 'evlos2', 'bvlos', 'ft_day', 'ft_night', 'remarks', 'no_of_landings_day', 'no_of_landings_night']
def form_valid(self, form):
form.instance.user = self.request.user
form.instance.rpa = RPA.objects.get(rpa_code=form.cleaned_data['rpa_code'])
return super().form_valid(form)
def form_invalid(self, form):
return super().form_invalid(form)
def get_success_url(self):
return reverse('ihq-rplogbook-list') + '?month=' + str(self.object.entry_date.month) + '&year=' + str(self.object.entry_date.year)
models.py
class RPLogbookEntry(models.Model):
## Date
entry_date = models.DateField()
## RPA Details
rpa_obj = RPA.objects.only('rpa_code')
RPA_CODE_CHOICES = []
for vars in rpa_obj:
RPA_CODE_CHOICES.append((vars.rpa_code, vars.rpa_code))
rpa_code = models.CharField(choices=RPA_CODE_CHOICES, max_length=20)
rpa_icao_code = models.CharField(max_length=15)
rpa_registration = models.CharField(max_length=30)
rpa = models.ForeignKey(RPA, on_delete=models.CASCADE)
## Crew Details
user = models.ForeignKey(User, on_delete=models.CASCADE)
USER_ROLE_CHOICES = [
('RPIC', 'Remote Pilot-In-Command'),
('RP', 'Remote Pilot'),
('SPOT', 'Spotter'),
('CAMOP', 'Camera operator'),
]
user_role = models.CharField(
max_length=5,
choices=USER_ROLE_CHOICES,
)
crew = models.CharField(max_length=128, blank=True)
crew_role = models.CharField(
max_length=5,
choices=USER_ROLE_CHOICES,
blank = True
)
## Flight Details
launch_location = models.CharField(max_length=128)
recovery_location = models.CharField(max_length=128)
remarks = models.CharField(max_length=256, blank=True)
vlos = models.BooleanField(default=True)
evlos1 = models.BooleanField(default=False)
evlos2 = models.BooleanField(default=False)
bvlos = models.BooleanField(default=False)
## Flight Time
ft_day = FlightTimeFieldInt("Day flight time", blank=True, null=True,)
ft_night = FlightTimeFieldInt("Night flight time", blank=True, null=True,)
def _ft_total(self):
return int(self.ft_day + self.ft_night)
ft_total = property(_ft_total)
## Category of mission or flight
MISSION_CATEGORY_CHOICES = [
('INS', 'Inspection'),
('MAP', 'Mapping'),
('PHO', 'Photography'),
('VID', 'Videography'),
('PRI', 'Private flying'),
('TRA', 'Training'),
]
mission_category = models.CharField(
max_length=3,
choices=MISSION_CATEGORY_CHOICES,
blank=True,
)
## Landings & Autolands
no_of_landings_day = models.IntegerField("Number of landings", blank=True, default=0,)
no_of_landings_night = models.IntegerField("Number of auto landings", blank=True, default=0,)
def get_absolute_url(self):
return reverse('ihq-rplogbook-list')
def clean(self):
if self.no_of_landings_day is None and self.no_of_landings_night is None:
raise ValidationError({'no_of_landings_day':_('You must have landed at least once!')})
if self.no_of_landings_night is None:
if self.no_of_landings_day >= 1:
self.no_of_landings_night = 0
return self.no_of_landings_night
if self.no_of_landings_day is None:
if self.no_of_landings_night >= 1:
self.no_of_landings_day = 0
return self.no_of_landings_day
def clean_fields(self, exclude=None):
validation_error_dict = {}
p = re.compile('^[0-9]+:([0-5][0-9])')
if self.ft_day !='' and p.match(self.ft_day) is None:
validation_error_dict['ft_day'] = ValidationError(_('Flight duration must be in HH:MM format.'))
if self.ft_night !='' and p.match(self.ft_night) is None:
validation_error_dict['ft_night'] = ValidationError(_('regex night wrong'))
if self.ft_day =='' and self.ft_night =='':
validation_error_dict['ft_day'] = ValidationError(_('Fill in at least one flying time duration.'))
if (self.vlos or self.evlos1 or self.evlos2 or self.bvlos) is False:
validation_error_dict['vlos'] = ValidationError(_('Select one LOS category.'))
if (self.vlos or self.evlos1 or self.evlos2 or self.bvlos) is True:
counter = 0
for x in [self.vlos, self.evlos1, self.evlos2, self.bvlos]:
if x == True:
counter += 1
if counter > 1:
validation_error_dict['vlos'] = ValidationError(_('Selecting more than one LOS category is not allowed.'))
# if self.no_of_landings is None and self.no_of_auto_landings is None:
# validation_error_dict['no_of_landings'] = ValidationError(_('You must have landed at least once!'))
if validation_error_dict:
raise ValidationError(validation_error_dict)
Basically my question is - shouldn't this UpdateView populate my form automatically?

Very silly mistake on my part.
I was using the same HTML template to add and edit these records, which had the {{form.cleaned_data.field_name}} in the <input value="..> tag. This works for retaining data when adding a new record, such as an invalid form, but won't show up when editing an object.
The fix was to create a new template (identical page), but fill the <input value="... with the necessary object value template tag i.e. {{object.field_name}}.

Related

Updating a field within another Model's save method with F()

I'm attempting to create a voting system where the score of a given post is separate from the type of votes placed by users. In the event that a user deletes a profile, a given score should not increment/decrement due to their vote being deleted. Therefore scores are only updated by using an F('score') + 1 or F('score') - 1 expression.
Within Vote.save(), I'm trying to implement this, yet the Question.score field doesn't update when the Vote is created. How can I get the test to pass where the score in the question goes from 0 to 1? django.db.models.F is in fact being imported into the module but it's not displayed here.
class TestQuestionScoreUpVote(TestCase):
'''Verify that a Question's score increments by one point
when the Vote is an "up" vote.'''
#classmethod
def setUpTestData(cls):
tag1 = Tag.objects.create(name="Tag1")
user = get_user_model().objects.create_user("TestUser")
profile = Profile.objects.create(user=user)
cls.question = Question.objects.create(
title="Question__001",
body="Content of Question 001",
profile=profile
)
cls.question.tags.add(tag1)
user_vote = Vote.objects.create(
profile=profile, type="upvote", content_object=cls.question
)
def test_new_user_vote_on_question(self):
self.assertEqual(self.question.score, 1)
class Post(Model):
body = TextField()
date = DateField(default=date.today)
comment = ForeignKey('Comment', on_delete=CASCADE, null=True)
profile = ForeignKey(
'authors.Profile', on_delete=SET_NULL, null=True,
related_name='%(class)ss',
related_query_name="%(class)s"
)
vote = GenericRelation(
'Vote', related_query_name="%(class)s"
)
score = IntegerField(default=0)
class Meta:
abstract = True
class Question(Post):
title = CharField(max_length=75)
tags = ManyToManyField(
'Tag', related_name="questions", related_query_name="question"
)
views = IntegerField(default=0)
objects = Manager()
postings = QuestionSearchManager()
class Meta:
db_table = "question"
ordering = ["-score" , "-date"]
def __repr__(self):
return f"{self.__class__.__name__}(title={self.title})"
class Vote(Model):
profile = ForeignKey(
'authors.Profile', on_delete=SET_NULL, null=True,
related_name="votes"
)
type = CharField(max_length=7)
content_type = ForeignKey(ContentType, on_delete=CASCADE)
object_id = PositiveIntegerField()
content_object = GenericForeignKey()
def save(self, *args, **kwargs):
post = ContentType.objects.get_for_id(
self.content_type_id
).get_object_for_this_type(id=self.object_id)
if self.type == "upvote":
post.score = F("score") + 1
else:
post.score = F("score") - 1
post.refresh_from_db()
super().save(*args, **kwargs)
You are forgetting to call post.save() after the object change:
def save(self, *args, **kwargs):
post = ContentType.objects.get_for_id(
self.content_type_id
).get_object_for_this_type(id=self.object_id)
if self.type == "upvote":
post.score = F("score") + 1
else:
post.score = F("score") - 1
post.save() # <- HERE
post.refresh_from_db()
super().save(*args, **kwargs)

TypeError at /join super(type, obj): obj must be an instance or subtype of type

Model.py
class UserAccountModel(models.Model):
ContactEmail = models.EmailField(max_length=30)
FirstName = models.CharField(max_length=30)
LastName = models.CharField(max_length=40)
Counrty = models.CharField(max_length=50)
Phone = models.IntegerField()
ChooseUserName = models.CharField(max_length=30)
password = models.CharField(max_length=32)
EnterCaptcha = models.CharField(max_length=4)
payments = models.BooleanField(max_length=6, default=False)
showsponsor = models.CharField(max_length=30, default=False)
RegisteredDate = models.DateTimeField(auto_now_add=True, blank=True)
ActivationOn = models.DateField(auto_now_add=False,blank=True)
expiry_date = models.DateField(auto_now_add=False,blank=True)
def save(self, **kwargs):
super(AddProgramModel, self).save(**kwargs)
vote = UserAccountModel(AddProgramModel=self)
vote.save()
def __str__(self):
return self.FirstName + ":" + self.ChooseUserName
views.py
this one is views of my project and bellow with bold text is a actual error location from django debugger while saving a record ,help me to resolve it
def join(request):
if request.method == 'POST':
refrer = request.POST['showsponsor']
try:
if UserAccountModel.objects.get(ChooseUserName=str(refrer)):
ContactEmail=request.POST['email']
FirstName=request.POST['firstname']
LastName=request.POST['lastname']
Counrty=request.POST['country1']
Phone=request.POST['phone']
ChooseUserName=request.POST['username']
password=request.POST['password2']
EnterCaptcha=request.POST['captcha']
payments=request.POST['payment']
# referal_Name = request.POST['showsponsor']
Note: error start from here join_save_record to join_save_record.save()
join_save_record = UserAccountModel.objects.create(ContactEmail=ContactEmail,FirstName=FirstName,
LastName=LastName,Counrty=Counrty,Phone=Phone,
ChooseUserName=ChooseUserName,password=password,
EnterCaptcha=EnterCaptcha, payments='True',
ActivationOn=datetime.now,expiry_date=datetime.now,)
join_save_record.save()
print(join_save_record.FirstName)
namew=request.POST['showsponsor']
# session creating
request.session['ChooseUserName'] = str(refrer)
rerredby = request.session.get("ChooseUserName")
print("session created : " + str(rerredby))
return render(request, 'payment_verify.html', {'rerredby':rerredby})
# messages.info(request, 'invalid refrer user except case name contact to the right persone who did')
print("denied")
except UserAccountModel.DoesNotExist :
return redirect("/join")
else :
return render(request, 'join.html')

Django filter with ForeignKey not working

I am building ecommerce and having trouble creating dashboard for sellers. No matter how I try to get filter processed orders so I can show sold products to sellers I couldn't make it happen. Some help will be a great relief. Following is my Seller Mixin I am trying to create:
mixins.py
class SellerAccountMixin(LoginRequiredMixin, object):
account = None
products = []
transactions = []
orders = []
def get_account(self):
user = self.request.user
accounts = SellerAccount.objects.filter(user=user)
if accounts.exists() and accounts.count() == 1:
self.account = accounts.first()
return accounts.first()
return None
def get_products(self):
account = self.get_account()
products = Product.objects.filter(seller=account)
self.products = products
return products
def get_all_products(self):
account = self.get_account()
products = Product.objects.all()
self.products = products
return products
def get_sold_products(self):
orders = UserCheckout.objects.get(user_user=self.user)
return orders
seller/views.py:
class SellerDashboard(SellerAccountMixin, FormMixin, View):
form_class = NewSellerForm
success_url = "/seller/"
def post(self, request, *args, **kwargs):
user = self.user
form = self.get_form()
if form.is_valid():
return self.form_valid(form)
else:
return self.form_invalid(form)
def get(self, request, *args, **kwargs):
apply_form = self.get_form() #NewSellerForm()
account = self.get_account()
exists = account
active = None
context = {}
if exists:
active = account.active
if not exists and not active:
context["title"] = "Apply for Account"
context["apply_form"] = apply_form
elif exists and not active:
context["title"] = "Account Pending"
elif exists and active:
context["title"] = "Dashboard"
#products = Product.objects.filter(seller=account)
context["products"] = self.get_products()
context["today_sales"] = self.get_today_sales()
context["sold_products"] = self.get_sold_products()
#context["total_profit"] = self.get_total_profit()
else:
pass
return render(request, "sellers/dashboard.html", context)
Above is my seller app and I am bringing the products model with simple features. The problem is that its not letting me get processed orders with UserCheckout model in Orders app. Following is a snapshot of Orders app.
Orders/models.
class UserCheckout(models.Model):
user = models.OneToOneField(settings.AUTH_USER_MODEL, null=True, blank=True)
email = models.EmailField(unique=True)
def __unicode__(self):
return self.email
ADDRESS_TYPE = (
('billing', 'Billing'),
('shipping', 'Shipping'),
)
class UserAddress(models.Model):
user = models.ForeignKey(UserCheckout)
type = models.CharField(max_length=120, choices=ADDRESS_TYPE)
street = models.CharField(max_length=120)
city = models.CharField(max_length=120)
state = models.CharField(max_length=120)
zipcode = models.CharField(max_length=120)
def __unicode__(self):
return self.street
def get_address(self):
return "%s, %s, %s, %s" %(self.street, self.city, self.state, self.zipcode)
CHOICES = (
('CreditCard', "CreditCard"),
('Cash On Delivery', 'Cash On Delivery'),
('PayPal', 'PayPal'),
)
ORDER_STATUS_CHOICES={
('created','Created'),
('paid','Paid'),
}
class Order(models.Model):
status = models.CharField(max_length=120, choices=ORDER_STATUS_CHOICES, default='created')
cart = models.ForeignKey(Cart)
user = models.ForeignKey(UserCheckout, null=True)
billing_address = models.ForeignKey(UserAddress, related_name='billing_address', null=True)
shipping_address = models.ForeignKey(UserAddress, related_name='shipping_address', null=True)
shipping_total_price = models.DecimalField(max_digits=50, decimal_places=2, default=5.99)
user_seller = models.ForeignKey(settings.AUTH_USER_MODEL)
order_total = models.DecimalField(max_digits=50, decimal_places=2, )
order_id = models.CharField(max_length=20, null=True, blank=True)
paymethod = models.CharField(max_length=120, choices=CHOICES, default='CreditCard')
seller = models.ForeignKey(SellerAccount, null=True)
def __unicode__(self):
return str(self.cart.id)
I can get multiple products but I need to filter products by seller and orders by seller. After trying multiple times I always get stuck with error:
user has to be a UserCheckout instance:
User "Admin": Must be a "User" instance.
and
'SellerDashboard' object has no attribute 'user'
I need to filter products by seller.
I need filter orders with paid status by the seller.
Seller Account Model:
class SellerAccount(models.Model):
user = models.ForeignKey(User)
managers = models.ManyToManyField(settings.AUTH_USER_MODEL, related_name="manager_sellers", blank=True)
#orders = models.ManyToManyField(Order)
active = models.BooleanField(default=False)
timestamp = models.DateTimeField(auto_now_add=True, auto_now=False)
def __unicode__(self):
return str(self.user.username)
def get_absolute_url(self):
return reverse("products:vendor_detail", kwargs={"vendor_name": self.user.username})
I am stuck so bad that I don't have courage to continue with django anymore. Please help.

Django Product Total

I'm trying to learn in Django. I'm trying to prepare the inventory application. But I do not calculate the input and output products.
I prepare models & views.
Models:
class Kategori(models.Model):
adi = models.CharField(max_length=10, verbose_name="Kategori")
def __str__(self):
return self.adi
class Birim(models.Model):
birim = models.CharField(max_length=2, verbose_name="Birim")
def __str__(self):
return self.birim
class Urunler(models.Model):
adi = models.CharField(max_length=50, verbose_name="Ürün Adı")
kod = models.PositiveSmallIntegerField(verbose_name="Ürün Kodu", blank=True, null=True)
etkenMadde = models.CharField(max_length=100, verbose_name="İçerik Etken Madde", blank=True, null=True)
tarih = models.DateField(default=datetime.now(), editable=False)
birim = models.ForeignKey(Birim, verbose_name="Birim")
kategori = models.ForeignKey(Kategori, verbose_name="Kategori")
aciklama = models.CharField(max_length=50, verbose_name="Açıklama", blank=True, null=True)
def __str__(self):
return self.adi
class StokCikis(models.Model):
urun = models.ForeignKey(Urunler, related_name="scikis_urun", verbose_name="Ürün")
tarih = models.DateTimeField(default=datetime.now())
miktar = models.PositiveSmallIntegerField(verbose_name="Miktar", default=0)
teslimAlan = models.CharField(max_length=20, verbose_name="Teslim Alan")
tesimEden = models.CharField(max_length=20, verbose_name="Teslim Eden")
def __str__(self):
return self.urun.adi
class StokGiris(models.Model):
urun = models.ForeignKey(Urunler, related_name="sgiris_urun", verbose_name="Ürün")
tedarikci = models.CharField(max_length=100, verbose_name="Tedarikçi", blank=True, null=True)
irsaliyeNo = models.PositiveSmallIntegerField(verbose_name="İrsaliye No", blank=True, null=True)
tarih = models.DateField(default=datetime.now().strftime("%d.%m.%Y"))
miktar = models.PositiveSmallIntegerField(verbose_name="Miktar", default=0)
aciklama = models.CharField(max_length=100, verbose_name="Açıklama", blank=True, null=True)
def __str__(self):
return self.urun.adi
Views.py
def kategori(request):
kategori = Kategori.objects.all()
return render_to_response('stok_kategoriler.html', locals())
def kategoriEkle(request):
kategoriId = request.GET.get('id')
if kategoriId:
ktgr = Kategori.objects.get(pk=kategoriId)
form = KategoriForm(instance=ktgr)
else:
form = KategoriForm
if request.method == 'POST':
if kategoriId:
form = KategoriForm(request.POST, instance=ktgr)
else:
form = KategoriForm(request.POST)
if form.is_valid():
form.save()
return HttpResponseRedirect('/stok/kategoriler')
button = "Ekle"
baslik = "Kategoriler"
return render(request, 'stok_kategori_ekle.html', locals())
def kategoriSil(request):
kategoriId = request.GET.get('id')
kategori = Kategori.objects.get(pk=kategoriId)
kategori.delete()
return HttpResponseRedirect('/stok/kategoriler')
def stokBirimler(request):
birimler = Birim.objects.all()
return render_to_response('stok_birimler.html',locals())
def stokBirimEkle(request):
birimId = request.GET.get('id')
if birimId:
stok_birim = Birim.objects.get(pk=birimId)
form = BirimForm(instance=stok_birim)
else:
form = BirimForm()
if request.method == 'POST':
if birimId:
form = BirimForm(request.POST, instance=stok_birim)
else:
form = BirimForm(request.POST)
if form.is_valid():
form.save()
return HttpResponseRedirect('/stok/birimler/')
baslik = "Stok Birimleri"
return render(request, 'stok_birim_ekle.html', locals())
def stokBirimSil(request):
birimId = request.GET.get('id')
birim = Birim.objects.get(pk=birimId)
birim.delete()
return HttpResponseRedirect('/stok/birimler/')
def stokUrunler(request):
urunler = Urunler.objects.all()
return render_to_response('stok_urunler.html', locals())
def urunEkle(request):
urunId = request.GET.get('id')
if urunId:
stok_urun = Urunler.objects.get(pk=urunId)
form = UrunForm(instance=stok_urun)
else:
form = UrunForm()
if request.method == 'POST':
if urunId:
form = UrunForm(request.POST, instance=stok_urun)
else:
form = UrunForm(request.POST)
if form.is_valid():
form.save()
return HttpResponseRedirect('/stok/urunler/')
baslik = "Stok Ürünleri"
return render(request, 'stok_urun_ekle.html', locals())
def urunSil(request):
urunId = request.GET.get('id')
urun = Urunler.objects.get(pk=urunId)
urun.delete()
return HttpResponseRedirect('/stok/urunler/')
Located in the model StokGiris.miktari and Stok.Cikis.miktari fields need calculation. Total = StokGiris.miktari - StokCikis.miktari and I want to list the records.
If I understand your question correctly, you want to aggregate the values of miktar of both models and subtract them from each other. You can do it with Django built-in aggregation:
from django.db.models import Sum
total = StokGiris.objects.all().aggregate(Sum('miktar')) - StokCikis.objects.all().aggregate(Sum('miktar'))
As for listing the records... Not really sure what you mean again, but some ways to "list the records":
# Just a list of DB items
list_of_stokgiris = list(StokGiris.objects.all())
# Serialized list of dictionaries with the DB values
list_of_stokcikis = StokCikis.objects.values() # You can add an argument to specify which fields you want to be serialized
# Serialized list of tuples with DB values
# I.e. [('Filipp',), ('Artjom',), ('Marat',)]
list_of_urunler = Urunler.objects.values_list('adi') # Same here for the argument. Multiple args are also supported.

django model inheritance & casting to subtype in a view

It's a sort of cms type application
I have an article model and some specializations in models.py
class Article(models.Model):
foo = models.CharField(max_length=50)
bar = models.CharField(max_length=100,blank=True)
DISPLAY_CHOICES = (
('N', 'None'),
('C','Carousel'),
('M','Marketing'),
('F','Featurette')
)
display = models.CharField(max_length=1, choices = DISPLAY_CHOICES)
def __unicode__(self):
return self.title
class Artist(Article):
website = models.URLField(max_length=200,blank=True)
class Venue(Article):
location = models.CharField(max_length=150)
map_link = models.URLField(max_length=200,blank=True)
class Event(Article):
time = models.DateTimeField()
venue = models.ForeignKey(Venue)
performers = models.ManyToManyField(Artist)
I want to render these in different ways depending on the value of article.display but when I call
articles.objects.all()
I still need the extra attributes form the subclasses so I wrote
#views.py
def castToSubClass(article):
try:
return Artist.objects.get(article_ptr_id = article.id)
except:
try:
return Event.objects.get(article_ptr_id = article.id)
except:
try:
return Venue.objects.get(article_ptr_id = article.id)
except:
return article
def index(request):
carousel = [castToSubClass(article) for article in Article.objects.filter(display='C']
marketing = [castToSubClass(article) for article in Article.objects.filter(display='M'[:3]]
featurettes = [castToSubClass(article) for article in Article.objects.filter(display='F']
return render_to_response('frontpage.html',
{
'carousel': carousel,
'marketing':marketing,
'featurettes': featurettes
})
to turn them all in the appropriate subclass object, this apart from seeming clunky seems to mean I'm hitting the database twice for every (or nearly every) item in the queryset.
Is there a way to do this in the initial calls to the manager instead?
Thanks.
Use one model to store everything, and add a field to distinguish the article type, so that you can render different look for every type combine with display in the template(Like tumblr do).
class Article(models.Model):
foo = models.CharField(max_length=50)
bar = models.CharField(max_length=100,blank=True)
DISPLAY_CHOICES = (
('N', 'None'),
('C','Carousel'),
('M','Marketing'),
('F','Featurette')
)
display = models.CharField(max_length=1, choices = DISPLAY_CHOICES)
ARTICLE_TYPE_CHOICES = (
('artist', 'Artist'),
('venue', 'Venue'),
('event', 'Event'),
)
type = models.CharField(max_length=32, choices = ARTICLE_TYPE_CHOICES)
website = models.URLField(max_length=200,blank=True, null=True)
location = models.CharField(max_length=150, blank=True, null=True)
map_link = models.URLField(max_length=200,blank=True, null=True)
time = models.DateTimeField(null=True)
venue = models.ForeignKey('self', null=True)
performers = models.ManyToManyField('self', null=True)
def __unicode__(self):
return self.title
#views.py
def index(request):
carousel = Article.objects.filter(display='C')
marketing = Article.objects.filter(display='M')
featurettes = Article.objects.filter(display='F')
return render_to_response('frontpage.html',{'carousel': carousel, 'marketing':marketing, 'featurettes': featurettes})

Categories

Resources