Url in a blog post django - django

https://github.com/nathanborror/django-basic-apps/blob/master/README.rst I am trying to implement this blog module my question is that the i am writing one generic function and when i fetch a blog get a url as
def Myfunc(request):
p = Post.objects.get(pk=12)
p.get_absolute_url //This prints blog/2011/jun/13/fgfgf/
My question is that how to get the url with the domain name or where does this being handled in the code..
EDIT: i.e, http://mysite.com/blog/2011/jun/13/fgfgf/
The models field is as,
class Post(models.Model):
"""Post model."""
STATUS_CHOICES = (
(1, _('Draft')),
(2, _('Public')),
)
title = models.CharField(_('title'), max_length=200)
slug = models.SlugField(_('slug'), unique_for_date='publish')
author = models.ForeignKey(User, blank=True, null=True)
body = models.TextField(_('body'), )
tease = models.TextField(_('tease'), blank=True, help_text=_('Concise text suggested. Does not appear in RSS feed.'))
status = models.IntegerField(_('status'), choices=STATUS_CHOICES, default=2)
allow_comments = models.BooleanField(_('allow comments'), default=True)
publish = models.DateTimeField(_('publish'), default=datetime.datetime.now)
created = models.DateTimeField(_('created'), auto_now_add=True)
modified = models.DateTimeField(_('modified'), auto_now=True)
categories = models.ManyToManyField(Category, blank=True)
#created_by = models.ForeignKey(UserProfile)
tags = TagField()
objects = PublicManager()
class Meta:
verbose_name = _('post')
verbose_name_plural = _('posts')
db_table = 'blog_posts'
ordering = ('-publish',)
get_latest_by = 'publish'
def __unicode__(self):
return u'%s' % self.title
#permalink
def get_absolute_url(self):
return ('blog_detail', None, {
'year': self.publish.year,
'month': self.publish.strftime('%b').lower(),
'day': self.publish.day,
'slug': self.slug
})

You can use the sites framework to get the fully qualified url - as per https://docs.djangoproject.com/en/1.2/ref/contrib/sites/

Related

Djnago Form getting Error while edit record

I am getting Issue while edit a record based on CHatquestion ID, if option is null then i need to add a record based on same chatquestion id, if chatqustion id exist in option it will work,
i am trying to multiple way to solve this issue but still can't find solution.
Models.py # thease are all 3 models
class Problem(models.Model):
Language = models.IntegerField(choices=Language_CHOICE, default=1)
type = models.CharField(max_length=500, null=True, blank=True)
def __str__(self):
return self.type
class ChatQuestion(models.Model): # Eding record based on chatquestion id
question = RichTextField(null=True, blank=True)
problem_id = models.ForeignKey(
Problem,
models.CASCADE,
verbose_name='Problem',
)
def __str__(self):
return self.question
is_first_question = models.BooleanField(default=False)
class Option(models.Model):
option_type = models.CharField(max_length=250, null=True, blank=True)
question_id = models.ForeignKey(
ChatQuestion,
models.CASCADE,
verbose_name='Question',
null=True,
blank=True
)
problem=models.ForeignKey(
Problem,
models.CASCADE,
verbose_name='Problem',
null=True,
blank=True
)
next_question_id = models.ForeignKey(ChatQuestion, on_delete=models.CASCADE, null=True, blank=True,
related_name='next_question')
def __str__(self):
return self.option_type
forms.py
class EditQuestionForm(forms.ModelForm):
class Meta:
model = ChatQuestion
fields =('question','problem_id')
class EditOptionForm(forms.ModelForm):
class Meta:
model = Option
fields =('option_type',)
views.py
def question_edit(request,id=None):
if id is not None:
queryset = get_object_or_404(ChatQuestion,pk=id)
queryset1=get_object_or_404(Option,question_id=queryset )
else:
queryset = None
queryset1 = None
if request.method=="POST":
form = EditQuestionForm(request.POST ,instance=queryset)
form1=EditOptionForm(request.POST, instance=queryset1)
if form.is_valid() and form1.is_valid():
question=form.cleaned_data['question']
option_type=form1.cleaned_data['option_type']
if id:
queryset.question=question
queryset.save()
queryset1.option_type=option_type
queryset1.save()
messages.success(request,'Sucessful')
return redirect('/fleet/list_chatbot')
else:
print(form.errors)
messages.error(request,'Please correct following',form.errors)
elif id:
form = EditQuestionForm(instance=queryset)
form1=EditOptionForm(instance=queryset1)
if not queryset1:
form1=EditOptionForm()
else:
form = EditQuestionForm()
form1=EditOptionForm()
context={
'form':form,
'form1':form1
}
return render(request,'chatbot/question_edit.html',context=context)

unable to fetch item from selected categories in django

