Two Foreign keys issue django - django

Hi I have this python code for django, and basically i am trying to build it so that every tourobject can have many tourbets but also i want to be able to save a certain winning tourbet as current bet but then django complains that it can't find TourBet
class TourObject(models.Model):
tourplace = models.ForeignKey(TourPlace, related_name='tourplace', verbose_name="tourplace", default=1)
title = models.CharField(max_length=155, blank=True)
description = models.TextField(blank=True)
date_created = models.DateTimeField(auto_now_add=True)
status = models.BooleanField(default=False, verbose_name="Status")
end_date = models.DateTimeField(blank=True, default=datetime.now)
current_bet = models.IntegerField(blank=True, default=0)
next_bet = models.IntegerField(blank=True, default=0)
no_auction_price = models.IntegerField(blank=True, default=1)
objects = models.Manager()
def __unicode__(self):
return self.title
def get_absolute_url(self):
return reverse("tourobjects:tourobject", kwargs={"pk": self.pk})
class RelatedTourObject(models.Manager):
def get_queryset(self):
return super(RelatedTourObject, self).get_queryset().select_related('tourobject').all()
class TourBet(models.Model):
user = models.ForeignKey(User, related_name='tourbet', verbose_name='User')
tourobject = models.ForeignKey(TourObject, related_name='tourobjectbet', verbose_name="tourobjectbet", default=1)
date_created = models.DateTimeField(blank=True, default=datetime.now)
bet_amount = models.IntegerField(blank=True, default=1)
objects = models.Manager()
related_tourobject = RelatedTourObject()
def __unicode__(self):
return str(self.bet_amount)

I think you can try this.
class TourObject(models.Model):
winning_bet = models.ForeignKey('TourBet', related_name='winning_bet')

Related

how to reset id whenever a row deleted in django?

I wanted to start id from 1 whenever a row is deleted it skips that number and jumps to the following number.
like in this image it skips numbers from 1-6 and 8.
I want to set it as 1,2,3.
Here is my models.py module
class dish(models.Model):
id = models.AutoField(primary_key=True)
dish_id = models.AutoField
dish_name = models.CharField(max_length=255, blank=True, null=True)
dish_category = models.CharField(max_length=255, blank=True, null=True)
dish_size = models.CharField(max_length=7, blank=True, null=True)
dish_price = models.IntegerField(blank=True, null=True)
dish_description = models.CharField(max_length=255, blank=True, null=True)
# dish_image = models.ImageField(upload_to="images/", default=None, blank=True, null=True)
dish_image = models.ImageField(upload_to="media/", default=None, blank=True, null=True) #here added images as a foldername to upload to.
dish_date = models.DateField()
def __str__(self):
return self.dish_name
Here is views.py module:
def delete(request, id):
dishs = dish.objects.get(id=id)
dishs.delete()
return HttpResponseRedirect(reverse('check'))
Deleting an object does not change any property of the remaining objects. You need to do that manually. First thing you need to do is to change the dish_id field:
# Change this:
# dish_id = models.AutoField
# to this:
dish_id = models.IntegerField(default=0)
Then in your views:
def delete(request, id):
dishs = dish.objects.get(id=id)
dishs.delete()
all_dishes = dish.objects.all()
for i, dish in enumerate(all_dishes):
dish.dish_id = i + 1
dish.save()
return HttpResponseRedirect(reverse('check'))
Separately, you really should write your classes in Pascal case, capitalizing the first letter of the class:
class Dish(models.Model):
And finally, Dish does not need an id field; that is created automatically, but you can leave that as is, it is not causing any problems.
You can achieve those things using an overriding save() method like this
class dish(models.Model):
id =models.AutoField(primary_key=True)
dish_id = models.BigIntegerField(unique = True)
dish_name = models.CharField(max_length=255, blank=True, null=True)
dish_category = models.CharField(max_length=255, blank=True, null=True)
dish_size = models.CharField(max_length=7, blank=True, null=True)
dish_price = models.IntegerField(blank=True, null=True)
dish_description = models.CharField(max_length=255, blank=True, null=True)
dish_image = models.ImageField(upload_to="images/", default=None, blank=True, null=True)
dish_image = models.ImageField(upload_to="media/", default=None, blank=True, null=True) #here added images as a foldername to upload to.
dish_date = models.DateField()
def __str__(self):
return self.dish_name
def save(self, *args, **kwargs):
count_obj = dish.objects.all().count()+1
self.dish_id = count_obj
super(dish, self).save(*args, **kwargs)

