the BUG :
Cannot resolve keyword 'date_added' into field. Choices are: date, entry, id, owner, owner_id, text
here s My Models :
from `django`.db import models
from `django.contrib.auth`.models import User
class Topic(models.Model) :
text = models.CharField(max_length=200)
date = models.DateTimeField(auto_now_add=True)
owner = models.ForeignKey(User,on_delete=models.CASCADE)
def __str__(self):
return self.text
class Entry(models.Model) :
topic = models.ForeignKey(Topic,on_delete=models.CASCADE)
text = models.CharField(max_length=200)
date = models.DateTimeField(auto_now_add=True)
class Meta:
verbose_name_plural = 'entries'
def __str__(self):
return self.text[:50] + "..."
heres My Views functions
def topics(request) :
topics = Topic.objects.filter(owner=request.user).`order_by`('date_added')
context = {'topics':topics}
return render(request, 'learning_logs/topics.html', context)
You have to add "date_added" field to your Topic model, because order_by orders items in Topic model, but now you have only Date field.
Related
I ran into a problem with the queryset query, I need to display certain tags for each article that are related to this article. Each article has tags associated with the article id.
model.py
class NewsDB(models.Model):
title = models.CharField('Название',max_length=300)
text = models.TextField('Текст статьи')
img = models.ImageField('Фото',upload_to='News',null='Без фото')
avtor = models.ForeignKey('Journalist', on_delete=models.PROTECT)
date = models.DateField()
def __str__(self):
return self.title
class Meta:
verbose_name = 'News'
verbose_name_plural = 'News DataBase'
class Hashtags(models.Model):
News=models.ForeignKey('NewsDB',on_delete=models.PROTECT)
Hashtag=models.CharField('Хештег',max_length=150,null='Без темы')
def __str__(self):
return self.Hashtag
view.py
class Show_post(DetailView):
model = NewsDB
template_name = 'navigation/post.html'
context_object_name = 'newsDB'
def get_context_data(self,**kwargs):
hashtags = super(Show_post,self).get_context_data(**kwargs)
hashtags['hashtags_list'] = Hashtags.objects.filter(News=self.pk)
return hashtags
you need to specify the kwargs
class Show_post(DetailView):
model = NewsDB
template_name = 'navigation/post.html'
context_object_name = 'newsDB'
def get_context_data(self,**kwargs):
hashtags = super(Show_post,self).get_context_data(**kwargs)
# the problem is in this line
hashtags['hashtags_list'] = Hashtags.objects.filter(News=self.kwargs['pk'])
return hashtags
I have been attempting to import data into my Django project using Django import-export. I have two models Ap and Job, Job has a FK relationship with Ap. Using the Admin, I can select the file and the type, CSV. So far my program seems to run, but gets hung up on the FK. I'm close, something is off and causing the import script to fail.
Models.py
class Ap(models.Model):
line_num = models.IntegerField()
vh = models.IntegerField()
vz = models.IntegerField()
status = models.CharField(
choices=statuses, default="select", max_length=40)
classified = models.BooleanField(default=False)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
class Job(models.Model):
aplink = models.ForeignKey(Ap, related_name=(
"job2ap"), on_delete=models.CASCADE)
job_num = models.IntegerField()
description = models.CharField(max_length=200)
category = models.CharField(
choices=categories, default="select", max_length=40)
status = models.CharField(
choices=statuses, default="select", max_length=40)
dcma = models.BooleanField(default=False),
due_date = models.DateField(blank=True),
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
views.py
class ImportView(View):
def get(self, request):
form = ImportForm()
return render(request, 'importdata.html', {'form': form})
def post(self, request):
form = ImportForm(request.POST, request.FILES)
job_resource = JobResource()
data_set = Dataset()
if form.is_valid():
file = request.FILES['import_file']
imported_data = data_set.load(file.read())
result = job_resource.import_data(
data_set, dry_run=True) # Test the data import
if not result.has_errors():
job_resource.import_data(
data_set, dry_run=False) # Actually import now
else:
form = ImportForm()
return render(request, 'importdata.html', {'form': form})
resource.py
class CharRequiredWidget(widgets.CharWidget):
def clean(self, value, row=None, *args, **kwargs):
val = super().clean(value)
if val:
return val
else:
raise ValueError('this field is required')
class ForeignkeyRequiredWidget(widgets.ForeignKeyWidget):
def clean(self, value, row=None, *args, **kwargs):
if value:
print(self.field, value)
return self.get_queryset(value, row, *args, **kwargs).get(**{self.field: value})
else:
raise ValueError(self.field + " required")
class JobResource(resources.ModelResource):
aplink = fields.Field(column_name='aplink', attribute='aplink', widget=ForeignkeyRequiredWidget(Ap,'id'),
saves_null_values=False)
job_num = fields.Field(saves_null_values=False, column_name='job_num', attribute='job_num',
widget=widgets.IntegerWidget())
description = fields.Field(column_name='description', attribute='description', saves_null_values=False,
widget=CharRequiredWidget())
class Meta:
model = Job
fields = ('aplink', 'job_num', 'description',)
clean_model_instances=True
admin.py
class JobResource(resources.ModelResource):
class Meta:
model=Job
fields=('aplink','job_num','description',)
class JobAdmin(ImportExportModelAdmin):
resource_class = JobResource
admin.site.register(Job, JobAdmin)
CSV file, data to import. I have tried leaving the first column empty, as will as putting the Id of the only Ap stored in the table ie 1. I have also tried hard coding the line_num, which is 1200 the first column as well.
CSV file for importing data:
Date importing errors:
In your resources, while defining fields, you need to include id field in the list. So change JobResource to the following:
class JobResource(resources.ModelResource):
class Meta:
model = Job
fields = ('id', 'aplink', 'job_num', 'description')
If you have defined a custom id field, then you will need to provide:
import_id_fields = ('your_id_field')
I have working models, forms, views and urls for a django CRUD app managing customer functions for a business. I just cant seem to figure out how to write a view to allow a user to add comments, or other data related to the customer and stored in other models using a single view and template.
So for example; for customer a, all the comments for customer a with the option to add, amend etc.. and the same for the other related models.
I understand how to do it for one I will be able to make quick progress. (old school programmer here)
Here is what I am working with - keeping it simple.
MODELS
class Emergency(models.Model):
# Fields
name = CharField(null = False, blank = False, max_length=60)
address = TextField(blank=True, null=True, help_text='Street and town', verbose_name='Address')
telephone = CharField(blank=False, null=False, unique= True, max_length=20)
relationship = CharField(choices=(('P', 'Parent'),('S', 'Son'),('D', 'Daughter'),('R', 'Relative'),('L', 'Partner')),max_length = 1,default='R')
class Meta:
ordering = ('-pk',)
def __unicode__(self):
return u'%s' % self.pk
def get_absolute_url(self):
return reverse('conform_emergency_detail', args=(self.pk,))
def get_update_url(self):
return reverse('conform_emergency_update', args=(self.pk,))
class Client(models.Model):
# Fields
surname = CharField(null = False, blank = False, max_length=30)
name = CharField(null = False, blank = False, max_length=60)
# Relationship Fields
emergencycontact = models.ForeignKey(Emergency, on_delete=models.CASCADE, name = 'Emergency Contact')
class Meta:
ordering = ('-pk',)
def __unicode__(self):
return u'%s' % self.pk
def get_absolute_url(self):
return reverse('conform_client_detail', args=(self.pk,))
def get_update_url(self):
return reverse('conform_client_update', args=(self.pk,))
class Clientnotes(models.Model):
# Fields
slug = AutoSlugField(populate_from='name', blank=True)
created = DateTimeField(auto_now_add=True, editable=False)
last_updated = DateTimeField(auto_now=True, editable=False)
note = CharField(blank=False, null=False, max_length= 300 )
# Relationship Fields
modified_by = models.ForeignKey(User, related_name='clientnotes_modified_by', on_delete=models.CASCADE, name= 'Changed by')
clientnotes = models.ManyToManyField(Client, name = 'Clients notes')
class Meta:
ordering = ('-created',)
def __unicode__(self):
return u'%s' % self.slug
def get_absolute_url(self):
return reverse('conform_clientnotes_detail', args=(self.slug,))
def get_update_url(self):
return reverse('conform_clientnotes_update', args=(self.slug,))
FORMS
class ClientForm(forms.ModelForm):
class Meta:
model = Client
fields = ['surname', 'name']
class ClientnotesForm(forms.ModelForm):
class Meta:
model = Clientnotes
readonly_fields = ['slug', 'modified_by']
fields = ['note']
VIEWS
class ClientListView(ListView):
model = Client
class ClientCreateView(CreateView):
model = Client
form_class = ClientForm
class ClientDetailView(DetailView):
model = Client
class ClientUpdateView(UpdateView):
model = Client
form_class = ClientForm
TEMPLATE NAMES
client_detail.html
client_form.html
client_list.html
I have simple views, forms and templates to list, view detail and add and it all works well - with the exception of related models because i am not able to add both models at the same time. I need a simple clear simpletons guide with what i have provided so it clicks into place.
I am trying to code with a Django ecommerce plugin called django-cart. I want to find the sum of the prices of all items in the cart. The cart model has the following code:
from django.db import models
from django.utils.translation import ugettext_lazy as _
from django.contrib.contenttypes.models import ContentType
from django.contrib.contenttypes import generic
class Cart(models.Model):
creation_date = models.DateTimeField(verbose_name=_('creation date'))
checked_out = models.BooleanField(default=False, verbose_name=_('checked out'))
def _valor_carrinho(self):
return self.objects.all().aggregate(Sum('total_price'))
valor_carrinho = property(_valor_carrinho)
class Meta:
verbose_name = _('cart')
verbose_name_plural = _('carts')
ordering = ('-creation_date',)
def __unicode__(self):
return unicode(self.creation_date)
class ItemManager(models.Manager):
def get(self, *args, **kwargs):
if 'product' in kwargs:
kwargs['content_type'] = ContentType.objects.get_for_model(type(kwargs['product']))
kwargs['object_id'] = kwargs['product'].pk
del(kwargs['product'])
return super(ItemManager, self).get(*args, **kwargs)
class Item(models.Model):
cart = models.ForeignKey(Cart, verbose_name=_('cart'))
quantity = models.PositiveIntegerField(verbose_name=_('quantity'))
unit_price = models.DecimalField(max_digits=18, decimal_places=2, verbose_name=_('unit price'))
# product as generic relation
content_type = models.ForeignKey(ContentType)
object_id = models.PositiveIntegerField()
link_item = models.CharField(max_length=100)
tipo_item = models.CharField(max_length=50)
cor_item = models.CharField(max_length=50, blank=True)
modelo_item = models.CharField(max_length=50, blank=True)
tamanho_item = models.CharField(max_length=50, blank=True)
objects = ItemManager()
class Meta:
verbose_name = _('item')
verbose_name_plural = _('items')
ordering = ('cart',)
def __unicode__(self):
return u'%d units of %s' % (self.quantity, self.product.__class__.__name__)
def total_price(self):
return self.quantity * self.unit_price
total_price = property(total_price)
# product
def get_product(self):
return self.content_type.get_object_for_this_type(id=self.object_id)
def set_product(self, product):
self.content_type = ContentType.objects.get_for_model(type(product))
self.object_id = product.pk
product = property(get_product, set_product)
And I am trying to use valor_carrinho (sorry for the mixup between Portuguese and English in the code) as the sum of the total_price field of all the items in the cart. But when I use it in a template, it returns nothing. What am I doing wrong?
I think it should be:
def _valor_carrinho(self):
return self.item_set.all().aggregate(Sum('total_price'))
to get all items for a specific Cart instance, I am NOT sure total_price works here, but to access the items of the cart it is item_set, hopefully it is enough to get you started!
The concept that that is using is reverse foreign key lookup, which is explained here
I am not sure that this does work as I think aggregate goes to the database layer and total_price has been defined as a property. I am going to denormalise and make the equivalent of total_price a field so that I can use the aggregate function.
Try the following code, it works for me so it might work for you:
view.py
def get_cart(request):
cart = Cart(request)
cart.summary()
return render_to_response('cart.html', dict(cart=Cart(request)),{'cart':cart})
cart.html
<h3> Total : {{ cart.summary }}</h3>
I'd like to insert individual squawks into the Room object so I can insert into the database. How do I do this?
I tried, Room(squawk=squawk object), but this doesn't appear to work.
class Squawk(models.Model):
username = models.ForeignKey(User)
message = models.CharField(max_length=160)
time = models.DateTimeField(auto_now_add=True)
def __unicode__(self):
return str(self.username) + ' - ' + self.message
class Room(models.Model):
title = models.CharField(max_length=160)
created = models.DateTimeField(auto_now_add=True)
users = models.ManyToManyField(User)
squawks = models.ManyToManyField(Squawk)
def __unicode__(self):
return self.title
from django.shortcuts import get_object_or_404
# get Room instance by id or raise 404 page if not found
room = get_object_or_404(Room,pk = id)
# add squawk to many-to-many relation
room.squawks.add(squawk_object)
https://docs.djangoproject.com/en/dev/ref/models/relations/