i want to fetch the item of related subcategories but i am unable to fetch the items from that subcategories it is showing me the error
AttributeError: 'Subcategories' object has no attribute 'item'
so here is my code
my models
class Subcategories(models.Model):
categories = models.ForeignKey(Categories, on_delete=models.CASCADE, related_name='our_categories')
name = models.CharField(max_length=200, blank=False)
joined_date = models.DateTimeField(default=timezone.now,editable=False)
update_at = models.DateTimeField(auto_now=True)
def __str__(self):
return self.name
class Item(models.Model):
categories = models.ForeignKey(Categories, on_delete=models.CASCADE,)
subcategories = models.ForeignKey(Subcategories, on_delete=models.CASCADE, related_name='products')
can_buy = models.ForeignKey(For, on_delete=models.CASCADE,)
name = models.CharField(max_length=200, blank=False)
contain_size = models.CharField(max_length=10, blank=True)
first = models.ImageField(upload_to='items', blank=False)
second = models.ImageField(upload_to='items', blank=True)
third = models.ImageField(upload_to='items', blank=True)
fourth = models.ImageField(upload_to='items', blank=True)
fifth = models.ImageField(upload_to='items', blank=True)
item_vedio = models.FileField(upload_to='item_vedio', blank=True)
offered_price = models.FloatField(blank=False,)
actual_price = models.FloatField(blank=False)
about = models.TextField(blank=False, default="about" )
offer = models.CharField(max_length=4, blank=True)
def __str__(self):
return self.name
my urls.py
urlpatterns = [
path('<int:subcategory_id>/products/',Product.as_view(),name='product' ),
]
my views.py
class Product(View):
def get(self, request,):
category_list = Categories.objects.all()
return render (request, 'products.html', {'category_list': category_list })
def get(self, request, subcategory_id):
subcategory = get_object_or_404(Subcategories, pk=subcategory_id)
products = subcategory.item.all()
return render (request, 'products.html',{"subcategory_list" : products })
any idea what causing the issue and thank you for your time
The related name is products for subcategories Foreign key in Item model.
subcategory.products.all()

foreign key in django

I have a model for musics and a model for comment of musics:
class music(models.Model):
author = models.ForeignKey(User, on_delete=models.CASCADE)
STATUS_CHOICES = (('draft', 'Draft'), ('published', 'Published'),)
music = models.FileField()
music_image = models.ImageField(upload_to="images/")
singer_name = models.CharField(max_length=100)
music_name = models.CharField(max_length=100)
text_of_music = models.TextField()
create = models.DateField(auto_now_add=True, blank=True, null=True)
update = models.DateField(auto_now=True, blank=True, null=True)
publish = models.DateField(default=timezone.now, blank=True, null=True)
slug = models.CharField(max_length=250, unique_for_date='publish')
status = models.CharField(max_length=10, choices=STATUS_CHOICES, default='draft')
objects = models.Manager()
published = PublishedManager()
class Meta:
ordering = ('-publish',)
def get_absolute_url(self):
return reverse('music:music_detail',
kwargs={"id":self.id})
class comment(models.Model):
# Foreignkey for each music
For = models.ForeignKey(music, on_delete=models.CASCADE, related_name='post')
body = models.CharField(max_length=500)
created_on = models.DateTimeField(auto_now_add=True)
active = models.BooleanField(default=True)
commented_by = models.ForeignKey(User, on_delete=models.CASCADE)
and this is my view:
def music_Detail(request, id=None):
user = request.user
template_name = 'music/music_detail.html'
Music = music.objects.all().filter(id=id)
new_comment = None
Comment = comment.objects.all().filter(active=True)
form = comment_form(data=request.POST)
if request.method == 'POST':
if form.is_valid():
new_comment = form.save(commit=False)
new_comment.For = Music
new_comment.save()
form = comment_form()
return render(request, template_name, {'Music': Music, 'Comment': Comment, 'form': form})
Well, I get this error when I comment:
Cannot assign "<QuerySet [<music: m, majid kharatha>]>": "comment.For" must be a "music" instance.
How can I solve this problem and how can I display the information of the user who left this comment?
As the error says, you'll have to assign a single Music, not a queryset.
Instead of filter()ing to get a new queryset containing a single music,
Music = music.objects.all().filter(id=id)
you want to get() a single one:
Music = music.objects.get(id=id)

I'm optimizing my django project backend, but I got many problems on "list_display" that contains ForeignKey

