Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to truncatechars of wagtail streamfield block?
After reading all the docs, I still don't know how to truncatechars of a wagtail streamfield blocks. {% for block in post.body %} {% if block.block_type == 'richtext' %} {{ block.value|truncatechars:100 }} {% endif %} {% endfor %} works with weird results depending on quantity of truncatechars - if it's definitely above the number of characters of all the streamfields, it displays everything (all) as expected; Now i'm putting 40 and it displays: First rich… third ric… fifth … (my text streamfields are "first richtext", "third richtext" and "fifth richtext" ; second and third blocks are pics successfully filtered out ) I think it could be fixed by adding all of the blocks into one for output, but I don't know how to do it. Do I iterate ? There's no "+" tag :/ -
Django RF, field level validation to check if requesting user is Admin
My Django Rest Framework project have models field where any authenticated users can create model instance. However I wanted to make sure that only Django Admin can change the accepted field value. What is the best way to prevent other users from changing the accepted field ? Pls note that I want to keep permission for authenticated users to create model instance keeping default accepted field. MODELS.PY class PO(models.Model): name = models.CharField(max_length=100) accepted=models.BooleanField(default=False) # I want this field to be changed only by admin user VIEWS.PY class POcreate(generics.CreateAPIView): queryset = PO.objects.all() serializer_class = POserializer permission_classes = [permissions.IsAuthenticated] SERIALIZER.PY class POserializer(serializers.ModelSerializer): class Meta: model=PO fields='__all__' -
how i can create form with two foreign key and user
I am creating a form for the order order class Order(models.Model): STATUS = ( ('Pending', 'Pending'), ('Out for delivery', 'Out for delivery'), ('Delivered', 'Delivered'), ) shop = models.ForeignKey(Shop, models.CASCADE, null=True) customer = models.ForeignKey(Customer, models.CASCADE, null=True) product = models.ForeignKey(Product, models.CASCADE, null=True) quantity = models.CharField(max_length=30, null=True, ) date_created = models.DateTimeField(auto_now_add=True, null=True) status = models.CharField(max_length=200, null=True, choices=STATUS, default='Pending') note = models.CharField(max_length=1000, null=True) and I have created on views.py def CreateOrder(request, shop_id, product_id): customer = request.user.customer shop = Shop.objects.get(id=shop_id) product = Product.objects.get(id=product_id) how I create remaining form of the views.py and my HTML href href="{% url 'CreateOrder' i.shop.id i.id %}" -
django.core.exceptions.ImproperlyConfigured: The included URLconf 'online_chat.urls' does not appear to have any patterns in it
I have this error and I don't know where it comes from, I have read similar questions on stack-overflow but nothing since to work for me. Could you please tell me why I get this error? That's the full error settings.py ROOT_URLCONF = 'online_chat.urls' urls.py urlpatterns = [ path('secret-chamber/', admin.site.urls), path('', Index.as_view(), name='home_page'), path('login/', LoginView.as_view(template_name='core/login.html'), name='log_in'), path('logout/', LogoutView.as_view(next_page='/'), name='log_out'), path('registration/', Registration.as_view(), name='registration'), path('contact-us/', ContactUs.as_view(), name='contact_us'), path('our-rules/', Rules.as_view(), name='our_rules'), path('user-page/', UserProfilePage.as_view(), name='user_page'), path('change-password/', ChangePassword.as_view(), name='change_password'), path('user-page/add-photos/', AddPhotos.as_view(), name='add_photos'), path('user-page/find-date/', FindDate.as_view(), name='find_date'), path('user-page/delete-image/<int:pk>/', DeletePhoto.as_view(), name='delete_photo'), path('user-page/edit/<int:id>/', EditUserProfile.as_view(), name='edit_page'), path('detail/<int:pk>/', ProfileSearch.as_view(), name='search_profile'), path('report/<int:pk>/', ReportMessage.as_view(), name='report'), path('api-auth/', include('rest_framework.urls')), path('api/v1/', include(router.urls)), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) Thank you for any help! -
OneToOneField throwing error that field does not exist, when it should not need to exist
I'm trying to create a one to one relationship between two models. My models.py is: class Store(models.Model): store_name = models.CharField(max_length=200) store_description = models.CharField(max_length=200) class Manager(models.Model): first_name = models.CharField(max_length=200) last_name = models.CharField(max_length=200) manager_email = models.EmailField(max_length = 254) store = models.OneToOneField(Store, on_delete=models.CASCADE) A can run makemigrations and migrate without issue, and I added both these models to admins.py When I try to create a new Manager record, I get an AttributeError that: 'Manager' object has no attribute 'store_name' Why is this being thrown? Why would store_name have to be a field in my Manager model? -
To and From return the same email id in django send_mai()
Views.py def contact(request): if request.method == 'POST': message_name = request.POST['message-name'] message_email = request.POST['message-email'] message = request.POST['message'] # send an email send_mail( 'Message from ' + message_name, # subject message, # message message_email, # from email ['myEmailId@gmail.com'], # to email ) settings.py EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_HOST_USER = 'myEmailId@gmail.com' EMAIL_HOST_PASSWORD = '<myaccount app password>' EMAIL_USE_TLS = True contact.html <form action="{% url 'contact' %}" method="POST" class="bg-light p-5 contact-form"> {% csrf_token %} <div class="form-group"> <input type="text" name="message-name" class="form-control" placeholder="Your Name"> </div> <div class="form-group"> <input type="email" name="message-email" class="form-control" placeholder="Your Email"> </div> <div class="form-group"> <textarea name="message" id="" cols="30" rows="7" class="form-control" placeholder="Message"> </textarea> </div> <div class="form-group"> <input type="submit" value="Send Message" class="btn btn-primary py-3 px-5"> </div> </form> i have created this code for the contact-me page. Now when user Submits the Contact Form which has the fields message-name, message-email and message, I receive the email where FROM and TO are both my email-id. It is not retrieving the users email. But rest of the fields are working fine. Even Tested with DebuggingServer and that works as expected. Seems like i am missing something in the setting.py because that is the one file i have changed. I don't understand where i am going wrong. Any help … -
Can not load css from global static Django
I set static folder to my project dir not in an app. my_project |-app1 |-template |-app1 |-base.html |-my_project |-manage.py |-static |-css |-style.css settings.py STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'oculus_website/static') ] base.html {% load static %} <link rel=”stylesheet” type="text/css" href='{% static "css/styles.css" %}'> thank you. -
ANDROID VOLLEY + DJANGO REST FRAMEWORK
I am having an issue regarding sending a post request to my backend. Currently, I am using django rest framework in my backend and sending the request via android app(frontend). I am using Android's volley library to do this. However, everytime I try to make a post request, there would always be an error message, saying 'E/Volley: [1826] BasicNetwork.performRequest: Unexpected response code 400 for http://172.31.120.129:8000/account/register/' Does anybody has ever encounter this issue before? I have look up for solutions online and none of them solve my problem here Below is my Register.java package com.example.orbital; import androidx.appcompat.app.AppCompatActivity; import android.content.Intent; import android.content.res.ColorStateList; import android.os.Bundle; import android.text.TextUtils; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; import androidx.appcompat.widget.Toolbar; import com.android.volley.AuthFailureError; import com.android.volley.Request; import com.android.volley.RequestQueue; import com.android.volley.Response; import com.android.volley.VolleyError; import com.android.volley.toolbox.JsonObjectRequest; import com.android.volley.toolbox.StringRequest; import com.android.volley.toolbox.Volley; import java.util.HashMap; import java.util.Map; public class RegisterActivity extends AppCompatActivity { EditText enterPassword,enterConfirmPassword,firstName,lastName,email,phoneNumber; TextView passWord,confirmPassWord; Button registerBtn; static String passwordSaved,firstNameSaved,lastNameSaved,emailSaved,phoneNumberSaved; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_register); initialiseFields(); //Instantiate RequestQueue registerBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { savedCredentials(); sendUserToRegister2Activity(); } }); } private void savedCredentials() { firstNameSaved = firstName.getText().toString().trim(); lastNameSaved = lastName.getText().toString().trim(); emailSaved = email.getText().toString().trim(); passwordSaved = enterPassword.getText().toString().trim(); phoneNumberSaved = phoneNumber.getText().toString().trim(); } // private … -
Datatables for personal use
I am making a project for a friend of mine who runs a dental clinic. The project is about managing appointments, adding customer etc. The project is in Django and I used Jquery Datatables plugin in the project..I am planning to deploy the project on web so he could access the patients info add/edit anytime anywhere he wants. However will this be violating the policy of Datatables plugin? Since i don't have the purchased license. -
Djanog - How to improve structuring of multiple store business vs single store business user for application?
My software application is available for a single store business and for a business with multiple stores. Currently I am maintaining essentially duplicate views, duplicate html pages, and duplicate urls for every view I create, one for multi store businesses and one for single store businesses. Doing this was what I felt was simplest solution to my problem. However it has created alot of duplicate content. How can existing structure be modified and improved on? Currently my code upon login looks as follows: /store/ store.html and using views.store: {% if store_number == 1: %} <form> <input> <button type="submit"> </form> {% endif %} {% if store_number > 1: %} {% for store in stores %} <h5><a href="{% url 'store_multi' storeid=store.id %}">{{ store.name }}</a></h5> {% endfor %} {% endif %} /store/<int:storeid>/ store_multi.html and using views.store_multi: <form> <input> <button type="submit"> </form> -
Is It Safe To Store Files Using The Same Names As They Are Displayed To Users
On a page on my website users can view files uploaded by other users. They can also view AND download their own files. This is done with the following link: <a href="{% url 'download_users_file' file_path=file.name %}" target='_blank'>{{ file.name }}</a> And executed through the view: def get(self, request, *args, **kwargs): path = self.kwargs['file_path'] file_path = os.path.join(settings.MEDIA_ROOT+'/'+path) if os.path.exists(file_path): with open(file_path, 'rb') as fh: response = HttpResponse(fh.read(), content_type="application/pdf") response['Content-Disposition'] = 'inline; filename=' + os.path.basename(file_path) return response raise Http404 The name of the file which users see when viewing the page is the same name they are saved as in the db, and that same name is passed to the get function when retrieving the file. IE: Filename as displayed on the website: test_file Filename as saved in the db: media/users_files/test_file.pdf Kwargs sent when user downloads file: file_path='test_file' Is this a security vulnerability? Could a malicious user with a little know-how notice this then simply change the kwargs sent in the get request and download other user's files? Thank you. -
You have an error in your MySQL sintax in Django
I'm trying to execute a simple MySQL query that will work on MySQL, while it gives any kind of error on Django. The (expected) output i get on MySQL is the following: ndate query_count 26/06/20 10 25/06/20 4 24/06/20 9 ... Here is the query: Summary = myTable.objects.raw("select FROM_UNIXTIME(unixtime, '%%Y/%%m/%%d') as ndate,count(id) as query_count from myTable group by ndate order by query_count DESC") This line will give me the following error: Raw query must include the primary key But if i edit the query to the following: select id FROM_UNIXITIME.... I will get the following error: (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '(unixtime, '%Y/%m/%d') as ndate,count(id) as query_count from myTable' at line 1") And here is my model: class myTable(models.Model): user_id = models.IntegerField() username = models.CharField(max_length=150) query = models.CharField(max_length=100) unixtime = models.IntegerField() class Meta: managed = False db_table = 'mytable' The query, basically, should only count how many rows there are for this table every day and give the following output: {'2020/06/28': 30, '2020/06/27': 20 ... }. Can anyone help me out on how to make the query work, or … -
Django Rest Serializer validate gives Invalid pk
I have this situation: Model class Handling(models.Model): STATUS = ( ('Active', 'Active'), ('Archived', 'Archived'), ) entdate = models.DateTimeField(auto_now_add=True, null=True) extdate = models.DateTimeField(auto_now_add=True, null=True) kpallet = models.ForeignKey(Pallet, related_name='kpallet', null=True, on_delete= models.PROTECT) kitem = models.ForeignKey(Item,related_name='kitems', null=True, on_delete= models.PROTECT, limit_choices_to={'kstatus': 'Active'}) quantity = models.SmallIntegerField(null=True) kstatus = models.CharField(max_length=20, null=True, choices=STATUS) def __str__(self): return str(self.kpallet) Serializer: class HandlingSerializer(serializers.ModelSerializer): class Meta: model = Handling fields = '__all__' Api: @api_view(['POST']) @permission_classes((permissions.AllowAny,)) def handlingCreate(request): serializer = HandlingSerializer(data=request.data) if serializer.is_valid(): serializer.save() else: print(serializer.errors); return Response("Error Handling not created") return Response("Handling Created") I get this error and i don't understand how to move on: {'kitem': [ErrorDetail(string='Invalid pk "958c2fd2-bbb6-42d6-8bfe-fbe035e9ceb5" - object does not exist.', code='does_not_exist')]} I've checked the pk and the object exists so I don't understand where the issue could be. Thanks for your help in advance. -
Extract the sum in JSON of a given date range?
Given a JSON that looks like this: { "timesheets": [ { "user": { "username": "erik", "first_name": "Erik", }, "project_id": 4, "calc_full_week": { "2020-06-22": 5, "2020-06-23": 10, "2020-06-24": 8, "2020-06-25": 8, "2020-06-26": null, "2020-06-27": null, "2020-06-28": null } }, { "user": { "username": "erik", "first_name": "Erik", }, "project_id": 4, "calc_full_week": { "2020-06-29": 8, "2020-06-30": 10, "2020-07-01": null, "2020-07-02": null, "2020-07-03": null, "2020-07-04": null, "2020-07-05": null } }, { "user": { "username": "rawwe", "first_name": "joey", }, "project_id": 4, "calc_full_week": { "2020-06-22": 3, "2020-06-23": 10.4, "2020-06-24": 8, "2020-06-25": 8, "2020-06-26": 8, "2020-06-27": 8, "2020-06-28": 5 } } ] } How can I efficiently extract the sum of the dates for a given range? E.g, if I provide the range 2020-06-25 - 2020-07-03 I want to to get the sum of all values that fit that range. Not sure if I should do the calculations on the backend (django) or with javascript on the client side. -
ModuleNotFoundError: No module named 'praw'
I am trying to make a website with Django that can get Reddit user's data with a module called PRAW In my views.py for the app called Data, I tried to import PRAW and do things with it and template things with Django. I am using PyCharm, so the module PRAW has already been installed in my VirtualEnv. There were no errors importing PRAW in the file alone as well. (I ran the file directly in PyCharm and no error showed up) However, when I run the server, I get: ModuleNotFoundError: No module named 'praw' Imports made in views.py from django.shortcuts import render, redirect import praw Something wrong happens with the import praw statement when server is ran for some reason. Thanks in advance. -
Removing a product row from cart once quantity hits zero using Django python or javascript
this is the HTML for my product list in my cart <div class="my-5 mx-2"> <div class="box-element"> <div class="row text-center"> <div class="col-2"></div> <div class="col-2"> <h4 id="PN">Name</h4> </div> <div class="col-3"> <h4 id="PN">Quantity</h4> </div> <div class="col-3"> <h4 id="PN">Price</h4> </div> <div class="col-2"> <h4 id="PN">Total</h4> </div> </div> <hr> {%for item in items%} <!--list starts--> <div class="row remover "> <div class="col-2 text-center"><img src="{{item.product.imageURL}}" width="100%"></div> <div class="col-2 text-center"> <h4 id="PN">{{item.product.name}}</h4> </div> <div class="col-3"> <div class="row"> <div class="col-6 text-right"> <i data-product={{item.product.id}} data-action="add" class="fa fa-arrow-up updater chg-quantity"></i><br> <i data-product={{item.product.id}} data-action="remove" class="fa fa-arrow-down updater chg-quantity"></i> </div> <div class="col-6 text-left"> <h4 class="mt-3 inserter1" id="PN">{{item.quantity}}</h4> </div> </div> </div> <div class="col-3 text-center"> <h4 class="inserter3" id="numbers">{{item.product.price|floatformat:2}}</h4> </div> <div class="col-2 text-center"> <h4 class="inserter2" id="numbers">{{item.TFEP|floatformat:2}}</h4> </div> </div> <hr> {%endfor%} <!--list ends--> </div> This is the JavaScript i am using to update quantities.SORRY its long i cant shorten it as its all interlinked. //QC= quantity changer function QC() { //console.log("QC running") let url = `http://127.0.0.1:8000/API/specific_orderitems_api/${orderId}/` fetch(url) .then((response) => response.json()) .then((data) => { //console.log("data5:", data) storer1(data) //console.log("QC not running") }) } function storer1(data) { c = data for (let i in c) { quantity = c[i]["quantity"] document.getElementsByClassName("inserter1")[i].innerHTML = quantity storer2 } } //total for each product //TFEP changer function storer2(data) { c = data for (i in c) … -
wagtail or django contribute after test it locally
I am trying to develop a new feature for wagtail but I am going through an issue to understand how can I test it locally. For example, I have a wagtail/django porject in my local machine and run it with installing wagtail or django or whatever in virtual enviroment. I am trying to figure out how can run the project without installing a wagtail or django, just want to clone the wagtail or django repo and i want to put it somewhere so that my project can import all the things from there? I am very new to contributing opensource project and i am finding a proper way to test and develop opensource project. I read this but it doesn't help me what I wanted: https://docs.wagtail.io/en/latest/contributing/developing.html#setting-up-the-wagtail-codebase can anyone help me in this? -
Is there any way to iterate over list inside list in django template?
I have a list a = [[1000,3000], [4000-5000]], i would like to show it has 1000-3000 4000-5000 in template. But i'm getting only the first object. What i tried is, products.html {% for i in price_group %} <label> <input class="uk-radio" type="radio" onchange="$('#form').submit();" name="price" value="{{ i.0.0 }};{{ i.0.1 }};price;first" checked> {{ i.0.0 }} - {{ i.0.1 }} </label> {{ price_group.pop.i }} {% endfor %} I used pop functionality to remove current from the list and take the next one, but it's not working as expected. it is showing only the first element in the list. Please correct me if I am wrong. What I want is it has a price range like. 1000-3000 4000-5000..like wise. Please help me. -
Saving Django models data to Database for derived class
I have below models class Student(models.Model): fname=models.CharField(max_length=100) mname=models.CharField(max_length=100) lname=models.CharField(max_length=100) dob=models.DateField() class StudentDetail(Student): Subject=models.CharField(max_length=50) marks=models.IntegerField() I am able to create Student objects. I try to add StudentDetail as below student=Student() student.fname='fname text' student.lname='lname text' student.mname='mname text' student.dob='2020-01-01' student.save() detail1=StudentDetail() detail1.address='Address text' detail1.student=student detail1.save() the last statement gives error. How to save StudentDetail in database. -
I am tring to delete ToDo Item but its not working
I’m unable to delete a newly added item in my todo list. Below is my django code. Here is my templates.html. Here is my models.py. Here is my urls.py. Here is my views.py. -
How to get all fields with filtering on the related set in django?
I have Three model defined. I want to filter Get specific user and get all related fields in the result set. For example, I want to get supplierInfo and company info of that user. class User(AbstractBaseUser): user_email= models.EmailField(unique=True, max_length=254) user_id = models.AutoField(primary_key=True) staff=models.BooleanField(default=True) admin=models.BooleanField(default=True) role_id=models.IntegerField(default=0) supplier=models.ForeignKey(Supplier, on_delete=models.CASCADE) .... class Company(models.Model): company_name= models.CharField(('company name'), max_length=255, blank=True) company_id = models.AutoField(primary_key=True) class Meta: verbose_name = ('company') verbose_name_plural = ('company') db_table = "company" def __str__(self): return self.company_name class Supplier(models.Model): supplier_name= models.CharField(('supplier name'), max_length=255, blank=True) supplier_id = models.AutoField(primary_key=True) company=models.ForeignKey(Company, on_delete=models.CASCADE) class Meta: verbose_name = ('supplier') verbose_name_plural = ('supplier') db_table = "supplier" def __str__(self): return self.supplier_name I Have tried this userInfo=User.objects.filter(user_id__exact=user.user_id).get() userRelated= Supplier.objects.filter(supplier_id__exact=userInfo.supplier_id).get() companyRelated=Company.objects.filter(company_id__exact=userRelated.company_id).get() I am getting expected result But I dont think it is the best way. I want to merge three queries and get the result in one object . I am new in django so please help me out. -
How to display files of other format (.docx/.pdf/.txt) in Django templates
I am trying to show files that are uploaded in a Django Template.My model is as follows class FileUpload(models.Model): id = models.AutoField(primary_key=True,auto_created=True) user = models.CharField(max_length=64) date = models.DateField(auto_now=True, db_index=True) time = models.TimeField(auto_now=True) text = models.TextField() image = models.ImageField(blank=True,null=True,upload_to='images') document = models.FileField(blank=True,upload_to='files') When I uploaded the file I can display it in another tab using admin If the file is an image then it can be shown using the img tag but what is the correct syntax and HTML tag for displaying the file in a Django template. -
How to get or create objects in another model while updating some model?
I have a select2 option to select the reporters in my form. User randomly puts the reporters name in the news create form and while saving the form it also creates the reporter objects and assign these objects in News reporters(many to many ) field. This works fine while creating the objects While updating it got some issues.In the update form there will be the reporters which are already assigned in the news.And user can add reporters and also can remove the reporters from the form. Here if user add the new reporter in the form then I want to create reporter object and assign the reporter object in many to many field and so if the user removes some reporter. But this code creates reporter object even if it is already created and assigned in the News object. I want to check if the reporter is already in the News then i don't want to create object in the Reporter model .If only user add new reporter then I want to create reporter object in Reporter model and then assign this object in News. How can I do it ? class UpdateNews(View): template_name = 'update_news.html' categories = NewsCategory.objects.order_by('-created') def … -
List of groups returns empty after validation - Django REST framework
I tried several ways to make this work and I couldn't. It is very likely, because I believe it should be working. I may be missing something that I am not aware of. I thank you for your attention. request.data {'first_name': 'Marcelo', 'last_name': 'Wanderley', 'username': 'marcelo', 'cpf': '1234', 'telefone': '99999999', 'email': 'marceloa@teste.com', 'observacao': '', 'groups': [{'id': 2},{'id': 4}], 'password': '111111', 'password_again': '111111', 'token_user_chain': 'TMWTIeGs2t1YPpKke2RZh2tLVMuMWdLFxaFYdD', 'private_key': ''} 'groups': [{'id': 2},{'id': 4}] View if serializer.is_valid(): serializer.create(validated_data=serializer.validated_data) return Response(serializer.data, status=HTTP_201_CREATED) return Response(serializer.errors, status=HTTP_400_BAD_REQUEST) Model class GroupSerializer(serializers.ModelSerializer): class Meta: model = Group fields = ('id',) class serializerUser(serializers.Serializer): class Meta: model = User id = serializers.PrimaryKeyRelatedField(read_only=True) first_name = serializers.CharField() last_name = serializers.CharField() email = serializers.CharField(validators=[UniqueValidator(queryset=User.objects.all())]) cpf = serializers.CharField(validators=[UniqueValidator(queryset=User.objects.all())]) token_user_chain = serializers.CharField(validators=[UniqueValidator(queryset=User.objects.all())]) telefone = serializers.CharField() groups = GroupSerializer(many=True) observacao = serializers.CharField(allow_null=True, allow_blank=True) password = serializers.CharField(write_only=True) username = serializers.CharField(write_only=True,validators=[UniqueValidator(queryset=User.objects.all())]) password_again = serializers.CharField(write_only=True) Output Print OrderedDict([('first_name', 'Marcelo'), ('last_name', 'Wanderley'), ('email', 'marcelo@teste.com'), ('cpf', '123'), ('token_user_chain', 'TMWTIeGs2vpH7DGCYNiSCttdirrMqPFEgPnczA'), ('telefone', '999999'), ('groups', [OrderedDict(), OrderedDict()]), ('observacao', ''), ('password', '999999'), ('username', 'Marcelo Wanderley'), ('password_again', '999999')]) ('groups', [OrderedDict(), OrderedDict()]) -
Ajax call not working when I modify the html dynamically
I am building a twitter like app. Attaching a reference of the image here: Take a look at how the app looks The ajax call is not working instead it takes to the action_url page,when the function updateHashLinks() is called after parseTweets() inside function fetchTweets(url) and attachTweet(data, true) inside the ajax call. But if I comment the updateHashLinks() at both places the ajax call is working perfectly. The updateHashLinks() is basically used to add a href tag dynamically to the hashed words like(#Twitter). The html code which I am using is: <div class='row'> <div class='col-sm-3 col-xs-12 text-center' style='background-color: gray; height: 30px;'> <h6>{{ request.user }}</h6> </div> <div class='col-sm-9 text-center'> {% if not request.GET.q %} <div class="media-body text-left"> {% include "tweets/form.html" with form=create_form action_url=create_url btn_title='Tweet' form_id='tweet-form' %} </div> {% endif %} <div id='tweet-container'> </div> <a href='#' id=loadmore>Load More Tweets</a> </div> </div> The Functions Which are Used are: function updateHashLinks() { $(".media-body").each(function (data) { //data.preventDefault() // console.log(this) var hashtagRegex = /(^|\s)#([\w\d-]+)/g var newText = $(this).html().replace(hashtagRegex, '$1 <a href="/tags/$2/">#$2</a>') console.log("-------------------------") console.log(newText) $(this).html(newText) }) } function attachTweet(value, prepend) { console.log("attachtweet") var tweetContent = value.content // console.log(tweetContent) var tweetUser = value.user var dateDisplay = value.date_display // console.log(tweetUser.url) var tweetHtml = "<div class=\"media\"><div class=\"media-body\">" + tweetContent + …