Django class based view, save in another model after CreateView

I have a create view (Loan_assetCreateView(generic.CreateView)) where I save if an asset is going to be loaned and when it will be returened in a model called Loan_asset(models.Model). Then I have the asset in a diffrent model Asset(model.Model). I would like to once I have saved my data in my Loan_assetCreateView(generic.CreateView) that is set the value in Asset.is_loaned to True. How can I do that?
My models.py:
class Asset(models.Model):
# Relationships
room = models.ForeignKey("asset_app.Room", on_delete=models.SET_NULL, blank=True, null=True)
model_hardware = models.ForeignKey("asset_app.Model_hardware", on_delete=models.SET_NULL, blank=True, null=True)
# Fields
name = models.CharField(max_length=30)
serial = models.CharField(max_length=30, unique=True, blank=True, null=True, default=None)
mac_address = models.CharField(max_length=30, null=True, blank=True)
purchased_date = models.DateField(null=True, blank=True)
may_be_loaned = models.BooleanField(default=False, blank=True, null=True)
is_loaned = models.BooleanField(default=False, blank=True, null=True)
missing = models.BooleanField(default=False, blank=True, null=True)
notes = HTMLField(default="")
ip = models.CharField(max_length=90, null=True, blank=True)
created = models.DateTimeField(auto_now_add=True, editable=False)
last_updated = models.DateTimeField(auto_now=True, editable=False)
class Loan_asset(models.Model):
# Relationships
asset = models.ForeignKey("asset_app.Asset", on_delete=models.SET_NULL, blank=True, null=True)
loaner_type = models.ForeignKey("asset_app.Loaner_type", on_delete=models.SET_NULL, blank=True, null=True)
location = models.ForeignKey("asset_app.Locations", on_delete=models.SET_NULL, blank=True, null=True)
# Fields
loaner_name = models.CharField(max_length=60)
loaner_address = models.TextField(max_length=100, null=True, blank=True)
loaner_telephone_number = models.CharField(max_length=30)
loaner_email = models.EmailField()
loaner_quicklink = models.URLField(null=True, blank=True)
loan_date = models.DateField()
return_date = models.DateField()
notes = HTMLField(default="")
returned = models.BooleanField(default=False, blank=True, null=True)
created = models.DateTimeField(auto_now_add=True, editable=False)
last_updated = models.DateTimeField(auto_now=True, editable=False)
class Meta:
pass
def __str__(self):
return str(self.loaner_name)
def get_absolute_url(self):
return reverse("asset_app_loan_asset_detail", args=(self.pk,))
def get_update_url(self):
return reverse("asset_app_loan_asset_update", args=(self.pk,))
my urls.py
`path("asset_app/loan_asset/create/", views.Loan_assetCreateView.as_view(), name="asset_app_loan_asset_create")`,
my views.py
class Loan_assetCreateView(generic.CreateView):
model = models.Loan_asset
form_class = forms.Loan_assetForm
Here are some options:
override form_valid method that's being called in post method implementation, so that after form will be validated (model instance saved), you'll be able to set the flag through foreign key/by creating Asset instance:
...
def form_valid(self, form):
self.object = form.save()
if self.object.asset:
self.object.asset.is_loaned = True
else:
self.object.asset = Asset.objects.create(is_loaned=True)
return HttpResponseRedirect(self.get_success_url())
use Django signals:
#receiver(post_save, sender=Loan_asset)
def create_transaction(sender, instance, created, **kwargs):
if created:
Asset.objects.create(is_loaned=True)
You can override the post method in your Loan_assetCreateView.
class Loan_assetCreateView(generic.CreateView):
model = models.Loan_asset
form_class = forms.Loan_assetForm
def post(request, *args, **kwargs):
response = super().post(request, *args. **kwargs)
# Do your thing
return response

I wanna create model which Before adding it must be accepted

I would like to create a model which must be accepted by the moderator before adding, after which every change in eg the title in this model must also be accepted
class MangaRequest(models.Model):
title = models.CharField(max_length=191)
type = models.CharField(max_length=30,choices=TYPE, blank=True, default='', null=True)
status= models.CharField(max_length=30, choices=STATUS, blank=True, default='', null=True)
date_start = models.DateField(blank=True, null=True)
data_end = models.DateField(blank=True, null=True)
age_restrictions = models.ForeignKey(OgraniczenieWiekowe, null=True, default='', blank=True)
volumes = models.SmallIntegerField(null=True, blank=True, default=0)
chapter = models.SmallIntegerField(null=True, blank=True, default=0)
is_accept = models.BooleanField(default=False)
delete = models.BooleanField(default=False)
This is my model and I have done it
def save(self, *args, **kwargs):
if self.is_accept == True:
manga = MangaAccept.objects.create(...)
super(MangaRequest, self).delete()
return manga
else:
super(MangaRequest, self).save()
And the same way is about deletes
My question is how can ACCEPT or REJECT for model and everyone field in this model ? Any sugestion ?