django masters all around the world
I'm Korean developer and started django 3 months ago.
Now I'm just a slave of my company.
Anyway, I have problem on optimizing django admin project, but no one has experienced the same problem.
This is my models "Project", "Answer", "Request".
# ------------------------------------------------------------------
# Model : Project
# Description : project model
# ------------------------------------------------------------------
class Project(models.Model):
class Meta:
verbose_name = ' project'
verbose_name_plural = ' project'
def __str__(self):
return str(self.id)
# ------------------------------------------------------------------
# Model : Request
# Description : Request model
# ------------------------------------------------------------------
class Request(models.Model):
client = models.ForeignKey(Client, on_delete=models.CASCADE, verbose_name='client')
project = models.ForeignKey(Project, on_delete=models.CASCADE, verbose_name='project')
product = models.ForeignKey(Subclass, on_delete=models.CASCADE, verbose_name='product')
category = models.ManyToManyField(Develop, verbose_name='category')
name = models.CharField('name', max_length=256, blank=True, null=True)
price = models.CharField('price', max_length=256, blank=True, null=True)
day = models.CharField('duedate', max_length=256, blank=True, null=True)
content = RichTextUploadingField('content', null=True)
file = models.FileField('file', upload_to=request_update_filename, blank=True, null=True)
created_at = models.DateTimeField('created_at', default=time)
add_meeting = models.BooleanField('add_meeting', default=False, null=True)
examine = models.BooleanField('check examing', default=False, null=True)
active_save = models.BooleanField('active-save', default=True, null=True)
class Meta:
verbose_name = ' request'
verbose_name_plural = ' requests'
def __str__(self):
return str(self.name)
class Answer(models.Model):
client = models.ForeignKey(Client, on_delete=models.CASCADE, verbose_name="client")
project = models.ForeignKey(Project, on_delete=models.CASCADE, verbose_name="project", null=True)
partner = models.ForeignKey(Partner, on_delete=models.CASCADE, verbose_name="partner")
class Meta:
verbose_name = ' Answer'
verbose_name_plural = ' Answer'
def __str__(self):
return str(self.id)
and this is my admin code
#admin.register(Project)
class ProjectAdmin(admin.ModelAdmin):
inlines = [RequestInline,AnswerInline]
list_display = ['request_name','client_email','project_price','project_created','count_answer','count_meeting','answer_status']
def request_name(self, obj):
project_id = obj.id
request_name = Request.objects.get(project = project_id)
return request_name
def client_email(self, obj):
project_id = obj.id
client = Request.objects.get(project=project_id).client
return client
def client_phone(self, obj):
project_id = obj.id
client = Request.objects.get(project=project_id).client
phone = User.objects.get(username=client).phone
return phone
def project_price(self, obj):
project_id = obj.id
request_price = Request.objects.get(project=project_id).price
return request_price
def project_created(self, obj):
project_id = obj.id
created_at = Request.objects.get(project=project_id).created_at
return created_at
def count_answer(self, obj):
project_id = obj.id
answer_qs = Answer.objects.all()
answer = Answer.objects.filter(project=project_id)
count = len(answer)
return count
def count_meeting(self, obj):
project_id = obj.id
answer_yes = Answer.objects.filter(project = project_id, state = 1)
count = len(answer_yes)
return count
def answer_status(self, obj):
project_id = obj.id
answer = Answer.objects.filter(project = project_id, info_check =1)
count = len(answer)
return count
There are many factors not included in the above, but what I want to solve is not to bring in the same queryset(Request, Answer).
The project itself is a structure that does not have attributes but is received only by foreign keys. Such a structure is making it difficult to find a solution.
I used select_related(prefetch_related too), but it does not work.
If you can give me some advice, I'd like to take some advice. thanks.
p.s. It is my first time asking question on this site, I apologize if there was anything rude.
admin.TabularInline will show the reverse foreign key in the admin detail page that may help you, but it seems that you have already used it in the inlines of ProjectAdmin.

Django: creating M2M relationship inline

I'm trying to create a view with a formset of forms for the "Link" model. The problem is that in each form I would like the user to have the possibility of not just choosing from the already created TargetLink objects, but to edit them inline.
class ClientUrl(models.Model):
client = models.ForeignKey(UpstreamClientModel, null=True)
url = models.URLField(unique=True, null=False)
active = models.BooleanField(default=True)
def __unicode__(self):
return self.url
class Meta:
verbose_name = 'url'
ordering = ['url']
KEYWORD_TYPES = (
('PN', 'Pending'),
('MN', 'Money'),
('BR', 'Brand'),
('LT', 'Long Tail'),
)
class ClientKeyword(models.Model):
client = models.ForeignKey(UpstreamClientModel, null=True)
kw_type = models.CharField('keyword type', max_length=2,
choices=KEYWORD_TYPES, default='LT')
keyword = models.CharField(max_length=150, unique=False)
directions = models.CharField(max_length=200, blank=True,
help_text='e.g: 25 chars, use "affordable rental cars"')
def __unicode__(self):
return self.keyword
class Meta:
ordering = ['keyword', ]
unique_together = ('client', 'keyword')
class TargetLink(models.Model):
keyword = models.ForeignKey(ClientKeyword, related_name='target_links')
url = models.ForeignKey(ClientUrl, related_name='target_links')
def __unicode__(self):
return '{0}:{1}'.format(self.keyword, self.url)
class Link(models.Model):
client = models.ForeignKey(UpstreamClientModel, related_name='links')
target = models.ForeignKey(Target, related_name='links')
user = models.ForeignKey(User, blank=True, null=True, related_name='links')
link_type = models.ForeignKey(LinkType, related_name='links')
site = models.ForeignKey(Site, blank=True, null=True,
related_name='links')
site_url = models.URLField(blank=True,
help_text='leave blank until url is live')
month = models.DateField(blank=True, null=True)
target_links = models.ManyToManyField(TargetLink, related_name='links')
How could I accomplish this?
One way might be to have a form that is outside of your formset for the TargetLinks and use Knockout.js or another client-side framework to push the updated choices for TargetLinks to the target_links field in the formsets.