Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django rest framework comment system
I am trying to build a rest api with django and having hard times with comment system. The API shows my comments correctly but it shows replies to comments twice. One at comments field of post, other at replies field of comments. Like both in depth 1 and 2. So to cut short, there is my code: --serializers.py class CommentChildSerializer(serializers.ModelSerializer): parent_id = serializers.PrimaryKeyRelatedField(queryset=Comment.objects.all(),source='parent.id') author = SerializerMethodField() class Meta: model = Comment fields = ('author', 'content', 'id','parent_id') def get_author(self, obj): return obj.author.username def create(self, validated_data): subject = parent.objects.create(parent=validated_data['parent']['id'], content=validated_data['content']) class CommentSerializer(serializers.ModelSerializer): reply_count = SerializerMethodField() author = SerializerMethodField() replies = SerializerMethodField() class Meta: model = Comment fields = ('id','content', 'parent', 'author', 'reply_count', 'replies') # depth = 1 def get_reply_count(self, obj): if obj.is_parent: return obj.children().count() return 0 def get_author(self, obj): return obj.author.username def get_replies(self, obj): if obj.is_parent: return CommentChildSerializer(obj.children(), many=True).data return None class PostListSerializer(serializers.ModelSerializer): url = post_detail_url author = SerializerMethodField() image = SerializerMethodField() comments = CommentSerializer(required=False, many=True) # comments = SerializerMethodField() class Meta: model = Post fields = ('title', 'image', 'author', 'star_rate', 'url', 'slug', 'comments') def get_author(self, obj): return obj.author.username def get_image(self, obj): try: image = obj.image.url except: image = None return image --comment model class Comment(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='comments') author … -
Making a portfolio website with Django and got Page not found (404)
Hello I'm making a portfolio website with Django, it was going fine but in the last steps following a guide I got this error Page not found (404) Request Method: GET Request URL: http://localhost:8000/ Using the URLconf defined in personal_portfolio.urls, Django tried these URL patterns, in this order: admin/ projects/ The empty path didn't match any of these. This is my project folder Here is personal_portfolio - urls.py from django.contrib import admin from django.urls import path, include urlpatterns = [ path("admin/", admin.site.urls), path("projects/", include("projects.urls")), ] And projects - urls.py from django.urls import path from . import views urlpatterns = [ path("", views.project_index, name="project_index"), path("int:pk>/", views.project_detail, name="project_detail"), ] Also the section in settings.py > INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'projects', ] Here is the link of the repo of the guide I'm following https://github.com/realpython/materials/tree/master/rp-portfolio I downloaded the repo and tried to run the server and got the same error, how? Also I searched here people with the same error even someone who was following the same guide but their solution didn't help mine and it was the same project -
Python quit unexpectedly when going into admin page of django
I was trying to learn django framework (3.0) and was following the djangoproject poll sample and when I got to the steps of going to the admin page, safari pop up "Python quit unexpectedly", and the error report was as below: Can any one give me a help, please? Process: Python [93865] Path: /Library/Frameworks/Python.framework/Versions/3.7/Resources/Python.app/Contents/MacOS/Python Identifier: Python Version: 3.7.0 (3.7.0) Code Type: X86-64 (Native) Parent Process: Python [93863] Responsible: Terminal [55160] User ID: 501 Date/Time: 2020-07-14 02:07:32.777 +0800 OS Version: Mac OS X 10.15.5 (19F101) Report Version: 12 Bridge OS Version: 3.0 (14Y908) Anonymous UUID: AA9B8144-257A-A323-5B3A-C712A59D4CD9 Sleep/Wake UUID: BD0D8E7C-0239-4F70-AEEF-EB8EA465FF34 Time Awake Since Boot: 170000 seconds Time Since Wake: 3400 seconds System Integrity Protection: enabled Crashed Thread: 2 Exception Type: EXC_BAD_ACCESS (SIGSEGV) Exception Codes: EXC_I386_GPFLT Exception Note: EXC_CORPSE_NOTIFY Termination Signal: Segmentation fault: 11 Termination Reason: Namespace SIGNAL, Code 0xb Terminating Process: exc handler [93865] Thread 0:: Dispatch queue: com.apple.main-thread 0 libsystem_ kernel.dylib 0x00007fff6b2970fe __select + 10 1 org.python.python 0x000000010e603fc0 time_sleep + 128 2 org.python.python 0x000000010e4c0995 _PyMethodDef_RawFastCallKeywords + 757 3 org.python.python 0x000000010e4bfdba _PyCFunction_FastCallKeywords + 42 4 org.python.python 0x000000010e57f5ae call_function + 782 5 org.python.python 0x000000010e57c560 _PyEval_EvalFrameDefault + 2515 Thread 1: 0 libsystem_kernel.dylib 0x00007fff6b2953d6 poll + 10 1 select.cpython-37m-darwin.so 0x0000000105d81a12 poll_poll + 466 2 org.python.python … -
How does a relative/absolute path works in HttpResponseRedirect()?
Dears, I came across with the following paragraph. I have questions: 1 why URL and Path are used interchangeably? 2 What urls will be returned in these two cases? "an absolute path with no domain (e.g. '/search/'), or even a relative path (e.g. 'search/')" "class HttpResponseRedirect The first argument to the constructor is required – the path to redirect to. This can be a fully qualified URL (e.g. 'https://www.yahoo.com/search/'), an absolute path with no domain (e.g. '/search/'), or even a relative path (e.g. 'search/'). In that last case, the client browser will reconstruct the full URL itself according to the current path. See HttpResponse for other optional constructor arguments. Note that this returns an HTTP status code 302" -
how to pass invisible information in a POST form, using django?
Hi guys I am trying to create a chat website, but when I want to send a message I must use a tool to pass within the form of the message an invisible information that will contains the other user username to be able to send the message to him. NOTE: I am using django 3.0.8 for backend! Help pls -
Serializer complains about no attribute '_meta'
I'm running a Django query against the following table and I want to convert the resulting queryset to JSON: class City(models.Model): city = models.CharField(max_length=50) city_ascii = models.CharField(max_length=50) lat = models.FloatField(default=0.0) lng = models.FloatField(default=0.0) country = models.CharField(max_length=50) country_abbrev2 = models.CharField(max_length=2) country_abbrev3 = models.CharField(max_length=3) region = models.CharField(max_length=50) The query is trying to get a list of all of the cities in a given country 'country_abbrev' (without any duplicates): cities = City.objects.filter(country_abbrev2=country_abbrev).values('city').distinct() cities_json = serializers.serialize('json', cities) return HttpResponse(cities_json, content_type='application/json') The query returns this error: Error: AttributeError: 'dict' object has no attribute '_meta' Now this other query does work but it returns the 'model' and 'pk' fields in addition to the 'city' field and I don't want them. data = serializers.serialize('json', City.objects.filter(country_abbrev2=country_abbrev).distinct(), fields=('city')) return HttpResponse(data, content_type='application/json') Is there a way to fix the first query? Or is there a better way to do it? This query is in an API view and I really would like to just pass an array of values like ```['city1', 'city2', ... ] that my JavaScript can parse on the client side. -
Django Access Sum of Child Class Attributes
I'm a beginner working on a school fees management software with Django. My Problem is Below: I have two models, Student and Family: from django.db import models --snip-- class Family(models.Model): father = models.CharField(max_length=100) mother = models.CharField(max_length=100) total_fees = students.fees.aggregate(models.Sum('fees')) def __str__(self): return self.father+" " +self.mother class Student(models.Model): family = models.ForeignKey(Family, on_delete=models.CASCADE, related_name='students', default='') name = models.CharField(max_length=100) date_of_birth = models.DateField('Date Of Birth') fees = models.IntegerField(default=0) email= models.CharField(max_length=200) def __str__(self): return self.name Im trying to get all the total fees of a family by adding up the fees of all the students in the family: total_fees = students.fees.aggregate(models.Sum('fees')) I used the solution stated here. but i get this error when i try to migrate: File "/home/my_username/mysite/students_app/models.py", line 34, in Family total_fees = students.fees.aggregate(models.Sum('fees')) AttributeError: 'ForeignKey' object has no attribute 'fees' What is the correct way to get the total fees for a family? Thanks! PS: This is my first question, please tell me how I can improve my questions :) -
How to store a tuple of tuples using Django ORM?
I have a model that uses an IntegerChoices enumeration and I have another model that needs to store two integers for every possible choice (three, for example) and it also refers to the first model. I need to use these integers in some code in the first model. I know I can use six integer fields but I do not like the approach. Is there a way to store the data in a single field? -
Django app Deploy but after hosting error of gunicorn
error page 1 [1]: https://i.stack.imgur.com/qxyjY.jpg error page 2 [2] https://i.stack.imgur.com/sNv1g.jpg -
Javascript data overwritten by jinja rendered data
I'm trying to implement like-unlike functionality in a blog project. Initially the page shows data using Jinja2 template variable in html. When the user clicks the 'LIKE' link it calls a javascript function where the fetch function updates data on the back-end and gets the latest count of likes and like status and updates that data in html. Issue: The JavaScript is working fine, I can see that after the onClick function is executed, the like count increases and the value of anchor tag changes from 'Like' to 'Unlike'. But soon after it is set to unlike, it is overwritten by jinja data to 'like'. I'm not sure what I'm missing here, any help is very much appreciated. HTML code: ```<div class="media-body"> <div id="post{{post.id}}"> <h4><a class="article-title" href="{% url 'getProfile' post.get_userId %}">{{ post.user.username }}</a></h4> <div id='existing-post'> <p class="article-content">{{ post.content }}</p> <div class="article-metadata"> <small class="text-muted">{{ post.date_posted|date:"F d, Y" }}</small> <a href="">edit</a> <input type="hidden" class="hidden" id="userId" value={{user.id}}> </div> <i class="fa fa-heart" aria-hidden="true" style="color: red;"></i><span id="countEle"> {{ post.get_likes_count }}</span> <a href="" class="post{{post.id}}" onclick=changeLikes(this.className) > {% if user in post.get_likes %} Unlike {% else %} Like {% endif%}</a> </div> </div>``` JavaScript code: function changeLikes(clickedId){ divEle=document.getElementById(clickedId); likedBy= document.getElementById('userId').value; // id_value=this.id var likedBy =divEle.querySelector('#userId').value; postId=clickedId.substring(4) fetch('/changeLikes', { … -
How can I create a transparent image holder in django?
I am trying to create a transparent image holder in python. I then want to add images to the holder. When the image holder is display on a web page I want to see the images, but I want the holder to be transparent. Thus I will still be able to see the original page behind the image holder My Code is as follows def test_image(): image_holder = PilImage.new('RGBA', (800, 200), (255, 0, 0, 0)) test_image = PilImage.open('test_image.png') a_channel = PilImage.new('L', test_image.size, 255) test_image.putalpha(a_channel) image_holder.paste(test_image, (50, 100), test_image) image_holder.save('test_image_A.png') return test_image If I view the image in a web page it works perfectly <img src="my_imageA.png" width="800" height="232"> But if I pass the image through a django context, the image_holder appears as red context['test_image'] = test_image() What can I do? -
How to filter tasks by categories in django/boostrap?
I`ve been following this tutorial: https://medium.com/fbdevclagos/how-to-build-a-todo-app-with-django-17afdc4a8f8c to create a todo list. I would like to display each tasks by category. Usually, I am using filter in my views if I want to only display some boolean model. As the category is not defined initially, and is a character, how can I filter tasks based on the category whatever will be the name. (I am aware that the taskDelete function does not work and return an error) models.py class Category(models.Model): # The Category table name that inherits models.Model name = models.CharField(max_length=100) #Like a varchar class Meta: verbose_name = ("Category") verbose_name_plural = ("Categories") def __str__(self): return self.name #name to be shown when called class TodoList(models.Model): #Todolist able name that inherits models.Model title = models.CharField(max_length=250) # a varchar content = models.TextField(blank=True) # a text field comment = models.TextField(blank=True) # a text field created = models.DateField(default=timezone.now().strftime("%Y-%m-%d")) # a date due_date = models.DateField(default=timezone.now().strftime("%Y-%m-%d")) # a date category = models.ForeignKey(Category, on_delete=models.CASCADE, default="general") # a foreignkey complete = models.BooleanField(default=False) class Meta: ordering = ["-created"] #ordering by the created field def __str__(self): return self.title #name to be shown when called views.py def check_list(request): todos = TodoList.objects.all() #quering all todos with the object manager categories = Category.objects.all() #getting all … -
Django: How to nest two serializers in each other?
I want to nest the profile serializer in my story serializer to access username, user picture, etc. within the story. The profile serializer contains the user detail serializer to access the username, user ID, etc. The entire nesting therefore looks like this: User serializer -> profile serializer -> story serializer. But when I do this and retrieve a story, I get the error message: Got AttributeError when attempting to get a value for field `user` on serializer `ProfileSerializer`. The serializer field might be named incorrectly and not match any attribute or key on the `User` instance. Original exception text was: 'User' object has no attribute 'user'. I searched for possible solutions but they wehre not applicable for my situation. User Model: class User(AbstractUser): pass User Detail Serializer: class UserDetailSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('username','id', ) Profile Model: class Profile(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) image = models.ImageField(default='default.jpg', upload_to='profile_pics/') def __str__(self): return f'{self.user.username} Profile' Profile Serializer: class ProfileSerializer(serializers.ModelSerializer): user = UserDetailSerializer () class Meta: model = Profile fields = ('id', 'user', 'image', 'bio') Story Model: class Story (models.Model): title = models.CharField(max_length=100,blank=False) author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=True) def __str__(self): return self.title Story Serializer: class StoryRetrieveSerializer (serializers.ModelSerializer): author = ProfileSerializer () … -
Moltiplication between two different dictionary
I'm trying to get a moltiplication between two dictionary: quantita_materiale={'140cm* 2cm': [1.0]} prezzo_materiale={'140cm* 2cm': [100.0], '70cm* 2cm': [100.0],} I want to get a result variable as moltiplication for all key that match between the two dictionary. I have tried to get the following code: value={k : v * prezzo_materiale[k] for k, v in quantita_materiale.items() if k in prezzo_materiale} But python give me the following error: can't multiply sequence by non-int of type 'list' -
Django development server is not loading
I ran my server using python manage.py runserver and everything was fine. But things started to get slower and slower the more code I added to my project. Until one day the dev server just stopped loading. On my bottom right it would say Waiting for 127.0.0.1:1000 (My server address) and it just wouldn't load into the dev server. I tried deleting my migration folders and my sqlite3's and re-migrated everything and created a new superuser but it still won't load. Any fixes? -
Can't print the value of models.ManyToManyField always return None
I'm trying to print the Value of ManyToManyField but it always None, i have tried to use ForeignKey but it doesn't work will because i already have database with ManyToManyField {{order.product}} models class Product(models.Model): name = models.CharField(max_length=200, null=True) tags = models.ManyToManyField(Tags) def __str__(self): return self.name class Order(models.Model): customer = models.ForeignKey(Customer, null=True, on_delete=models.SET_NULL) product = models.ManyToManyField(Product, null=True) date_created = models.DateTimeField(auto_now_add=True) view def home(request): products = Product.objects.all() orders = Order.objects.all() context = {'total_orders': total_orders, 'total_products': total_products, 'Pending_order': Pending_order, 'Delivered_order': Delivered_order, 'customers': customers, 'orders': orders } return render(request, 'accounts/dashboard.html', context) html <tbody> {% for order in orders%} <tr> <th scope="row">{{order.id}}</th> <td>{{order.product}}</td> <td>{{order.date_created}}</td> <td>{{order.status}}</td> <td></td> <td></td> </tr> {% endfor %} </tbody> -
How to connect forms in django with each other?
People please help! I’ve been tormented with this all week. In general, I have two forms on one page, one form should automatically substitute the name of the block in which we are located (this one works), and the second should, depending on which block we are in the select, provide options for choosing categories of only this block. my views class AddTable(SuccessMessageMixin, CreateView): model = TableCategory form_class = TableCategoryForm second_form_class = TableItemsForm template_name = 'forms/table_add.html' success_url = '.' success_message = "Категория таблицы успешно добавленна" def get_initial(self): initial = super(AddTable, self).get_initial() initial['block'] = CreateBlock.objects.get(pk=self.kwargs['pk']) return initial def get_context_data(self, **kwargs): context = super(AddTable, self).get_context_data(**kwargs) context['tablecat'] = TableCategory.objects.filter(block=self.kwargs['pk']) context['tableitem'] = TableItems.objects.all() #if 'formcat' not in context: # context['formcat'] = self.form_class() if 'form2' not in context: context['form2'] = self.second_form_class() return context my models # tables models class TableCategory(models.Model): """ table category """ block = models.ForeignKey(CreateBlock, on_delete=models.CASCADE, related_name='blocktablecat', default=0) category = models.CharField(max_length=50) def __str__(self): return self.category class Meta: verbose_name = 'Категория таблицы' verbose_name_plural = 'Категории таблицы' class TableItems(models.Model): """ table items """ category = models.ForeignKey(TableCategory, related_name='tableitems', on_delete=models.PROTECT) name = models.CharField(max_length=50) price = models.SmallIntegerField(default=0) def __str__(self): return self.name class Meta: verbose_name = 'Содержимое таблицы' verbose_name_plural = 'Содержимое таблицы' class CreateBlock(models.Model): """ blocks """ user = … -
common Url for all the apps in django
I want your help, I am new in Django suppose I have 2 apps name 1. school 2. college The school app has its separate url.py and view.py file. If I want to show contact-us page, then I have to crate URL be like localhost://school/contact-us and there is separate view.py file in school app for handling view for "/contact-us" url 2, Now in college app there is also contact-us page and both school and college have the same contact us page. I don't want to write the same code again for the college app. It's increasing my code as well a time to develop a project, I am writing whole project HTML pages urls in every app. may I have more apps like medical college, etc so, is there any way to get this done. can you tell me have to write a single URL and view for the common page? -
random function on working in Django even though I imported it. local variable 'random' referenced before assignment
So im basically trying to render a random template, but it says that "local variable 'random' referenced before assignment", even though I imported random. this is my code at the top from django.shortcuts import render from . import util import markdown2 import random this is my logic def random(request): entries = [entry for entry in util.list_entries()] random = random.choice(entries) getentry = util.get_entry(random) return render(request, "encyclopedia/title.html", { "entryname": markdown2.markdown(getentry) }) -
Django datepicker inlineformset_factory
Good day, I am trying to make a form with a datepicker using Jquery. For some reason the datepicker does not pop up when I hover over the date field. Any ideas how to solve this issue? I used How to use Datepicker in django as a reference. Best wishes, Ted Models.py class Information(models.Model): title_choices = [ ('Mr', 'Mister'), ('Ms.', 'Miss'), ] title = models.CharField(max_length=100) first_name = models.CharField(max_length=100, default = '') last_name = models.CharField(max_length=100, default = '') date_posted = models.DateTimeField(default=timezone.now) titles = models.CharField( max_length = 3, choices = title_choices, default= '', ) # date_posted = models.DateTimeField(default=timezone.now) created_by = models.ForeignKey(User, related_name="collections", blank=True, null=True, on_delete=models.SET_NULL) def __str__(self): return str(self.id) class Debt(models.Model): """ A Class for Debt information. """ post = models.ForeignKey(Information, related_name="has_titles", on_delete=models.CASCADE) debt = models.CharField("Item", max_length=500) # period = models.CharField(max_length=100, default = '') period_start = models.DateField("Date",auto_now=False, blank = False, null = True) forms.py class DebtForm(forms.ModelForm): class Meta: model = Debt exclude = () DebtFormSet = inlineformset_factory( Information, Debt, form=DebtForm, fields=['debt', 'period_start'], extra=1, can_delete=True ) class PostForm(forms.ModelForm): class Meta: model = Information exclude = ['created_by', 'date_posted', ] widgets = { 'period_start': forms.DateInput(attrs={'class':'datepicker'}), } def __init__(self, *args, **kwargs): super(PostForm, self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_tag = True self.helper.form_class = 'form-horizontal' self.helper.label_class = 'col-md-3 … -
How to get a moltiplication between two queryset
I have the following queryset from django models: a= {'140cm* 2cm': [1.0], '70cm* 2cm': [1.0]} b= {'140cm* 2cm': [100.0]} I want to obtain c variable as the moltiplication between a and b for each equal elements. In this case: c={'140cm* 2cm': [100.0]} -
I had 'NoneType' object has no attribute 'groups' in django when I tried to save an user
I'm new in django, I have three groups in Admin: Medico, Paciente, Administrador. I just have the error, AttributeError at /registro/ 'NoneType' object has no attribute 'groups', but my form is saving all the data # Registro del Sistema def home_registro(request): if request.method == 'POST': formulario = PacienteFormulario(request.POST) if formulario.is_valid(): paciente = formulario.save() grupo = Group.objects.get(name='Paciente') paciente.groups.add(grupo) return render(request, 'home/home_confirmacion.html') else: formulario = PacienteFormulario() context = { 'formulario': formulario } return render(request, 'home/home_registro.html', context) form.py: class PacienteFormulario(UserCreationForm): class Meta: model = User fields = ('username', 'first_name', 'last_name', 'email', 'password1', 'password2') def save(self, commit = True): user = super().save(commit = False) user.email = self.cleaned_data['email'] user.first_name = self.cleaned_data['first_name'] user.last_name = self.cleaned_data['last_name'] if commit: user.save() Error: line 35, in home_registro paciente.groups.add(grupo) AttributeError: 'NoneType' object has no attribute 'groups' I hope someone can help me. Thanks -
How to mention users using @ in django
I have been working on a project on django and it is very similar to instagram and twitter, one of the functions it needs to have is to mention users using "@" in text fields. I have been investigation a little while now on how I can do that in django and I have found litteraly nothing except some libraries like django-mentions which I don't understand how it works but I have also found that this is possible using react but I don't know if it is possible to implement react to an almost finished django project. How can this function work? Should I use react or any javascript? models.py class Post(models.Model): text = models.CharField(max_length=200) user = models.ForeignKey(User, related_name='imageuser', on_delete=models.CASCADE, default='username') views.py (upload view contains the form that stores the post to later display it and main view displays the uploaded post) def upload(request): if request.method == 'POST': form = PostForm(request.POST, request.FILES) if form.is_valid(): instance = form.save(commit=False) instance.user = request.user instance.save() return redirect('home') print('succesfully uploded') else: form = PostForm() print('didnt upload') return render(request, 'home.html', {'form': form}) def main(request): contents = Post.objects.all() context = { "contents": contents, } print("nice2") return render(request, 'home.html', context) forms.py class PostForm(forms.ModelForm): class Meta: model = Post … -
How to prepopulate Django (non-Model) Form (how to pass the values list from view.py to the ChoiceField in the Form)?
I have read similar threads, but found nothing. The rest of my code works pretty well. The problem is here: I generate a list list_to_prepopulate_the_form1 consisting of 2x tuples in my views.py and need to pass this list to the form in forms.py views.py from django.http import HttpResponse, HttpRequest, HttpResponseRedirect from .models import * def n01_size_kss(request): if request.method == 'POST': form = KSS_Form(request.POST) context = {'form':form} if form.is_valid(): filtertype, context = n01_context_cleaned_data(form.cleaned_data) if filtertype != "none": list_to_prepopulate_the_form1 = prepare_dictionary_form2(context) form1 = KSS_Form1(initial={'list1'=list_to_prepopulate_the_form1}) context = {'form':form1, **context} return render(request, 'af/size/01_kss_size2.html', context) else: context = {'form':KSS_Form()} return render(request, 'af/size/01_kss_size1.html', context) forms.py from django import forms from django.conf.urls.i18n import i18n_patterns class KSS_Form1(forms.Form): druckstufe = forms.ChoiceField(\ required=True, \ label=_("Specify desired presure stage:"), \ initial="1", \ disabled=False, \ error_messages={'required':'Please specify desired pressure stage'}, \ choices = list1, ) What is the right way to do it? Thank you -
why get method jquery run twice when loading next page?
i need help in this code must return posts in second page and append them to $container, but when ( if ) condition is true , it returns posts twice like in next image. What could be wrong? $(window).off('scroll').on('scroll',function() { if($(window).scrollTop() + $(window).height() === $(document).height()) { var $more = $('.page-more-link') var $container = $('#time-line'); ///// Before loading new items //// $('.get-more-posts').hide(); $('.loading').show(); $.get($($more).attr('href'), $.proxy(function(data) { var $data = $($.parseHTML(data)); var $newMore = $data.find('.page-more-link'); var $items = $data.find('.post'); if (!$items.length) { $items = $data.filter('.post'); } $container.append($items); if (!$newMore.length) { $newMore = $data.filter('.page-more-link'); } if ($newMore.length) { $more.replaceWith($newMore) $more = $newMore } else { $more.remove(); } ///// After loading new items //// autosize_textarea(); $('.get-more-posts').show(); $('.loading').hide() /// count views of posts fun ///// countViews($($items).find('.post-body')); })) } });