Dynamically generate fields+1 for model form

I have a model that is basically just a service report. I want this model to contain multiple punches (clock in\clock out). How do I go about doing that? When I pull up the form, I want to be able to add punches obviously.
class ServiceReportModel(models.Model):
report_number = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
site = models.ForeignKey(customers_models.SiteModel, on_delete=models.PROTECT)
request_number = models.ForeignKey(ServiceRequestModel,
on_delete=models.PROTECT,
null=True,
blank=True,
related_name='s_report_number'
)
reported_by = models.ForeignKey(main_models.MyUser, related_name='reports')
reported_date = models.DateTimeField(auto_now_add=True)
updated_by = models.ForeignKey(main_models.MyUser, blank=True, null=True, related_name='+')
updated_date = models.DateTimeField(auto_now=True)
equipment = models.ForeignKey(customers_models.EquipmentModel, on_delete=models.PROTECT)
report_reason = models.CharField(max_length=255, null=True)
time_in = models.DateTimeField(blank=True, null=True)
time_out = models.DateTimeField(blank=True, null=True)
actions_taken = models.TextField(null=False, blank=False)
recommendations = models.TextField(null=True, blank=True)
def get_absolute_url(self):
return reverse('service-report', kwargs={'pk': self.pk})
def __str__(self):
return '%s - %s, %s' % (self.site.company, self.reported_date.strftime('%d %B %Y'), self.equipment.name)
class Meta:
ordering = ['reported_date']
verbose_name = 'Service Report'
verbose_name_plural = 'Service Reports'

Name error: Can not import [model name]

I am trying to link the model Post to the model Topic via a foreign key. When I run the makemigrations command, it raises an import error, and says that the name 'Topic' is not defined. What could be the cause of this? It certainly seems to be defined. I've pretty much ruled out that it is not a problem within the db.
class Post(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, blank=True)
title = models.CharField(max_length=100)
summary = models.TextField(blank=True, null=True)
content = models.TextField()
draft = models.BooleanField(default=False)
details = models.CharField(blank=True, null=True, max_length=250)
updated = models.DateTimeField(auto_now=True, auto_now_add=False)
timestamp = models.DateTimeField(auto_now=False, auto_now_add=True)
topic = models.ForeignKey(Topic, blank=True, null=True)
thumbnail = models.ImageField(upload_to='media', blank=True, null=True)
def get_absolute_url(self):
return reverse('posts:detail', kwargs={'pk': self.pk})
def __str__(self):
return self.title
class Topic(models.Model):
name = models.CharField(max_length=50)
description = models.TextField()
picture = models.ImageField(upload_to='media', blank=True, null=True)
isperson = models.BooleanField(default=False)
ispolicy = models.BooleanField(default=False)
positive = models.BooleanField(default=True)
percent = models.CharField(max_length=5)
def __str__(self):
return self.name
Any ideas? I don't see any problems in this code, and neither did my IDE, which recognized the model Topic
I am considering that you have indented your code for Post model properly in your file.
Solution : Try to define Topic above Post.
First, this
topic = models.ForeignKey(Topic, blank=True, null=True)
should be this
topic = models.ForeignKey('Topic', blank=True, null=True)
This way it tells django that you're setting a foreign key to a model, which isn't declared yet, but will be declared further in the code.
Second, you should properly indent your Post model and its methods:
class Post(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, blank=True)
title = models.CharField(max_length=100)
summary = models.TextField(blank=True, null=True)
content = models.TextField()
draft = models.BooleanField(default=False)
details = models.CharField(blank=True, null=True, max_length=250)
updated = models.DateTimeField(auto_now=True, auto_now_add=False)
timestamp = models.DateTimeField(auto_now=False, auto_now_add=True)
topic = models.ForeignKey('Topic', blank=True, null=True)
thumbnail = models.ImageField(upload_to='media', blank=True, null=True)
def get_absolute_url(self):
return reverse('posts:detail', kwargs={'pk': self.pk})
def __str__(self):
return self.title
Because as you have it now, django doesn't understand that the unindented fields belong to the Post model.